Reputation: 2135
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?
Upvotes: 0
Views: 182
Reputation: 116878
I just want to understand why do we really need thread safety with collections?
We need thread safety with any object that is being modified. Period. If two threads are sharing the same object and one thread makes a modification, there is no guarantee that the update to the object will be seen by the other thread and there are possibilities that the object may be partially updated causing exceptions, hangs, or other unexpected results.
One of the speedups that is gained with threads is local CPU cached memory. Each thread running in a CPU has local cached memory that is much faster than system memory. The cache is used as much as possible for high speed calculations and then invalidated or flushed to system memory when necessary. Without locking and memory synchronization, each thread could be working with invalid memory and could experience race conditions.
This is why threaded programs need to use concurrent collections (think ConcurrentHashMap
) or protect collections (or any mutable object) using synchronized
locks or other mechanisms. These ensure that the objects can't be modified at the same time and ensure that the modifications are published between threads appropriately.
Upvotes: 0
Reputation: 20455
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 of the reason outside of scope of this discussion changes made in one thread may not be visible in another.
Upvotes: 1
Reputation: 198103
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
.)
Upvotes: 1