How does ConcurrentHashMap work internally?

ConcurrentHashMap is a thread-safe hash map designed to allow high concurrency by avoiding a single lock over the whole map, instead using fine-grained internal locking so multiple threads can read and write different parts of the map at the same time.

Key Points: • In Java 7 and earlier, it partitioned the map into a fixed number of segments, each independently lockable, so writes to different segments didn't contend. • Since Java 8, the segment design was replaced with per-bin (per-bucket-node) locking using synchronized blocks on the first node of a bin, combined with CAS (compare-and-swap) operations for many updates. • Read operations (get()) are largely lock-free, relying on volatile reads of table entries, so readers rarely block behind writers. • When a bin gets too many collisions, Java 8+ ConcurrentHashMap converts the bin's linked list into a balanced tree (red-black tree) for better worst-case lookup performance. • It does not allow null keys or null values, unlike HashMap, specifically to avoid ambiguity in concurrent get() calls.

Example: Two threads updating different keys in a ConcurrentHashMap that happen to land in different bins can proceed in parallel with essentially no contention, whereas a synchronizedMap-wrapped HashMap would force one thread to wait for the other regardless of which keys are involved.

Interview Tip: A concise interview answer is:

"ConcurrentHashMap avoids one global lock by locking at the level of individual bins rather than the whole map, and since Java 8 it uses synchronized blocks on bin heads plus CAS operations for much of the update path, with mostly lock-free reads. That fine-grained approach is what makes it scale so much better than a synchronized HashMap under contention."