guenhter
guenhter

Reputation: 12177

Changing an immutable data structure from two threads

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 }
        }
    }
}

Upvotes: 1

Views: 77

Answers (1)

nhaarman
nhaarman

Reputation: 100438

Immutable data structures can not be mutated - it's in the name. That means there are no methods on it that modify its state. If there are, it's not immutable. Thus, your EventReceiver is not immutable and you need to design for data races to make it thread safe.

One of the ways to make data structures thread safe is using locks to guard access to the contested properties, such as using synchronized like you're doing here.

Upvotes: 2

Related Questions