How does ConcurrentHashMap work internally in Java 8+?
Structure
Like HashMap: a table of bins that can be lists or red-black trees (TreeBin). Java 7's 16 fixed segments were removed; Java 8 locks at the level of individual bins.
Writes
- If the target bin is empty, the new node is inserted with a CAS, with no lock at all.
- If the bin is not empty, the thread synchronizes on the first node of that bin and updates it. Writers to different bins never block each other.
- During a resize, the table is split into ranges and writer threads help transfer bins to the new table. A moved bin is marked with a
ForwardingNode, so readers know to look in the new table.
Reads
get() takes no lock. It reads volatile fields (Node.val and next are volatile), so it sees completed writes.
Size and counting
size() sums a base counter plus an array of CounterCells (the same striping idea as LongAdder), so increments under contention do not all fight over one variable. The result is an estimate while updates are in flight; mappingCount() returns a long.
Atomic compound operations
putIfAbsent, computeIfAbsent, compute, merge are atomic per key. Use them instead of check-then-act sequences such as if (!map.containsKey(k)) map.put(k, v), which are races.
Example
ConcurrentHashMap<String, LongAdder> hits = new ConcurrentHashMap<>();
hits.computeIfAbsent(endpoint, k -> new LongAdder()).increment(); // atomic and contention-friendly
// Word count from many threads
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(word, 1, Integer::sum);Follow-up questions interviewers ask
Try answering each one before you open it.
Why does ConcurrentHashMap not allow null keys or values?
Ambiguity. In a concurrent map, get(k) == null could mean "absent" or "mapped to null", and you cannot follow up with containsKey(k) atomically because another thread may change the map in between. Banning nulls makes null unambiguously mean "absent", which putIfAbsent, compute and friends rely on.
What are the pitfalls of computeIfAbsent?
The mapping function runs while the bin is locked, so it must be short and must not modify the same map. Recursive updates can deadlock or throw IllegalStateException("Recursive update"). Do not call slow remote services inside it; that blocks every writer for that bin. For expensive loading with expiry, use a cache library such as Caffeine, which handles this properly.
ConcurrentHashMap vs Collections.synchronizedMap vs Hashtable?
Hashtable and synchronizedMap use one lock for the whole map, so all readers and writers serialise, and iteration requires external synchronisation. ConcurrentHashMap has lock-free reads, per-bin write locks and weakly consistent iterators that never throw ConcurrentModificationException. Prefer ConcurrentHashMap in all new code.