Topic 5.5
Race Conditions
In one line
Two threads interleave on shared state and the result depends on timing — the bug class every LLD question secretly tests.
Think of it like this
Two people grabbing for the last seat on a bus at the exact same moment. If there's no rule for who checks and who sits first, both might think they got it — and you end up with a mess (double booking).
Key ideas
- 01
Classic shape: check-then-act (isFree → occupy) or read-modify-write (balance++).
- 02
The bug is invisible: works 99.99% in dev, corrupts state under load.
- 03
Fix by construction: atomic claim operations (compute, CAS, DB row locks, synchronized block).
- 04
Describe races as interleavings out loud: 'thread A reads free=true, thread B reads free=true, both claim'.
- 05
Interview narration: 'this is a race; I make the claim atomic' — graders look for that sentence.
Java / Spring map
- →
synchronized, ConcurrentHashMap.compute, AtomicReference, SELECT…FOR UPDATE.
Code & diagrams
The bug, then the fix — side by side.
// BUGGY — check then act, two threads can both pass
class BuggySpotClaim {
private boolean free = true;
public boolean claim() {
if (free) { // T1 and T2 both see true
free = false; // then both claim
return true;
}
return false;
}
}
// FIX — the check and the set are one synchronized claim
class FixedSpotClaim {
private boolean free = true;
public synchronized boolean claim() {
if (!free) return false;
free = false;
return true;
}
}
// Or with atomics:
class AtomicSpotClaim {
private final AtomicBoolean free = new AtomicBoolean(true);
public boolean claim() { return free.compareAndSet(true, false); } // one CAS
}Explain without notes
Replay the interleaving that double-claims with the buggy version on a whiteboard.
Practice
Find a check-then-act in the Vending Machine and fix it — state exactly which method was the race.
Trade-offs
- ↔
Locks pessimistically serialize; CAS retries under contention — both acceptable until contention is extreme.
Completion checklist
I see 'check-then-act' as an immediate race alert in any design.