Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How does ConcurrentHashMap achieve thread safety?
Modern ConcurrentHashMap (Java 8 onward) does not lock the entire map for every operation. Instead, it locks at the granularity of a single bin (bucket).
Inserting into an empty bin is done with a lock-free compare-and-swap; if a collision lands in a bin that already has a node, only that bin's first node is synchronized on while the chain (or, once it's long enough, a red-black tree) is updated. Reads generally proceed without any locking at all, relying on volatile reads of the table and node fields to see up-to-date values.
Resizing is handled cooperatively: multiple threads that touch the map during a resize help transfer entries to the new table segment by segment rather than one thread doing all the work while others block.
This fine-grained approach lets many threads read and write different bins truly in parallel, which is why ConcurrentHashMap scales far better under contention than a map wrapped in a single lock.
More Related questions...