Why are the compute/merge family the correct tools for thread-safe accumulation on a ConcurrentHashMap, and what are the pitfalls?
answer
- get-then-put = lost update race
- compute/merge = atomic read-modify-write per key
- function runs under per-bin lock: short, non-blocking
- no nested updates to same map (deadlock)
- atomic per key only; LongAdder for hot counters
basics
~10 sOn a ConcurrentHashMap, compute, computeIfAbsent, computeIfPresent, and merge perform the read-modify-write for a key as one atomic step, so two threads can't lose each other's updates. Plain get-then-put can; that's the bug they fix.
solid answer
~50 sA naive concurrent counter — `m.put(k, m.get(k) + 1)` — has a lost-update race: two threads read the same old value and one overwrites the other. On `ConcurrentHashMap`, the remapping methods (`merge`, `compute`, `computeIfAbsent`, `computeIfPresent`) execute the entire read-modify-write **atomically for that key**, eliminating the race without external synchronization — so `m.merge(k, 1, Integer::sum)` is correct with no lock of your own. Pitfalls: the remapping function runs while holding a per-bin lock, so keep it **short and non-blocking**. It is not retried here, unlike `ConcurrentMap`'s default `compute`, `computeIfPresent` and `merge`. Updating the **same** map inside the function (especially nested computeIfAbsent) is documented as forbidden; a detected recursive update throws `IllegalStateException`, and an undetected one can lose an update or deadlock. Null keys/values are disallowed entirely. Atomicity is per key only — operations spanning multiple keys still need higher-level coordination. For pure counters, the class documentation offers LongAdder values as a scalable frequency map.
go deeper
Knows get-then-put can lose updates and that merge/compute are the safe alternatives.
Can write atomic counters with merge/compute and states that the function should be short and simple.
Explains per-bin locking, the per-key (not cross-key) atomicity boundary, and the no-self-modification rule.
Designs high-throughput accumulation (LongAdder, sharding), knows which concurrent maps may retry a function, and architects multi-key invariants beyond per-key atomicity.
### The race in the naive approach Consider two threads incrementing the same counter: ```java int v = map.get(k); // both read 5 map.put(k, v + 1); // both write 6 -> one increment lost ``` Between the `get` and the `put`, another thread can run. This is a **lost update**: the final value is 6, not 7. `get`-then-`put` is two separate atomic operations, and nothing keeps another thread out in between. ### How ConcurrentHashMap's compute/merge fix it `ConcurrentHashMap` is split into independently-lockable **bins** (buckets). When you call `merge`, `compute`, `computeIfAbsent`, or `computeIfPresent`, the map locks the bin for that key, runs your function, and writes the result — all **as one atomic step for that key**. (On an empty bin, `merge` just installs the value with a CAS and never calls your function.) No other thread can interleave its read-modify-write on the *same* key. So: ```java map.merge(k, 1, Integer::sum); // atomic increment, no lost update map.compute(k, (key, v) -> (v == null ? 0 : v) + 1); // also atomic ``` are correct concurrent counters with no `synchronized` of your own. ### Constraints on the function Because the function runs **inside** the map's per-bin lock: 1. **Keep it short and non-blocking** — long or blocking work stalls other threads' updates to that bin. The documentation's words are "short and simple". 2. **It is not retried on this class** — `compute` invokes the function "exactly once per invocation of this method", and `computeIfAbsent` and `computeIfPresent` once or not at all. The `merge` Javadoc gives no count, but its code applies the function once, under the bin lock. Run eight threads on JDK 27 and the count is 1,600,000 function calls for 1,600,000 `compute` calls. The retry belongs to `ConcurrentMap`'s default `compute`, `computeIfPresent` and `merge`, where "the remapping function may be called multiple times", so a function that may also run on another `ConcurrentMap` has to tolerate repeats. 3. **Never modify the same map inside the function.** The Javadoc says the function "must not modify this map during computation" (for `merge`, "must not attempt to update any other mappings of this Map"). Detection is partial: it throws `IllegalStateException` "if the computation detectably attempts a recursive update to this map that would otherwise never complete". On JDK 27 the outcome depends on the call, the bin and the key, so it can throw, lose an update or finish with no error. `computeIfAbsent` on an absent key in an empty bin throws "Recursive update" if its function calls `merge` on that key. `merge` on a present key, with a function that calls `map.merge(k, 10, Integer::sum)` and returns a value, finishes with no error and loses the `+10`. A nested `put` of a key in another bin can finish with no error and keep both writes. An undetected update can still deadlock: two threads nesting `computeIfAbsent` or `compute` across two bins in opposite order blocked each other, and `findDeadlockedThreads` reported them. So a passing test proves nothing. 4. **No null keys or values** — `ConcurrentHashMap` forbids null entirely, so `getOrDefault` is the way to read with a fallback. ### Atomicity is per key, not across keys These methods make a single key's update atomic. A logical operation touching **two** keys (e.g., transfer between accounts) is **not** atomic just because each call is — you still need higher-level coordination (a lock, or a redesign so the invariant lives under one key). ### When to reach for LongAdder Under very high contention on a single hot key, every `Integer` merge locks that one bin, so threads queue on it. The class documentation describes a "scalable frequency map" for this: `LongAdder` values initialized through `map.computeIfAbsent(k, x -> new LongAdder()).increment()`. Once the adder exists, `computeIfAbsent` finds it and `increment` works on the adder, whose internal variables "may grow dynamically to reduce contention". (Trade-off: reads must call `sum()`.) ### Summary Use the remapping family for any read-modify-write on a shared `ConcurrentHashMap`; never `get`-then-`put`. Keep functions short and simple, never touch the same map inside them, and remember atomicity stops at one key.
- Why is map.put(k, map.get(k) + 1) unsafe under concurrency but map.merge(k, 1, Integer::sum) safe?The put version is two separate operations with a gap where another thread can read the same old value and clobber the update. merge performs the read-combine-write atomically for that key, so increments cannot be lost.
- What is the danger of calling computeIfAbsent on the same map inside its own mapping function?A computation that never completes. The Javadoc forbids it: the mapping function must not modify this map. A detected recursive update throws IllegalStateException, as a nested computeIfAbsent into the same empty bin does. One for a key in another bin completed alone, but two threads nesting in opposite order deadlocked, so a passing test proves nothing.
- Using map.put(k, map.get(k)+1) for a concurrent counter
- Doing blocking I/O inside the remapping function
- Calling computeIfAbsent on the same map from within its function
- Assuming a two-key update is atomic because each call is
- Trying to store null in a ConcurrentHashMap
- ConcurrentMap.computeIfAbsent, compute and merge
- Java 1.8
Assumes JDK 27; ConcurrentMap's compute and merge arrived in Java 8, and the ConcurrentHashMap contract reads the same at JDK 25.
context
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentMap (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentHashMap.java at jdk-27-gagithub.com