You can use ConcurrentLinkedQueue
of Java. The following solution supports concurrency, in a way that if you add objects, while retrieving the history, they will be added to the history, and to the result of the current call. However, they are read once in this solution. If you need to stop adding while retrieving the history, we can think about a different solution. Consider having the History class as follows:
case class History() {
private val _events = new ConcurrentLinkedQueue[Event]()
def add(event: Event): Unit = _events.add(event)
def events: List[Event] = {
if (_events.isEmpty) {
List()
} else {
_events.poll() +: events
}
}
}
Then, when running the following code:
def main(args: Array[String]): Unit = {
val h = History()
List(
Event(10),
Event(20),
Event(30)
).foreach(h.add)
println(s"Events are: ${h.events.mkString(", ")}")
println(s"Events are: ${h.events.mkString(", ")}")
}
The output is:
Events are: Event(10), Event(20), Event(30)
Events are:
Process finished with exit code 0