I am trying to find answer to these, but not able to find it on Google or in Java docs.
Case 1: in ConcurrentHashMap
, suppose a thread t1 is reading from segment n, and at same another thread t2 want to write on the same segment n:
Question 1: will these two operations will be one after another, or they will execute simultaneously?
Case 2: in ConcurrentHashMap
, suppose a thread t1 is writing on segment n, and at same another thread t2 want to read from the same segment n,
Question 2: will these two operations will be one after another, or they will execute simultaneously?
I think javadoc answers both your questions:
Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.
Segments are for update operations:
The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default 16), which is used as a hint for internal sizing.
So, in short, reads are not blocked (it is implemented as reading volatile variables). Writes could block each other if they write in the same segment.