Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashmap simultaneous write and get operations

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.

like image 302
Bilbo Avatar asked Oct 24 '16 07:10

Bilbo


2 Answers

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.

like image 158
mhasan Avatar answered Sep 30 '22 10:09

mhasan


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

like image 41
Tinwor Avatar answered Sep 30 '22 09:09

Tinwor