Notes
The race
Here is the race. Gate A asks if spot seven is free, and it is. Before Gate A writes its car in, Gate B asks the same question, and the spot is still free. Both gates park. Both drivers get a ticket for spot seven. Each thread did the right thing on its own. The bug lives in the gap between the check and the write, when another thread can sneak in.
Check-then-act
This shape is called check then act. You read a value, make a decision, then write, assuming the value has not changed in between. Without protection, that assumption is false. A race condition is any bug where the result depends on the timing of threads. These bugs are rare, so they slip through tests, and they get worse exactly when traffic is highest.
boolean park(String plate) {
if (this.plate == null) { // check
// another thread can run here
this.plate = plate; // act
return true;
}
return false;
} Lost updates
The second classic race is the lost update. Adding one to a counter looks like one step, but it is three: read the value, add one, write it back. If two threads both read forty one, both write forty two, and one increment vanishes. The occupancy counter drifts, and the board says a full lot has space. The same bug hits any balance plus equals amount style of code.
- count++ is really:
- 1 read count (say 41)
- 2 add one (42)
- 3 write 42
- two threads both read 41,
- both write 42:
- one car entry is lost
- same bug: balance += amount
synchronized
The simplest fix is the synchronized keyword. Every Java object has a built in lock called a monitor. A synchronized method takes the object's monitor before running and releases it after, even if an exception is thrown. Gate B now waits until Gate A has finished both the check and the write, then sees the spot is taken. The check and the act became one atomic step. Synchronized also makes Gate A's write visible to Gate B.
synchronized boolean park(String p) {
if (plate == null) {
plate = p;
return true;
}
return false;
} ReentrantLock
ReentrantLock does the same job as an object with more control. You can try for the lock with a timeout and give up instead of waiting forever, you can wait in a way that responds to interruption, and you can ask for a fair lock that serves threads in order. The price is discipline: always unlock in a finally block. Forget it once and every other gate waits forever. Reentrant means the thread that holds it can lock it again without blocking itself.
private final Lock lock =
new ReentrantLock();
lock.lock();
try {
if (plate == null) { plate = p; ...}
} finally {
lock.unlock(); // always
}
lock.tryLock(50, MILLISECONDS) Compare-and-set
For a single value, atomics are often cleaner. Compare and set says: if the current value is still what I expect, replace it, all in one step done by the hardware. The spot keeps its owner in an AtomicReference. Gate A swaps empty for car A and wins. Gate B tries to swap empty for car B, but the value is no longer empty, so it fails and picks another spot. No lock, no waiting. AtomicInteger does the same for counters.
AtomicReference<String> owner =
new AtomicReference<>();
boolean park(String plate) {
return owner.compareAndSet(null, plate);
}
AtomicInteger free = ...;
free.decrementAndGet(); Retry loops
When a compare and set fails, you read the new value and try again. Methods like update and get run that retry loop for you. If many threads hammer one counter, LongAdder spreads the work across cells and is faster. But atomics protect one variable at a time. If two values must change together, like marking a spot taken and recording the ticket, use a lock around both.
- CAS fails: read again, retry
- updateAndGet(x -> x - 1)
- does the loop for you
- heavy contention on a
- counter: LongAdder
- two values that must change
- together (spot + ticket):
- use a lock
ConcurrentHashMap
Shared maps are next. A ConcurrentHashMap is safe for many threads at once, but only per call. Checking contains key and then calling put is check then act again, and two gates could both issue a ticket for the same plate. Use the atomic methods instead: put if absent, compute if absent, and merge for counting. Each one does the check and the write together.
// wrong: check-then-act again if (!tickets.containsKey(plate)) tickets.put(plate, ticket); // right: one atomic call tickets.putIfAbsent(plate, ticket); entries.merge(gate, 1, Integer::sum); tickets.computeIfAbsent(k, f);
Visibility
There is a quieter problem: visibility. Processors keep values in caches and registers, and the compiler may reorder or hoist reads. So when Gate B sets a lot closed flag, Gate A's loop might keep reading an old copy forever. The Java memory model only promises that a write is seen when there is a happens before link, created by locks, volatile fields, thread start and join, and the concurrent classes.
volatile
Marking a field volatile fixes visibility. Every write goes where other threads will see it, and every read gets the latest value. It is perfect for a simple flag like open or closed. But volatile does not make compound actions atomic. A volatile counter with plus plus is still three steps and still loses updates. Use volatile for flags and published references, and atomics or locks for anything that reads then writes.
private volatile boolean open = true;
// gate thread
while (open) { serveNextCar(); }
// admin thread
open = false; // seen promptly
volatile int count;
count++; // STILL a race Deadlock
Locks bring their own danger: deadlock. Gate A holds the first lock and waits for the second, while Gate B holds the second and waits for the first. Neither ever moves. The standard fix is a global lock order: when you need two spots, always lock the lower spot id first. Other habits help too: use try lock with a timeout, keep locked sections short, and never call unknown code while holding a lock.
- A holds lock 1, wants lock 2
- B holds lock 2, wants lock 1
- nobody moves, ever
- fixes:
- • always lock in one order
- (e.g. by spot id)
- • tryLock with a timeout
- • keep locked code short
- • never call outside code
- while holding a lock
Best fix: no sharing
Often the best fix is to avoid shared mutable state. Immutable objects, like Java records with final fields, can be shared by any number of threads with no locks at all. Confinement means only one thread ever touches some data. And when state must be shared and changed, keep it inside one small class and guard it there, so the thread safety story fits in one sentence during the interview.
- immutable objects: records
- with final fields, safe to
- share freely
- confinement: data owned by
- one thread only
- small shared core: keep
- mutable state in one class
- and guard it there
Pick the right tool
Here is a quick guide. A single flag: volatile. A counter: an atomic integer, or LongAdder under heavy load. Claiming one slot: compare and set. A shared map: ConcurrentHashMap with its atomic methods. Several values that must change together: synchronized or a lock. Need a timeout or fairness: ReentrantLock. Choosing the smallest tool that fits keeps code fast and easy to reason about.
- one flag: volatile
- one counter: AtomicInteger
- or LongAdder
- claim one slot: CAS
- shared map: ConcurrentHashMap
- + its atomic methods
- several values together:
- synchronized or a Lock
- need timeout or fairness:
- ReentrantLock
In LLD interviews
Every serious LLD problem asks this. Two gates and one spot, two users and one cinema seat, shared rate limiter counters, the last item in stock. Say which state is shared, describe the race, and name the exact fix. Common mistakes: making every method synchronized without thinking, locking on a new object each call so nothing is protected, and sharing a plain HashMap between threads.
- parking lot: two gates,
- one spot
- movie booking: two users,
- one seat
- rate limiter: shared counters
- inventory: last item in stock
- mistakes: synchronize every
- method; lock on a new object;
- HashMap shared across threads