Java 21: ConcurrentHashMap & Lock Striping
easy⏱ 5 mincoursejava
Segments → per-bucket locks (Java 8)
Java 7 CHM used 16 'segments' (default concurrency level), each a mini HashMap with its own lock. Java 8 dropped segments: now every bucket can be locked independently via synchronized on the bucket's head node — finer granularity, lock-free reads with volatile.
CAS on empty buckets
First write to an empty bucket uses compareAndSwap (CAS) on the tab[i] slot — no lock, just a single atomic instruction. Only if CAS fails (contention) does it fall back to synchronized. That's why CHM absolutely crushes a plain synchronized HashMap.
// CHM.putVal (simplified)
if ((f = tabAt(tab, i)) == null) {
if (casTabAt(tab, i, null, new Node(hash, k, v))) break; // no lock
}
else synchronized (f) { // lock ONLY this bucket's chain
// walk + update
}
Weak consistency for iterators
CHM iterators are weakly consistent — they don't throw ConcurrentModificationException, but may or may not see concurrent updates. size() is a rough estimate, not a snapshot. keySet().toArray() is consistent per bucket. This is a deliberate trade for scalability.
Simulate lock-striped writes
Build a StripedMap<K, V> with 16 stripes. On put, pick stripe by hash(k) & 15. Simulate 4 concurrent workers writing 1000 keys each, logging contention events (when two workers pick the same stripe). Show why even-stripe distribution gives near-zero contention.
compute/merge are atomic
chm.compute(k, (k, v) -> v == null ? 1 : v + 1) is atomic for a single bucket. Use it instead of get + put for counters. Same for merge(k, 1, Integer::sum) — the cleanest atomic-increment in Java.
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(word, 1, Integer::sum); // atomic counter increment
Quiz: ConcurrentHashMap vs Collections.synchronizedMap
Why is CHM faster than Collections.synchronizedMap(new HashMap<>())? synchronizedMap locks the entire map per call — one writer blocks everyone. CHM locks only the affected bucket (and reads are lock-free). Under contention, CHM is 10-100x faster.