ConcurrentHashMap Interview Questions
KOTLIN › JVM Concurrency
How is ConcurrentHashMap different from a synchronized HashMap?
What a strong answer covers: A synchronized map uses one lock for every operation. ConcurrentHashMap allows lock-free reads and locks only a single bucket when writing (Java 8+ uses CAS for empty bins and synchronises on the bin's first node), so many threads can read and write different keys concurrently. Iterators are weakly consistent and never throw ConcurrentModificationException.
Why doesn't ConcurrentHashMap allow null keys or values?
What a strong answer covers: In a concurrent map, get returning null would be ambiguous: is the key absent, or mapped to null? With HashMap you can call containsKey afterwards, but in a concurrent map another thread could change it between the two calls. Banning nulls makes null always mean 'absent'.
Is if (!map.containsKey(k)) map.put(k, v) safe on a ConcurrentHashMap? What should you use instead?
What a strong answer covers: No: each call is thread-safe, but the check-then-act sequence isn't atomic, so two threads can both see the key missing and both put. Use putIfAbsent, computeIfAbsent, compute or merge, which are atomic per key. For counters, merge(key, 1, Int::plus) or a ConcurrentHashMap of LongAdder.
What should and shouldn't go inside computeIfAbsent's lambda?
What a strong answer covers: The lambda runs while holding the bin lock, so it should be short and side-effect free. Don't do slow I/O or network inside it (it blocks other writers to that bin), and never modify the same map from inside it, which can deadlock or throw IllegalStateException for recursive updates. For expensive values, store a Deferred or lazy and compute outside the lock.
You need an in-memory cache shared by many coroutines that loads each key once even if 50 requests ask for it simultaneously. How would you build it?
What a strong answer covers: Store the in-flight work rather than the value: ConcurrentHashMap<K, Deferred<V>> with computeIfAbsent(key) { scope.async(start = LAZY) { load(key) } }, then await it. All callers share one Deferred. Remove the entry on failure so it can be retried, and decide on expiry and size limits (an LRU). Alternatively use a Mutex per key. A strong answer covers request coalescing, failure, cancellation of a shared load, and eviction.