Practical technical guides / Core IT: Java

ConcurrentHashMap.computeIfAbsent Must Not Modify the Same Map From Its Function

On JDK 23 a memoised recursive function throws Recursive update or deadlocks depending on table size and threads. Why, and three safe replacements.

By Sandeep Belgavi · Published 2026-11-26

On JDK 23 a memoised recursive function throws Recursive update or deadlocks depending on table size and threads. Why, and three safe replacements.

A memoised function that works until it does not

ConcurrentHashMap.computeIfAbsent looks like the ideal memoisation primitive. It computes a value only when the key is missing, it is atomic, and it is thread-safe. So a recursive function that caches its sub-results with computeIfAbsent on the same map seems natural: the price lookup for a bundle of books at Belgavi's Book Store calls itself for each nested bundle and caches every price it computes.

On JDK 23.0.2 a textbook version of that pattern, a memoised Fibonacci on a default-sized ConcurrentHashMap, throws java.lang.IllegalStateException with the message Recursive update when asked for fib(20), and leaves the map empty. The same code on a map created with an initial capacity of 64 computes fib(40) without complaint. A pattern whose failure depends on table size passes small tests and fails on real inputs, which is why it is worth understanding exactly.

The Javadoc already states the rule: the mapping function must not modify this map during computation, and the method may throw IllegalStateException if the computation detectably attempts a recursive update to this map that would otherwise never complete. This guide reproduces the failure, explains the mechanism in the JDK source, shows the deadlock version with two threads, and gives three replacements.

Reproduce it

// Author: Sandeep Belgavi. Memoised recursion through computeIfAbsent on the same map.
static final Map<Integer, Long> CHM = new ConcurrentHashMap<>();

static long fib(int n) {
    if (n < 2) return n;
    return CHM.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2));
}

The companion probe runs this and several variants with JDK 23.0.2 on Windows 11. Its recorded output includes these lines:

chm fib(20) threw java.lang.IllegalStateException: Recursive update
chm size after failure=0
hashmap fib(20) threw java.util.ConcurrentModificationException
different-bin nested=ok size=2
same-key nested threw java.lang.IllegalStateException: Recursive update
two-thread cross nesting=no progress after 3 s (deadlock)

HashMap fails too, with ConcurrentModificationException, because its compute methods also detect a modification made by the mapping function. The difference is that HashMap was never thread-safe, so nobody expected it to tolerate this.

Why it happens: a reserved bin

ConcurrentHashMap stores entries in an array of bins and locks one bin at a time. When computeIfAbsent finds the key's bin empty, it does not run your function first and insert afterwards. It installs a placeholder, a ReservationNode, in the bin, locks it, runs the mapping function and then replaces the placeholder with the real node. That is how the method guarantees the function runs at most once per key while other threads wait.

Now the mapping function calls computeIfAbsent on the same map. If the nested key hashes to the same bin, the nested call finds the reservation and the code path for that case throws Recursive update. In JDK 23's source the same exception is thrown from several places, including the resize routine: if the nested insertions push the map past its resize threshold, the transfer step meets the reserved bin and throws as well.

That explains the size dependence, and a third probe in the companion code shows which path fired in each case by printing the top stack frames. A default ConcurrentHashMap starts with 16 bins. fib(20) reserves the bin for key 20 and then descends, reserving keys 19, 18 and so on before any of them completes. Key 4 lands in the same bin as key 20, so the exception was thrown inside computeIfAbsent itself, 17 nested computeIfAbsent frames deep, with the map still empty.

The sweep in the companion probe shows the second path. With new ConcurrentHashMap<>(16), which sizes the table to 32 bins, every n up to 25 succeeds and every n from 26 to 40 throws. For fib(26) no nested key shares a bin with the reservation, but by the time the descent unwinds, 24 nested entries have been inserted, which reaches the resize threshold of a 32-bin table. The exception came from transfer, called from addCount, with 24 entries in the map: the resize met the reserved bin. With an initial capacity of 64 the table has 128 bins and every n up to 40 succeeds. None of this makes the pattern correct; it only changes the input at which it breaks.

Nesting across bins is not safe either

The probe also shows that a nested computeIfAbsent for a key in a different bin succeeded: different-bin nested=ok. That is the most dangerous result, because it makes code look fine. With two threads, each holding a reservation and nesting into the other's key, neither can make progress.

// Author: Sandeep Belgavi. Two threads, each nesting into the key the other has reserved.
Future<?> f1 = ex.submit(() -> m.computeIfAbsent(1, k -> { await(both); return m.computeIfAbsent(2, j -> 20); }));
Future<?> f2 = ex.submit(() -> m.computeIfAbsent(2, k -> { await(both); return m.computeIfAbsent(1, j -> 10); }));

Thread one holds the bin for key 1 and waits for the bin of key 2. Thread two holds the bin for key 2 and waits for the bin of key 1. The probe reports no progress after three seconds and abandons the executor. In a service this looks like request threads that never return, with thread dumps showing two threads blocked inside ConcurrentHashMap on each other's bins. The single-threaded exception is the lucky case; the deadlock is what the same design does under concurrency.

Three replacements

The first replacement removes recursion through the map. For a function that is naturally iterative, such as Fibonacci or prices that can be computed bottom-up from a known order of bundles, compute the dependencies first in a loop and only then store results.

The second replacement computes outside the map and publishes with putIfAbsent. This gives up the at-most-once guarantee, so two threads may compute the same value, but it never holds a bin while running user code.

// Author: Sandeep Belgavi. Compute without holding a bin, then publish; duplicates are possible.
static long fib(int n) {
    if (n < 2) return n;
    Long hit = MEMO.get(n);
    if (hit != null) return hit;
    long v = fib(n - 1) + fib(n - 2);
    Long prev = MEMO.putIfAbsent(n, v);
    return prev != null ? prev : v;
}

The probe computes fib(90) with this version and stores 89 entries. Duplicate computation is harmless when the function is pure and cheap. When it is expensive, such as a remote price lookup, the third replacement keeps at-most-once semantics by caching futures: computeIfAbsent stores a CompletableFuture immediately, which is a quick, non-recursive operation, and the expensive work runs after the bin is released. A recursive dependency then waits on another future rather than on a bin lock. Cycles in the dependency graph still deadlock, so detect them in the data, not in the cache.

Failure modes worth testing

A test with small inputs proves nothing, as the sweep shows. Test the memoised path with inputs large enough to force several resizes, and with a map created with the default capacity, which is what production code usually uses.

Watch for indirect recursion. The mapping function rarely calls computeIfAbsent visibly; it calls a service method that calls a repository that reads a cache backed by the same map. Search for the map's uses, not only for nested calls in the lambda.

Long mapping functions hurt even without recursion. The Javadoc notes that other updates may be blocked while the computation is in progress, so the computation should be short and simple. A mapping function that makes a network call holds a bin, and every other key in that bin, for the duration of the call.

Recognising it in production

The exception is the easy case to diagnose because the stack trace names computeIfAbsent and the mapping function twice. Note what the failure leaves behind: the probe found the map empty afterwards, because computeIfAbsent does not establish a mapping when its function throws. A caller that catches the exception and retries recomputes everything and fails again. The deadlock is harder. A thread dump shows two or more threads in a ConcurrentHashMap compute method, each inside the mapping function of an outer call, each blocked on a monitor that another of them holds, because the bin locks are ordinary object monitors. Search the dump for nested compute frames on the same map rather than for the exception, which never appears.

What stays the same in other caches

The same rule applies to caching libraries that build on compute-style methods: a loader that reads the same cache for another key is recursion through the cache. Read the documentation of the library you use on recursive or reentrant loads before relying on them, and test the case the way the probe does rather than assuming it is supported. The general ConcurrentHashMap guide on this site covers bins, resizing and counters in more depth at /blogs/java/java_concurrent_hashmap.html.

Verification checklist

Grep for computeIfAbsent, compute and merge whose function bodies call methods that may reach the same map. Run the companion probe on your JDK to confirm the behaviour you rely on. Add a test that computes a deep memoised value from an empty, default-sized map, and a two-thread test with a timeout for any code that nests cache loads. Treat IllegalStateException: Recursive update in logs as a design bug, not a transient error to retry.

Primary references and authorship

Sources checked 2026-11-26. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/java/chm_recursive_update. Views are my own and do not represent any employer, past or present.