Video in progress

Strong Middle 🧵 Concurrency

What happens if you do something slow, or something that touches the same map, inside ConcurrentHashMap.computeIfAbsent?

The mapping function runs under the bucket lock. A slow function also blocks the other keys that land in the same bin, and modifying that same map from inside gives an IllegalStateException, or even an infinite loop in some versions.

📖 Answer

A common piece of code used as a cache:

private final ConcurrentHashMap<Long, Customer> cache = new ConcurrentHashMap<>();

Customer get(long id) {
    return cache.computeIfAbsent(id, k -> customerClient.load(k)); // HTTP, 300 ms
}

There are two problems.

The first is the scope of the lock. While the function runs, that bin (one or several keys) is locked. If another key happens to land in the same bin, its get isn't affected, but its compute/put waits the 300 ms too. If the external service hangs, that wait gets much longer.

The second is recursion:

cache.computeIfAbsent(a, k -> cache.computeIfAbsent(b, ...)); // dangerous

On Java 9+ this often throws IllegalStateException: Recursive update; on Java 8, in some cases a thread would spin forever. The Javadoc says it directly: the function should be short and simple, and must not modify the map.

What I do:

  • I use the function only for cheap work (a new object, new LongAdder());
  • for slow loading I store a CompletableFuture, so the lock is held only while the future is created:
cache.computeIfAbsent(id, k -> CompletableFuture.supplyAsync(() -> customerClient.load(k), io));
  • or a ready-made cache: Caffeine's LoadingCache was written with exactly these problems in mind.