How does ConcurrentHashMap work in Java 8+ versus Java 7?
advancedCore Java › Java Collections Framework
Java 7 used 16 lock-striped Segments (each a ReentrantLock over a mini hash table). Java 8+ removed segments: an empty bucket is filled with a lock-free CAS; otherwise it uses synchronized on the bucket's first node. Resizing is cooperative (multiple threads migrate bins), and bins treeify like HashMap.
- Reads are lock-free (
volatilefields);size()uses stripedCounterCells (likeLongAdder), so it is an estimate under concurrency. - No
nullkeys or values.
- Is
if (!m.containsKey(k)) m.put(k, v)safe? No, useputIfAbsent/computeIfAbsent. - Can
computeIfAbsentcall other map operations in its function? No; it can deadlock or throwIllegalStateException(recursive update).