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.