Video in progress
What happens if you make a recursive call inside map.computeIfAbsent for memoization?
Since Java 9, HashMap detects this and throws a ConcurrentModificationException. ConcurrentHashMap depending on the case throws IllegalStateException: Recursive update, or hangs on older JDKs. The mapping function must not modify that same map: write a recursive cache with plain get/put.
📖 Answer
Nice-looking but broken code:
private final Map<Integer, Long> memo = new HashMap<>();
long fib(int n) {
if (n < 2) return n;
return memo.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2));
}
Inside fib(k - 1), computeIfAbsent is called again and writes to the same map, while the outer call hasn't finished yet. The documentation explicitly forbids this: the mapping function must not modify the map during computation.
The result depends on the version and the implementation:
HashMap(Java 9+):ConcurrentModificationException; in Java 8 you could get a silently corrupted map;ConcurrentHashMap: oftenIllegalStateException: Recursive update; in Java 8 there were cases of an infinite loop;TreeMap,LinkedHashMap: no guarantee.
The right way to write it:
long fib(int n) {
if (n < 2) return n;
Long cached = memo.get(n);
if (cached != null) return cached;
long value = fib(n - 1) + fib(n - 2); // the recursion is outside the map
memo.put(n, value);
return value;
}
Or remove the recursion altogether: a loop with two variables.
In prod this usually isn't Fibonacci but shows up as reading from another cache inside a cache: cache.computeIfAbsent(userId, id -> loadUser(id)), and loadUser tries to get the role from the same cache. In Caffeine, a recursive get is forbidden too. There's one rule: don't touch that same cache inside the mapping function.
Sign up to mark studied questions and save your progress.