Video in progress
What happens if you modify the same map inside ConcurrentHashMap.computeIfAbsent?
The mapping function runs under the bucket lock. Writing to the same map from inside it often throws IllegalStateException: Recursive update on Java 9+, while on Java 8 a thread could hang forever in some cases. The function must be short, free of side effects, and must not touch the map.
📖 Answer
A common memoization mistake:
Map<Integer, BigInteger> memo = new ConcurrentHashMap<>();
BigInteger fib(int n) {
if (n < 2) return BigInteger.valueOf(n);
return memo.computeIfAbsent(n, k -> fib(k - 1).add(fib(k - 2))); // recursive write
}
The inner call writes to a different key, but that key can land in the same bucket or in a bin that is still being prepared. The result is an exception or (on older JDKs) a hang. In a plain HashMap, Java 9+ throws a ConcurrentModificationException in a similar case.
The second problem is a slow function:
cache.computeIfAbsent(userId, id -> httpClient.loadProfile(id)); // 2 seconds
For those 2 seconds, writes for other keys in the same bucket wait too. Under load this makes threads pile up, and in a thread dump you see many threads BLOCKED inside ConcurrentHashMap.
What to do:
- write the recursion as a plain loop or with a separate check (
get, thenputIfAbsent); - move the slow loading out of the map, or put in a lightweight object like
computeIfAbsent(k, x -> new CompletableFuture<>())and do the heavy work afterwards; - use a ready-made cache (Caffeine), which handles this correctly.
Sign up to mark studied questions and save your progress.