The 30 second answer
Reads usually don't block, and writes lock only a small part of the table, so many threads work at once. Each single call is atomic, and compute, computeIfAbsent and merge are atomic per key. But check-then-act across two calls can still race, so I use putIfAbsent or compute instead. Size and iteration are only estimates during writes, and null keys or values are not allowed.
Reads usually don't block, and updates lock only a small part of the table, so many threads can work at once. Each single call is atomic, and compute, computeIfAbsent and merge run atomically per key. But a sequence like if (!map.containsKey(k)) map.put(k, v) is two calls and can race; use putIfAbsent or compute. size() and iteration are only estimates while others write, and it doesn't allow null keys or values. Follow-up: How do you count frequencies safely? (map.computeIfAbsent(k, x -> new LongAdder()).increment(), the example in the Javadoc.)
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent("shoes", k -> new LongAdder()).increment(); // safe from many threads
// Racy: two calls, another thread can insert in between
if (!cache.containsKey(k)) cache.put(k, load(k));
// Atomic per key: load runs at most once for k
cache.computeIfAbsent(k, key -> load(key));Alternate interview scenarios
"Design a concurrent in-memory cache with high read throughput, automatic expiration and safe updates."
A ConcurrentHashMap gives lock-free reads and atomic computeIfAbsent, which loads each missing key only once, so many threads asking for the same key do not all hit the database. But a ConcurrentHashMap has no size limit and no expiry. If I build those myself, I need a timestamp per entry, a sweeper or lazy expiry check on read, and an eviction policy. Getting those right under concurrency is the hard part. In practice I use Caffeine, which provides size-bound eviction, expireAfterWrite or expireAfterAccess, and refreshAfterWrite to reload a hot key in the background. One caveat: the loading function inside computeIfAbsent must be short and must not touch the same map, because it runs while that key's bin is locked.
Sources (2)
- ConcurrentHashMap Javadoc (Java 21)docs.oracle.com
- Caffeine wiki: Eviction (size, time-based expiration)github.com