I have a question about ConcurrentHashMaps. Lets say I have 2 threads. Thread A tries to get an object from a shared ConcurrentHashMap. Thread B clears the shared map. What happens if Thread A and Thread B access the shared resource simultaneously, at the very same time. I searched the documentation and the web and can't find a definitive answer, also tried to do it myself but to no avail.
ConcurrentHashMap is divided into different segments based on concurrency level. So different threads can access different segments concurrently in java.
Can threads read the segment of ConcurrentHashMap locked by some other thread in java?
Yes. When thread locks one segment for updation it does not block it for retrieval (done by get method) hence some other thread can read the segment (by get method), but it will be able to read the data before locking.
For operations such as putAll concurrent retrievals may reflect removal of only some entries. For operations such as clear concurrent retrievals may reflect removal of only some entries.
The documentation is quite clear about this case:
Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
So if the two threads use the resource at the same time but one is reading and the other one is updating you could read a resource that is not available.
For more info check the documentation paragraph 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With