I use immutable data-structures as much as possible, because it's really easy to work with them. The problem though is when two threads modify the data-structure. In that case, the synchronized
keyworks helped, but isn't one reason for immutable data-structures, to avoid synchroinzed
?
What is the more idemoatic way to modify a immutable list from two threads?
data class MyEvent(val time: Long, val somethingElse: String)
class EventReceiver {
private var events = listOf<MyEvent>()
// called several times a second
fun addEvent(e: MyEvent) {
synchronized(this) {
events += e
}
}
// internal cron-trigger calls this every 10 seconds
fun purge(olderThan: Long) {
synchronized(this) {
events = events.filter { it.time < olderThan }
}
}
}