Quick revision
The short answer
ConcurrentHashMap runs the mapping function while it holds the lock on the key's bin, so a slow userClient.fetch keeps that bin locked for the whole remote call: every other update to the same bin waits, other keys that hash to that bin wait, and a resize that needs to move the bin waits too, which can stall writers across the whole map. The rule is that a mapping function must be short and must not do I/O. The redesign stores CompletableFuture<User> values so computeIfAbsent only installs a future, runs the fetch outside the lock, and removes failed futures, or uses a cache library with async loading such as Caffeine's AsyncLoadingCache.
What to remember
In this answer, we saw that ConcurrentHashMap runs the computeIfAbsent mapping function while holding its bin's lock, so a slow remote fetch blocks other updates to that bin, unrelated keys that hash into it, and resizes that need to move it, which can stall the whole map. The rule is that mapping functions must be short and must not do I/O. We redesigned the cache to store CompletableFuture values, so the lock is held only while installing a future and failed futures are removed, and showed Caffeine's AsyncLoadingCache as the ready-made version with expiry, bounds and metrics.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
ConcurrentHashMap runs the mapping function while it holds the lock on the key's bin, so a slow userClient.fetch keeps that bin locked for the whole remote call: every other update to the same bin waits, other keys that hash to that bin wait, and a resize that needs to move the bin waits too, which can stall writers across the whole map. The rule is that a mapping function must be short and must not do I/O. The redesign stores CompletableFuture<User> values so computeIfAbsent only installs a future, runs the fetch outside the lock, and removes failed futures, or uses a cache library with async loading such as Caffeine's AsyncLoadingCache.
Why this question is asked
Caching remote lookups with computeIfAbsent is so natural that it appears in almost every Java codebase: one line, no duplicate calls, thread-safe. It works beautifully while the remote service is fast. The trouble starts on a bad day, when the user service slows to two seconds per call and suddenly endpoints that have nothing to do with users time out too. Interviewers ask this scenario because diagnosing it requires knowing what the map does while our function runs. In this answer, we will recap the locking inside computeIfAbsent, trace how one slow call spreads to unrelated keys, state the rule, and redesign the cache with futures and with Caffeine.
1A Quick Recap: The Function Runs Under a Lock
computeIfAbsent promises that the mapping function runs at most once per absent key, even if many threads ask at the same moment. To keep that promise, ConcurrentHashMap locks the key's bin, one slot of its internal array, and keeps it locked until the function returns and the value is stored. If the bin was empty, it installs a reservation node first and locks that. Other threads that want to write to the same bin wait for the lock.
Plain reads with get do not take the lock, so they continue. But computeIfAbsent itself is the read path of this cache: every lookup goes through it. So any lookup that lands in a locked bin, and is not served by the lock-free fast path for an existing head node, waits until the remote call finishes.
2How One Slow Call Stalls Unrelated Keys
Let us follow the incident. The user service starts taking 2 seconds per call. A request asks for user 42, which is not cached.
7 messages in order. Play them, or step through them one at a time.
Thread B wants a different user, but it shares bin 10 and waits for the whole remote call.
The first waiter is fine; it wants the same value. The second waiter is the surprise: user 1066 hashes into the same bin as user 42 in the current table, so a completely unrelated lookup inherits the 2-second delay. With thousands of users and a few hundred bins, many keys share each bin.
The third effect is the one that turns a slow dependency into a full outage. When the map grows, the resize moves bins to a new table one at a time, and moving a bin requires its lock. Threads that write during a resize help with the transfer, so they can end up waiting on the locked bin as well. Now writers for any key can stall. With a request thread pool of 200, it takes only a few seconds of this before every thread is waiting and the service stops answering health checks.
3The Rule: Short Functions, No I/O
The Javadoc of ConcurrentHashMap.computeIfAbsent says the computation should be short and simple. In practice that means the mapping function may build a small object or do a quick calculation, and must not call a remote service, run a database query, read a file, take another lock or call back into the same map. Anything whose duration we do not control does not belong inside a bin lock.
The reason is not only latency. The map's internal locks are invisible to our timeouts and circuit breakers: nothing in our code knows that thread B is waiting for a remote call made by thread A. So the delay does not show up where we look for it.
4Redesign 1: Store Futures, Not Values
The map can still give us one call per key if we store the promise of a value instead of the value. Installing a CompletableFuture takes microseconds, so the bin lock is released almost at once, and the slow fetch runs on another thread with no map lock held.
Notice three details. The mapping function only creates a future, so it is short. Concurrent callers for user 42 all receive the same future, so we still make one remote call per key, a property called request coalescing. And when a fetch fails or times out, remove(id, f) deletes the entry only if it is still that failed future, so an error is not cached forever and we do not remove a newer, successful entry by mistake. Successful entries still need an expiry policy, which a plain map does not offer.
5Redesign 2: Use a Cache With Async Loading
Writing the expiry, size limit, failure handling and metrics ourselves is a lot of code that a library already gets right. Caffeine's AsyncLoadingCache stores futures internally, loads on an executor, removes failed loads automatically, and adds bounded size, expiry and refresh.
Whichever we choose, the slow dependency is now isolated: lookups for user 42 wait on their own future, with their own timeout, and lookups for every other user, cached or not, never touch a lock held during I/O. We still want a timeout and a circuit breaker on userClient itself, so that when the user service is down we fail quickly instead of piling up futures.
6Follow-up questions
Would a synchronized HashMap or a striped lock avoid the problem?
No, they make it worse or the same. Any design that holds a lock while doing I/O couples unrelated callers to the slowest remote call. The fix is to hold no lock during the call, which is what storing a future achieves.
Why remove(id, f) instead of remove(id)?
Because by the time the failure callback runs, another thread may already have replaced the failed entry with a fresh future that is succeeding. remove(key, value) removes the entry only if it still maps to our failed future, so we never throw away someone else's good work.
Is it still a problem with virtual threads?
Yes. A virtual thread blocking in the remote call still holds the bin's monitor, and other threads, virtual or platform, still wait for it. Before Java 24 a virtual thread blocked inside synchronized could even pin its carrier thread. Virtual threads make waiting cheaper, but they do not make the lock shorter.
7Conclusion
In this answer, we saw that ConcurrentHashMap runs the computeIfAbsent mapping function while holding its bin's lock, so a slow remote fetch blocks other updates to that bin, unrelated keys that hash into it, and resizes that need to move it, which can stall the whole map. The rule is that mapping functions must be short and must not do I/O. We redesigned the cache to store CompletableFuture values, so the lock is held only while installing a future and failed futures are removed, and showed Caffeine's AsyncLoadingCache as the ready-made version with expiry, bounds and metrics.
Open with
The cause is that ConcurrentHashMap runs the mapping function while holding the lock on that key's bin. That is how it guarantees one computation per key. So when userClient.fetch takes two seconds, the bin stays locked for two seconds.
Then, if they want more
Other lookups for the same user wait, which is intended, but so do lookups for unrelated users that happen to hash to the same bin, and since every lookup in this cache goes through computeIfAbsent they block too.
Worse, if the map needs to resize, moving that bin needs its lock, and writers that help with the resize can stall as well, so the slowdown spreads across the map and eventually eats the request thread pool. The rule is that a mapping function must be short and must never do I/O.
For the redesign, I would store CompletableFuture of User as the value. computeIfAbsent then only installs a future created with supplyAsync on an I/O executor, which takes microseconds, and the fetch runs with no map lock held. Concurrent callers for the same user share one future, so we still coalesce requests.
I would add a timeout, and remove the entry with remove(id, future) when it fails, so errors are not cached. In practice I would rather use Caffeine's AsyncLoadingCache, which does exactly this and adds size bounds, expiry and stats, plus a timeout and circuit breaker on the client itself.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 24
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A team caches remote lookups with cache.computeIfAbsent(userId, id ->...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/ecc33d6390/