Skip to the page

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.

The 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

  1. What is a race condition? Show one.
  2. This request counter uses a ConcurrentHashMap and still lets 120 requests through. Why?
  3. AtomicInteger, synchronized or a lock: how do you choose?
  4. How do you test for a race?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview