Concurrency in LLD · core
Race conditions and atomic updates
A race happens when two threads read, check and write shared data in separate steps. A thread-safe map is not enough. Make the whole read-check-write one atomic step.
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
- HashMap is not thread-safe. Concurrent puts can lose entries or corrupt the table.
- Even ConcurrentHashMap does not fix read-check-write. Two threads read 99, both allow, both write 100. More than 100 requests get through and an update is lost.
- Atomic fix: counts.computeIfAbsent(userId, k -> new AtomicInteger()) then incrementAndGet() <= limit. Or a compare-and-set loop that never passes the limit, or compute() that returns the new count.
- Compound operations on a store (putIfAbsent, increment) use compute or merge, not get then put.
- synchronized on the whole method is correct but makes every user wait on one lock. A lock per user (or per bucket) keeps throughput.
- A volatile int counter is not atomic for increments.
- Test: start many threads together with a start latch, call allow for one user many times, and assert that exactly 100 are allowed. Repeat the run.
- Python GIL does not make read-modify-write atomic, so use a Lock. Node.js runs one thread for your code, but a gap across await can still interleave.
The red pen
Common traps: mistake → fix
Mistake: ConcurrentHashMap makes the code thread-safe
Fix: single calls are safe; check-then-act across calls is not.
Mistake: A volatile counter is enough
Fix: volatile gives visibility, not atomic increment.
Mistake: A global lock with blocking input and output inside is fine
Fix: it makes all users wait.
Easy to hard
Questions interviewers ask, easy to hard
- What is a race condition? Show one.
- This request counter uses a ConcurrentHashMap and still lets 120 requests through. Why?
- AtomicInteger, synchronized or a lock: how do you choose?
- How do you test for a race?
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.