What are the atomic compound methods on ConcurrentHashMap (putIfAbsent, computeIfAbsent, compute, merge), and why use them instead of get-then-put?
answer
- putIfAbsent / computeIfAbsent / compute / merge = atomic check-and-act
- get-then-put has a lost-update race window
- computeIfAbsent = lazy, once per call on a miss
- merge = thread-safe accumulate/counter
- Mapping function runs UNDER the bin lock: short, non-blocking, don't self-mutate
basics
~20 sThey do a check-and-update as one atomic step, so two threads can't interleave between checking and writing. A manual get-then-put has a race window where both threads see the same state and clobber each other; these methods close that window.
solid answer
~50 sThese methods bundle a read and a conditional write into a single atomic operation. putIfAbsent inserts only if the key is absent and returns the existing value (or null). computeIfAbsent runs a function to build a value only when the key is missing, storing and returning it—ideal for lazy initialization and caches. compute always runs a remapping function over the current value (null in = absent). merge combines a new value with an existing one via a function, perfect for counters/accumulators. A hand-written 'if absent then put' has a race where two threads both observe the key missing and both insert, losing one update; these methods make check-and-act one step for other updates to that key. Caveat: the function runs under the bin lock, so keep it short and non-blocking, and never modify the same map from it. At JDK 27 that breach throws IllegalStateException only when detected; otherwise it can lose a write, or deadlock two threads that nest into each other's bins.
code
java · 30 linesimport java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
class CompoundMethods {
record Config(String name) {
static Config load(String name) { return new Config(name); }
}
static final ConcurrentHashMap<String, Long> counts = new ConcurrentHashMap<>();
static final Map<String, Config> cache = new ConcurrentHashMap<>();
static void wrongCount(String word) {
// WRONG: two threads can both read the same c -> lost update
Long c = counts.get(word);
counts.put(word, c == null ? 1 : c + 1);
}
static void rightCount(String word) {
// RIGHT: one atomic read-modify-write per key
counts.merge(word, 1L, Long::sum);
}
static Config lookup(String name) {
// load() runs only on a miss, once per call; if it returns null or throws, no mapping is left
return cache.computeIfAbsent(name, Config::load);
}
// Keep the function short, and never update this map from inside it:
// cache.computeIfAbsent(k, key -> { cache.put(other, config); return config; }); // breaks the contract
}go deeper
Knows putIfAbsent/computeIfAbsent/compute/merge exist and that they avoid a race that get-then-put has.
Picks the right method per use case (insert-once, lazy cache, transform, accumulate) and explains the lost-update race the compound atomicity closes.
Articulates that atomicity is per-key per-call, that the mapping function runs under the bin lock (so should be short and non-blocking), and why self-mutation is dangerous.
Reasons about contention hotspots (a hot key serializes through one bin lock), function side effects (once per call on ConcurrentHashMap, possibly repeated under ConcurrentMap's defaults), and when a single CHM operation is insufficient for a cross-key invariant, choosing alternative coordination.
## The race these methods fix A very common pattern is **check-then-act**: look at the map, then update based on what you saw. Written by hand on a concurrent map it is **not safe**: ```java if (!map.containsKey(k)) { // thread A and thread B both see 'absent' map.put(k, compute()); // both put -> one update is lost } ``` Each individual call (`containsKey`, `put`) is atomic, but the **gap** between them is not. Two threads can interleave and both proceed, producing a **lost update** or duplicate initialization. The fix is a method that performs the check **and** the act **as one indivisible operation**. ## The four compound methods - **`putIfAbsent(k, v)`** — if `k` is absent, insert `v`; otherwise leave the existing value. Returns the **previous** value (`null` if there was none). Use for "insert once". Note: the value `v` is computed eagerly *before* the call, even if it ends up unused. - **`computeIfAbsent(k, fn)`** — if `k` is absent, run `fn(k)` to produce a value, store it, and return it; if present, just return the existing value **without** calling `fn`. The Javadoc's wording is exact: `fn` is "invoked exactly once per invocation of this method if the key is absent, else not at all." Racing callers on one key therefore share a single successful build, but this is not once per key forever: if `fn` returns `null` or throws, no mapping is left and the next call runs it again. Ideal for **lazy initialization** and **memoizing caches** (e.g. one expensive object per key). - **`compute(k, fn)`** — always run `fn(k, currentValueOrNull)`; store and return its result. If `fn` returns `null`, the mapping is **removed**. Use when the new value depends on the old one and you may also want to delete. - **`merge(k, v, fn)`** — if `k` is absent, store `v`; if present, store `fn(existingValue, v)`. If `fn` returns `null`, remove the mapping. The canonical use is **accumulation**: `map.merge(word, 1, Integer::sum)` is a thread-safe word counter. The Javadoc's own idiom for a scalable frequency map keeps a `LongAdder` per key: `freqs.computeIfAbsent(key, k -> new LongAdder()).increment()`. Each call is one atomic step for other updates to that key. In the JDK 27 source, an update takes the **bin lock** (the monitor of the bin's first node). `putIfAbsent` and `merge` insert into an empty bin with a CAS instead, while `computeIfAbsent` and `compute` CAS a placeholder `ReservationNode` into it and hold that node's monitor while the function runs. `putIfAbsent` and `computeIfAbsent` may also return without locking when the key sits in the bin's first node. Reads are not held back: a `get` during a running `compute` returns the earlier value. ## Atomicity guarantee and its scope The guarantee is **per single method call on a single key**: "The entire method invocation is performed atomically." A *sequence* of compound calls is still not atomic as a group. If you need a multi-key invariant, the map alone won't give it to you. ## Critical caveat: the function runs under the lock For `computeIfAbsent`, `compute`, and `merge`, the **remapping function executes while the bin is locked**. The Javadoc's words: "Some attempted update operations on this map by other threads may be blocked while computation is in progress, so the computation should be short and simple." In practice: - **Short and simple** — it can stall every other writer to that bin, including writers of other keys that merely share it. - **Avoid blocking** — I/O or waiting on another lock stretches that stall, and a second lock adds ordinary lock-ordering risk. The bin lock is a `synchronized` monitor, so before JDK 24 a virtual thread blocking here pinned its carrier. Since JEP 491 (JDK 24, so both 25 LTS and 27) it can unmount, yet it still holds the monitor and other writers still wait. - **Never modify this map** — the one hard rule: the function "must not modify this map during computation" (`merge` says it "must not attempt to update any other mappings of this Map"). Detection is partial. On JDK 27, a nested `computeIfAbsent` or `compute` on the same absent key throws `IllegalStateException: Recursive update` when that key's bin is empty or a list, the Javadoc's case of a recursive update "that would otherwise never complete". In a tree bin the same nesting throws nothing, and the call returns a value that is not the one stored. The same JDK also lets a nested write to a key in another bin succeed silently, and silently overwrites a `put` made inside `compute` on the same present key. Two threads can also deadlock: if each runs a function on an absent key and nests into the bin the other holds, both stay `BLOCKED`. No exception does not mean safe: **don't mutate the map inside its own mapping function**. - **No retry here, unlike some `ConcurrentMap`s** — `computeIfAbsent` (on a miss) and `compute` document one invocation per call, and `merge` applies its function once inside the bin lock with no retry. The retry warning belongs to the `ConcurrentMap` default methods ("the remapping function may be called multiple times") and to `ConcurrentHashMap.replaceAll`, which re-applies its function when its compare-and-replace loses a race. Code written against the interface should keep functions free of side effects that cannot repeat. ## putIfAbsent vs computeIfAbsent - `putIfAbsent` computes the value **eagerly**; wasteful if creation is expensive and the key usually already exists. - `computeIfAbsent` computes **lazily**, only on a miss, and racing callers on one key share a single successful build—making it the right tool for caches. ## Worked example A thread-safe multimap and a counter: ```java map.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(item); // atomic get-or-create, then add counts.merge(key, 1L, Long::sum); // safe increment ``` Each map call is atomic per key; the equivalent get-then-put versions would race. The `add` is outside that step: it runs on the returned list after `computeIfAbsent` returns, and is thread-safe because `CopyOnWriteArrayList` is. A reader can still see the new list empty, and a concurrent `remove(key)` can detach it before the `add`, losing the item.
- When would you prefer putIfAbsent over computeIfAbsent?When the value is cheap or already in hand (no benefit to laziness), or when you need to know whether your call inserted: putIfAbsent returns null only if it did, while computeIfAbsent returns the current value either way. If construction is expensive, computeIfAbsent is better because it only builds on a miss.
- What is dangerous about calling map.computeIfAbsent inside another computeIfAbsent on the same map?The outer function runs while the bin is locked, and the Javadoc forbids it to modify the map. At JDK 27 the same absent key throws IllegalStateException ("Recursive update") only in an empty or list bin; a tree bin throws nothing and returns a value that is not the one stored. A nested update to another bin can succeed silently, and two threads nesting into each other's bins can deadlock. Restructure: compute the inner value first.
- Saying putIfAbsent computes the value lazily (it doesn't; computeIfAbsent does)
- Doing heavy work or blocking I/O inside computeIfAbsent/compute/merge functions
- Mutating the same map inside its own mapping function
- Claiming a sequence of compound calls is atomic as a group
- Treating get-then-put on CHM as safe because each call is atomic
- Believing ConcurrentHashMap.compute retries its function under contention, as a CAS loop would
- ConcurrentMap.computeIfAbsent, compute and merge
- Java 1.8
- ConcurrentMap.putIfAbsent
- Java 1.5
Describes JDK 27's recursive-update behaviour, which updates inside a mapping function throw IllegalStateException and which pass silently; JDK 25 LTS behaves the same, and older releases may differ. Virtual threads stop being pinned by the bin lock from JDK 24 (JEP 491), so 25 LTS and 27 agree on that.
context
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentMap (Java SE 27 & JDK 27)docs.oracle.com
- JEP 491: Synchronize Virtual Threads without Pinningopenjdk.org