When memoizing I/O or recursive dependencies in Java, pair putIfAbsent(key, future) with atomic remove(key, created) on failure.
TL;DR30-second simplified summary▾
Two-phase Future coalescing preserves singleflight deduplication while eliminating same-bucket I/O stalls and recursive update exceptions.
Why computeIfAbsent() Holds a Bin Monitor.
To guarantee at-most-once execution per key, ConcurrentHashMap inserts a ReservationNode and synchronizes on it while executing the mapping lambda.
Decoupling Computation from Bin Monitor
- Lock hold: Full T_compute (50ms I/O)
- Unrelated keys in same bin: Blocked
- Same-bucket recursion: IllegalStateException
- Lock hold: ~15ns pointer insertion
- Unrelated keys in same bin: Unblocked during I/O
- Same-bucket recursion: Safe via Future.join()
Two-Phase CompletableFuture Coalescing.
Use putIfAbsent() to elect one computation owner while concurrent callers await the same Future without holding any bucket lock.
Two-Phase CompletableFuture Coalescing
CompletableFuture<V> fut = map.get(key);
if (fut == null) {
CompletableFuture<V> created = new CompletableFuture<>();
CompletableFuture<V> prev = map.putIfAbsent(key, created);
if (prev == null) {
try {
created.complete(computeOutsideLock(key));
} catch (Throwable t) {
map.remove(key, created);
created.completeExceptionally(t);
}
fut = created;
} else { fut = prev; }
}
return fut.join();
Failure Eviction & Amortized Complexity.
Always pair exception handling with map.remove(key, created) (2-arg atomic remove) so a transient failure does not poison the cache forever. [INSERT YOUR BENCHMARK / PROD NOTE] for tail latency under high miss concurrency.
CompletableFuture Coalescing & Failure Eviction State Machine
- Problem
- How to memoize blocking I/O, external RPCs, or recursive map lookups in ConcurrentHashMap without stalling unrelated keys in the same bin or throwing IllegalStateException.
- Naive Solution
- Call ConcurrentHashMap.computeIfAbsent(key, fn) directly for every memoized computation.
- Why It Fails
- computeIfAbsent() holds a synchronized ReservationNode lock for the entire mapping lambda, blocking unrelated keys hashing to the same bucket and throwing IllegalStateException: Recursive update on same-bucket recursion.
- Alternatives
- Compare computeIfAbsent() (singleflight but holds bin lock across T_compute), get() then putIfAbsent() (nanosecond lock hold but duplicates work on concurrent misses), and two-phase putIfAbsent(key, new CompletableFuture<>()) with atomic remove(key, created).
- Engineering Decision
- Use computeIfAbsent() only for pure CPU-bound, non-recursive micro-computations (<1 microsecond); when population involves blocking I/O, external RPCs, or recursive lookups into the same map, store a CompletableFuture via putIfAbsent() and compute outside any map lock.
- Trade-Offs
- Eliminates bin-lock starvation and recursive update exceptions while preserving singleflight deduplication, in exchange for one CompletableFuture allocation per miss and explicit 2-arg remove(key, created) failure cleanup.
Why must exception cleanup call map.remove(key, created) instead of map.remove(key)?
| Choice | What it buys | What it costs |
|---|---|---|
| computeIfAbsent(k, fn) | Singleflight: Yes | Lock Hold Time: Full T_compute Recursive Safe?: No (IllegalStateException) |
| get() then putIfAbsent() | Lock Hold Time: Nanoseconds Recursive Safe?: Yes | Singleflight?: No (duplicate work) |
| putIfAbsent(k, Future) | Lock Hold Time: Nanoseconds Recursive Safe?: Yes Singleflight?: Yes | Allocates one CompletableFuture per cache miss Requires 2-arg atomic remove(key, created) on failure |
Practice: Make the trade-off yourself.
What happens in Java 17 when ConcurrentHashMap.computeIfAbsent() recursively calls computeIfAbsent() on a different key that hashes to the same bucket?