Home > Software design >  Why do we need thread safety with collections?
Why do we need thread safety with collections?

Time:10-19

I just want to understand why do we really need thread safety with collections? I know that if there are two threads and first thread is iterating over the collection and second thread is modifying the collection then first thread will get ConcurrentModificationException.

But then what if, if I know that none of my threads will iterate over the collection using an iterator, so does it means that thread safety is only needed because we want to allow other threads to iterator over the collection using an iterator? Are there any other reasons and usecases?

CodePudding user response:

I know that if there are two threads and first thread is iterating over the collection and second thread is modifying the collection then first thread will get ConcurrentModificationException.

That's not true. ConcurrentModificationException is for situation when your iterate thru collection and change it at the same time.

Thread safety is complex concept that includes several parts. It won't be easy to explain why we need it.

Main thing is because reason outside of scope of this discussion changes made in one thread may not be visible in another.

CodePudding user response:

Any sort of reading and any sort of writing in two different threads can cause issues if you're not using a thread safe collection.

Iterating is a kind of reading, but so are List.get, Set.contains, Map.get, and many other operations.

(Iterating is a case in which Java can easily detect thread safety issues -- though multiple threads are rarely the actual reason for ConcurrentModificationException.)

  • Related