Why this matters
Collections.synchronizedMaplooks like the answer and is usually the wrong one, for two separate reasons.- Making each call atomic does not make a sequence of calls atomic, and that gap causes bugs that pass every single-threaded test.
ConcurrentHashMapis a standard interview topic, and the segment-to-node-locking change in Java 8 is the detail that distinguishes a current answer.
The problem with wrapping
Every method acquires the same lock on the whole map. Two threads reading unrelated keys block each other for no reason. Under contention this becomes the bottleneck of the application.
The second problem is worse, because it is silent:
Both threads see "absent" and both write. Making individual calls thread-safe does nothing for a
check-then-act sequence — you would still have to wrap the whole block in synchronized, at which point
the wrapper has bought you nothing.
ConcurrentHashMap
How it achieves concurrency
- Reads are lock-free. The table and node fields are
volatile, so a reader sees a consistent value with no synchronisation at all. - Writes lock one bucket.
synchronizedon the head node of that bucket means writes to different buckets proceed in parallel. - Resizing is cooperative. Multiple threads help transfer entries rather than one blocking the rest.
- Size is tracked with striped counters — an array of cells, so incrementing does not become a contention point.
Before Java 8 it used segment locking: the table was divided into 16 independently locked segments, giving a concurrency level of 16. Java 8 replaced that with per-node locking, so the effective concurrency is the number of buckets rather than a fixed 16.
Atomic compound operations
This is the practical reason to use it: the check-then-act gap is closed by single atomic calls.
LongAdder spreads increments across several internal cells, so threads rarely contend. Under heavy
concurrent writes it substantially outperforms AtomicLong, which has every thread competing on one
field.
No nulls
ConcurrentHashMap rejects null keys and values. The reason is that get returning null would be
ambiguous — absent, or present with a null value — and you cannot resolve the ambiguity with
containsKey because another thread may change the answer between the two calls.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 4 sections
- The rest of the family
- Weakly consistent iteration
- Choosing
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.