'Manipulating list in thread safe way

I've a set of listeners that class can be accessed to by classes to add themselves or remove themselves from the set.

private val set = mutableSetOf()

fun register(listener: Listener) {
    set.add(listener)
}

fun unregister(listener: Listener) {
    set.remove(listener)
}

private fun notifyListeners() {
   set.foreach{
      it.notify()
   }
}

If a class removes itself from the set while notifyListener() is iterating over the set, it can result in a race condition. What's the best way to avoid race condition? How can this code be improved?



Solution 1:[1]

I'd suggest simply using CopyOnWriteArrayList and only resorting to a custom synchronization implementation if performance is unsatisfactory (the documentation mentions that making copies of data on every mutation can be costly).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Egor