Concurrency · mid
Thread-safe counters and maps
ConcurrentHashMap is safe per call, but get-then-put is not atomic. Use merge, computeIfAbsent, LongAdder or a lock for the whole action, and never run slow code inside them.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Hashtable and synchronizedMap use one lock for every call. Java 7 ConcurrentHashMap used 16 segments. Java 8 and later use one table: CAS for an empty bucket, a lock on the first node for a non-empty bucket.
- No nulls:
getreturning null must mean absent. - Check-then-act is not atomic.
counts.put(m, counts.getOrDefault(m, 0) + 1)loses updates even in a ConcurrentHashMap. Usemerge(m, 1L, Long::sum)orcomputeIfAbsent(m, k -> new LongAdder()).increment(). size()is an estimate under updates;mappingCount()returns a long. Iterators are weakly consistent and never throw ConcurrentModificationException.- computeIfAbsent and compute run your function while the bucket is locked. A slow function, such as a remote call, blocks other keys in the same bucket and can use up all request threads. Do not change the same map inside it.
- Better for slow loads: Caffeine with an async loader, timeouts on the client, a fallback value and a bulkhead.
- AtomicLong uses compare-and-swap in a retry loop. LongAdder spreads updates over cells and is much faster for hot counters. Its sum is not an exact snapshot during updates.
- ReentrantLock over synchronized:
tryLockwith a timeout, interruptible waiting, fairness, several Conditions. Always unlock in finally. ReadWriteLock or StampedLock for read-heavy data. In-memory locks protect nothing across pods. The database must enforce it: a conditionalUPDATE ... WHERE balance >= :amount, row locks or optimistic locking.
The red pen
Common traps: mistake → fix
Mistake: ConcurrentHashMap makes get-then-put safe
Fix: each call is safe; the pair is not atomic.
Mistake: A flush that copies then clears is safe
Fix: updates between copy and clear are lost; swap the map atomically.
Mistake: computeIfAbsent is a good place for a remote call
Fix: it holds a bucket lock while it runs.
Easy to hard
Questions interviewers ask, easy to hard
- How does ConcurrentHashMap stay thread-safe without locking the whole map?
- Why does a ConcurrentHashMap counter still lose updates?
- AtomicLong or LongAdder for 200 threads counting API calls?
- Why did product pages hang when the pricing call became slow inside computeIfAbsent?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.