Lesson · Concurrent Collections
ConcurrentHashMap: CAS on empty bins, monitors on collisions
16 min readConcurrentHashMap
ConcurrentHashMap keeps the HashMap shape and replaces its one missing feature: a sane way for two threads to write at once. A CAS fills an empty bin, the bin head monitor handles a collision, and the atomic methods built on top are how compound updates stop racing.
The same table, a different write path
Start with what does not change. ConcurrentHashMap is still a bucket array addressed by hash & (capacity - 1), still chained, still resized when the entry count crosses capacity times the load factor 0.75. Everything the HashMap internals lesson taught about masks, chains and resize applies here; this lesson is about what happens when two threads do it at the same time.
What changes is where exclusion lives. HashMap has none and is safe only single-threaded. A synchronized wrapper has one mutex for the whole map and serializes everything. ConcurrentHashMap resolves contention per bin, so unrelated keys almost never wait for each other.
Retrievals generally do not block: a get reads the table reference and the nodes it needs, and reflects the result of the most recently completed update as of when the read began. No read takes the write path, which is why read-heavy code scales here where a wrapper stalls.
- Reads are lock-free.
get,containsKeyand traversal read node fields and never acquire a bin monitor. - Writes take one of two paths. A CAS when the target bin is empty, the bin head monitor when it is not.
- Resize is shared work. A thread that arrives at a bin already being moved helps transfer instead of waiting, and other bins keep serving reads and writes meanwhile.
The map did not get a bigger lock. It got many smaller ones, and the read path lost its lock entirely.
Two write paths, and why they are enough
Empty bin. The thread builds the node and installs it with a compare and set on the array slot. If another thread filled that bin first, the CAS fails, the loop retries, and the second attempt finds a non-empty bin and takes the other path. The loser wrote nothing, so nothing was lost.
Occupied bin. The thread synchronizes on the head node and then re-checks the bin, because the state it observed before acquiring the monitor may already be obsolete. Inside the monitor it walks the chain, appends or replaces the node, or inserts into the tree bin, then releases. Two writers on one bin serialize; writers on different bins do not.
The pair covers the invariant the table needs: a bin is only mutated under its head monitor, and an empty bin is only filled by CAS. There is no interleaving in which two threads append conflicting nodes to the same chain.
Resize follows the same principle. The transfer moves bins one at a time and leaves a forwarding marker behind, so a thread that reaches a moved bin can join the transfer rather than block on it, and reads keep working against bins that have not moved yet.
Two write paths, one table: CAS for the empty bin, the bin head monitor for everything else. Narrow exclusion is what lets unrelated keys stay independent.
ConcurrentHashMap · one table, two write paths
reads take neither path: they are lock-free
empty: CAS installs the first node
collision: synchronized on the bin head
8 entries: treeify; back to a chain at 6
no writer active
being moved: arriving threads help transfer
readers pass through, untouched
size()
baseCount 4cell[0] 3cell[1] 2cell[2] 0=9Striped counters, summed on demand. An estimate while updates are in flight, exact once the map is quiet.
A bin is only ever mutated under its head monitor, and an empty bin is only ever filled by CAS. A writer that loses the CAS wrote nothing, so the retry is free of consequences, and two writers on different bins never meet. The weaker the guarantee looks per operation, the more of the table can be worked on at once.
No null keys, no null values
ConcurrentHashMap rejects null keys and null values with NullPointerException, and the reason is the atomic methods rather than taste. computeIfAbsent uses a null return from your mapping function to mean no mapping was produced, and computeIfPresent treats a null result as remove. If null were a legal stored value, the map could not tell an absent entry from an empty one.
The same argument applies to reading. On a single-threaded HashMap, containsKey and get agree unless a bug intervenes. On a concurrent map every answer is already a moment old when it returns, and a stored null would remove the only signal that distinguishes a missing key from a present one.
The practical consequence is small once stated: use Optional, a sentinel value, or a second collection when you need to represent absence. The map made that choice for you, and every reader of a concurrent map gets to assume the values are real.
- `put(null, v)` and `put(k, null)` throw. The rejection happens at the boundary, before any bin work.
- `get(k) == null` can only mean absent. There is no ambiguity left to reason about.
- A null return from a remapping function means remove (for
computeIfPresentandcompute) or record nothing (forcomputeIfAbsent); it never stores null.
Null is not a value in this map; it is the absence of one, and the whole API depends on that reading.
The numbers behind the structure
The tuning constants are the same ones the single-threaded table uses, and the concurrent machinery reads the same thresholds. Here is the set that matters, with what each one buys:
| Detail | Value | What it buys |
|---|---|---|
| Install into an empty bin | compare and set on the slot | a write with no lock; a lost race simply retries |
| Write into an occupied bin | synchronized on the head node | contention scoped to one bin, not one map |
| Treeify a bin | 8 entries, table at 64 buckets or more | a chain becomes a red-black tree; below 64 buckets the table grows instead |
| Untreeify a bin | back to a chain at 6 | hysteresis, so one insert and one remove cannot flip the shape repeatedly |
| Default load factor | 0.75 | resize threshold at capacity times 0.75, the same math as HashMap |
| Default initial capacity | 16 | the same starting table; pre-size when you know the volume |
| Null policy | rejected | absence keeps exactly one representation |
Thresholds are implementation details; atomicity is the contract. Quote 8 and 6 when you explain the implementation, not when you rely on behaviour.
Compound operations, as one call
The methods below are the reason to reach for this class. Each performs a read, a decision and a write as a single operation with a single linearization point, so the gap that makes check-then-act fail does not exist.
| Method | Key present | Key absent | Returns |
|---|---|---|---|
| putIfAbsent(k, v) | returns the existing value, writes nothing | installs v | the current value, or null when it installed v |
| computeIfAbsent(k, fn) | fn does not run | runs fn and installs the result unless it is null | the present or computed value, or null |
| computeIfPresent(k, fn) | runs fn with the current value, removes if it returns null | fn does not run | the new value, or null |
| compute(k, fn) | runs fn with the current value, removes if it returns null | runs fn with null, installs unless it returns null | the new value, or null |
| merge(k, v, fn) | runs fn(old, v), removes if it returns null | installs v | the new value, or null |
computeIfAbsent is the cache; containsKey-then-put is the race. If your compound update needs two calls on a shared map, check for a named method before reaching for a lock.
The memoizing cache, done right
A cache with a compute-once rule is the classic use, and it comes down to one line: return cache.computeIfAbsent(key, k -> compute(k)). Two threads racing for the same key is exactly the case the method was built for: one runs the function, the other waits and receives the result, and the expensive work happens once.
The broken version looks almost identical and loses the guarantee. containsKey then get then put is three calls and three linearization points, so two threads can both miss and both compute. The fix is not a lock around the three calls, it is one call instead of three.
The traps concern what happens inside that call, because the bin holding the key is busy while the function runs. Keep it short. Do not touch the map from inside it: a nested computeIfAbsent or put on the same map can block on a bin the outer call already holds, and some of those cases are detected and thrown as IllegalStateException while others merely stall. Decide what a null result means, too, because computeIfAbsent treats it as no mapping recorded, and the caller then has to handle the null.
- One call, one decision point. If the value must be computed at most once per key,
computeIfAbsentis the entire mechanism. - Returning null records no mapping. It does not store a null: this map has none. Either compute a real value or handle the null at the call site.
- Never modify the map inside the function. The bin is held for the duration, so a nested update can block or throw.
- Keep the function short. Other updates to the same bin wait on it, so a slow call is a local stall with a global smell.
- merge is the counter idiom.
hits.merge(word, 1, Integer::sum)reads, folds and writes in one operation, and no update is lost under any interleaving.
The cache is the method, plus discipline about the function body. Everything people try to build with three calls already exists as one.
ConcurrentHashMap player · two threads, one bin
bin array · capacity 6
index = hash & (capacity - 1). Four bins stay empty on purpose: they are the keys nobody contends for.
calls putIfAbsent
calls putIfAbsent
Two threads register the same key at the same time: putIfAbsent("user:7", sessionA) and putIfAbsent("user:7", sessionB). The bin for that key is empty.
Scene 1 is one winner and one no-op. Scene 2 is two atomic calls that still lose a value. Scene 3 is the decision and the write performed as one operation.
size(), iteration and other estimates
size() is not a count taken under a lock. The implementation keeps a base counter plus a small set of cell counters, the same striping idea LongAdder uses, and size() sums them on demand. While updates are in flight that sum is an estimate, because there is no instant at which the map is quiet to be measured; once updates stop, the sum is exact. Use mappingCount() when you want the same number as a long.
Iterators, spliterators and the keySet, entrySet and values views are weakly consistent: safe under concurrent writes, never throwing ConcurrentModificationException, and free of any promise about which updates a traversal contains. Traversal order is unspecified, so do not build logic on it.
Bulk operations follow the same rule and add one knob. forEach, search and reduce have overloads taking a parallelism threshold, the estimated element count at which the operation is worth splitting. Long.MAX_VALUE requests sequential execution, 1 requests as much parallelism as possible, and parallel bulk operations run on the common ForkJoinPool rather than a pool you choose.
- `size()` and `isEmpty()` are instantaneous sums, not snapshots, so do not drive control flow with them under concurrency.
- `mappingCount()` returns the same figure as a long, which survives tables larger than Integer.MAX_VALUE.
- Parallel bulk operations share the common pool with everything else using it, and inherit weak consistency like any other traversal.
Under concurrency every count is an estimate until the map is quiet. Size, emptiness and traversal order are all answers as of roughly now.
What to remember
Five habits keep a concurrent map both fast and correct:
- Reach for a named method first.
putIfAbsent,compute,mergeexist so a compound update is one operation. - Keep mapping functions short and read-only. They run while the bin is held and must not update the same map.
- Treat size, isEmpty and iteration as estimates. They are cheap and honest, not snapshots.
- Expect no nulls. The map refuses them so absence keeps one meaning.
- Pre-size when the volume is known, exactly as with HashMap: the resize cost is still real, it is just shared across the threads that trigger it.
The concurrency is in the structure, the atomicity is in the methods. Use the structure for speed and the methods for correctness.
The cache that deadlocks on itself
A mapping function that reaches back into the same map is the trap this class hides best. computeIfAbsent runs your function while the bin holding the key is busy, so a nested computeIfAbsent or put on that map can block on a bin the outer call already holds, and some of those cases surface as IllegalStateException with a message about a recursive update. The rule is short: the mapping function reads what it needs, computes quickly, returns a value, and never touches the map it is filling.
Interview angles
How does ConcurrentHashMap allow writes without one global lock?+
It resolves each bin separately. A write to an empty bin is a CAS on the slot, so there is nothing to lock; a write to an occupied bin synchronizes on that bin head node and re-checks the state it saw before the monitor was acquired. Readers never take either path.
What are the consequences of refusing nulls?+
Absence has exactly one representation, so get(k) returning null can only mean the key is not there. It also lets the remapping methods use a null return to mean no mapping or remove, which is central to compute and merge.
Common misconception: That the ban exists only to avoid the single null key HashMap allows.
putIfAbsent or computeIfAbsent?+
putIfAbsent when the value already exists and you only want to install it if the key is free; it returns the current value, so a losing thread learns what won. computeIfAbsent when the value must be produced, because the function runs only when the key is absent and at most once per key.
computeIfAbsent is the memoizing cache. The documented contract says the function is applied at most once per key, and it runs while the bin is held, so it must be short and must not update the same map.
What does size() actually return?+
A sum of the base counter and the per-cell counters, read without locking. Under concurrent updates it is an estimate, because there is no quiescent instant to measure; once updates stop, it is exact.
The striping is the LongAdder idea: one shared counter would become the new bottleneck, so counts are spread across cells and summed on demand. mappingCount() gives the same number as a long.
Is ConcurrentHashMap lock-free?+
No, and the distinction matters. Reads are lock-free and never block writers; writes use CAS to fill an empty bin and a monitor on the bin head when the bin is occupied. Contention is scoped to a bin, which is why unrelated keys rarely wait.
Common misconception: That lock-free reads mean the whole structure is lock-free.
What changed from Java 7 to Java 8?+
Java 7 used a fixed array of segments, each one a ReentrantLock, and the concurrency level was the segment count. Java 8 replaced segments with CAS plus per-bin synchronization on the node head, which uses memory better and keeps one key's contention inside its own bin.
Follow-up: What happens to a bin that grows long in either design?