How does ConcurrentHashMap achieve high-throughput thread safety without locking the whole map in Java 8+?
In Simple Words:
Unlike Hashtable or Collections.synchronizedMap() which lock the entire map on every read or write, Java 8+ ConcurrentHashMap uses bucket-level fine-grained locking with CAS (Compare-And-Swap) and synchronized on the single root node of the target hash bucket.
Architectural Mechanics:
- Lock-Free Reads: Read operations (
get()) are completely lock-free and never block. Value fields and node pointers are declaredvolatile, guaranteeing that writes by other threads are immediately visible. - CAS for Empty Buckets: When inserting a new key into an empty bucket (
table[i] == null), it uses lock-free hardware CAS (sun.misc.Unsafe.compareAndSwapObject). If no collision occurs, no thread lock is ever acquired. - Synchronized per Bucket: If a collision occurs (the bucket already has a head node), the writing thread locks only that individual head node using Java's built-in
synchronized(node). All other buckets remain open for concurrent writes by other threads.
ConcurrentMap<String, Long> userBalances = new ConcurrentHashMap<>();
// Atomic compute operation executed lock-free using CAS retry loops:
userBalances.compute("user_42", (key, oldVal) -> (oldVal == null) ? 100L : oldVal + 50L);
Treeification:
Just like HashMap, if any single bucket experiences more than 8 collisions and the table size reaches 64, that specific bucket transforms from a linked list into a balanced Red-Black Tree (TreeBin), preventing hash-flooding DoS attacks ($O(\log N)$ worst-case search).