Threads and Races
The follow-up you will definitely get — which data is shared, what rule a collision would break, and the four techniques that answer almost every version of the question.
Almost every SDE-2 LLD round ends up here, usually as: "two users try to book the last seat at the same moment — what happens?"
First, the vocabulary, because it's used loosely everywhere.
- A thread is one flow of execution. A server handles many users by running many threads at once, and they share the same objects in memory.
- A race (or race condition) is when the result depends on which thread happens to get there first — and one of the possible orders is wrong.
- An invariant is a rule that must always hold. "A seat has at most one owner" is an invariant. A race is only a bug because it breaks one.
The difference between a vague answer ("I'd synchronise it") and a specific one ("the seat hold is a compare-and-set on the seat's status, so exactly one caller wins and the other gets SeatUnavailable") is often the difference between being levelled as junior and as SDE-2.
#The two-question drill
Whatever the system, answer in this order:
- Which data is shared and changes? Name the exact field or collection. There are usually only two or three in a whole design.
- What rule would a collision break? "A spot is assigned to at most one car." "The balance never goes negative."
Only then pick a mechanism. Jumping to synchronized without naming the data is guessing, and interviewers can tell.
- 1 1 · Make it unchangeable Nothing to race on. Free.
- 2 2 · Give it one owner One thread touches it. Also free.
- 3 3 · Use an atomic operation Compare-and-set, ConcurrentHashMap. Cheap, can't deadlock.
- 4 4 · Lock the smallest thing One seat, one account — not the whole system.
- 5 5 · Push it into the database Unique constraint, conditional update, transaction.
#1 · Unchangeable objects can't race
Most of a good design is value objects, and a value object that never changes cannot be corrupted by two threads — there's nothing for them to fight over. Say this early and you've ruled most of your classes out of the threading discussion before anyone asks:
"Money, TimeSlot and Ticket never change after they're created, so calculating a fee shares nothing. The only changing shared data here is spot occupancy and the ticket store."
Now the conversation is about two things instead of ten.
#2 · One owner needs no lock
If exactly one thread ever touches a piece of data, no protection is needed at all. This is why a lift is usually modelled with one thread per car: requests go into a queue, the car's own loop takes them out, and the car's fields have exactly one writer.
class ElevatorController {
private final BlockingQueue<Request> inbox = new LinkedBlockingQueue<>();
private final Elevator elevator; // only run() touches this
void submit(Request r) { inbox.put(r); } // any thread may call this
void run() { // one thread runs this
while (running) {
Request r = inbox.poll(100, MILLISECONDS);
if (r != null) elevator.accept(r);
elevator.step();
}
}
}Say this: "Rather than locking the lift's state, I give it a queue and one owning thread. Callers hand work over; the lift has a single writer, so its internals need no locks."
The same idea appears one level up in HLD: it's why systems give each slice of data a single owning server. See Sharding.
#3 · Atomic operations
For "grab the last one" problems, the right tool is usually compare-and-set rather than a lock.
Compare-and-set (CAS) means: change this value to B, but only if it is currently A — and tell me whether it worked. The check and the change happen as one indivisible step, so two threads cannot both succeed.
class ParkingSpot {
private final AtomicReference<Status> status = new AtomicReference<>(FREE);
/** Returns true for exactly one caller, however many race. */
boolean tryOccupy() {
return status.compareAndSet(FREE, OCCUPIED);
}
void release() { status.set(FREE); }
}Two cars, one true. The loser sees false and asks for another spot. No lock, no waiting, no deadlock possible.
The collection equivalents matter just as much:
| Instead of | Use | Why |
|---|---|---|
HashMap guarded by synchronized | ConcurrentHashMap | Readers don't block each other |
map.get then map.put | putIfAbsent / computeIfAbsent | The gap between the two is the bug |
counter++ | AtomicLong | ++ is read, add, write — three steps, not one |
ArrayList of listeners | CopyOnWriteArrayList | Each write copies the list, so a thread looping over it never sees it change mid-loop. Fine when it's read constantly and written rarely |
#4 · Real locks, at the right size
You need an actual lock when the rule spans more than one object — moving money between two accounts, moving a seat between two holds. Two things to get right.
Size. A single lock on the whole car park means one car at a time, everywhere. Lock the individual spot instead. State the trade-off: "one lock is obviously correct but makes every request wait in a single line; per-spot locks let cars at different spots proceed at the same time, and nothing needs one spot's change to happen before another's."
Order, to avoid deadlock. Deadlock is when two threads each hold something the other needs, so both wait forever. It needs two threads taking two locks in opposite orders. The standard fix is to always take them in the same order:
void transfer(Account from, Account to, Money amount) {
// always lock in the same order, by ID
Account first = from.id().compareTo(to.id()) < 0 ? from : to;
Account second = (first == from) ? to : from;
synchronized (first) {
synchronized (second) {
from.withdraw(amount);
to.deposit(amount);
}
}
}Worth knowing: deadlock needs four conditions at once, and breaking any one is enough:
- Mutual exclusion — only one thread can hold the lock.
- Hold-and-wait — a thread keeps the lock it has while waiting for another.
- No preemption — nobody can take a lock away from the thread holding it.
- Circular wait — A waits for B while B waits for A.
Ordering breaks circular wait, because nobody can hold the "later" lock while waiting for an "earlier" one. tryLock with a timeout breaks hold-and-wait: a thread that can't get the second lock gives up and releases the first.
ReentrantReadWriteLock deserves a sentence when reads hugely outnumber writes: many readers can hold it at once, but a writer must hold it alone. The catch is that constant reading can starve writers — if there's always at least one reader holding the lock, a writer may wait indefinitely.
#5 · Push it into the database
When the interviewer says "but you have five servers", in-memory tricks stop working — each server has its own copy of everything. The answer moves down a layer:
- Unique constraint — the database rejects a second row for the same seat. Simple, correct, nothing extra to run.
- Conditional update —
UPDATE seats SET status='HELD' WHERE id=? AND status='FREE', then check how many rows changed. This is compare-and-set, written in SQL. One row changed means you won. - Optimistic locking — a
versioncolumn:WHERE id=? AND version=?, incremented on write. Zero rows means someone beat you; retry or fail. - A distributed lock (Redis, ZooKeeper) — only when the thing isn't a row you can conditionally update. Say the caveats: it needs an expiry, so a crashed holder doesn't keep it forever. But that means your hold on the lock (the lease) can expire while you're still mid-operation — and another server can grab it and start working on the same thing. See Distributed Locks.
#The classic follow-ups, answered
"Two users book the last seat at the same time."
"The seat's status is the shared data; the rule is one live hold per seat. I'd make the hold a conditional change —
compareAndSet(FREE, HELD)in one process, orUPDATE … WHERE status='FREE'with a row-count check across servers. Exactly one wins; the other getsSeatUnavailableand I refresh their view. The hold carries an expiry so an abandoned checkout frees the seat — checked when the seat is next read, so it doesn't depend on a timer still being alive."
"How do you avoid deadlock?"
"Mostly by needing only one lock. Where I need two — a transfer — I always take them in the same order by ID, and use
tryLockwith a timeout so the worst case is a failed operation rather than a stuck thread."
"Is your singleton thread-safe?"
"The enum form is — Java guarantees an enum's instance is created exactly once, even with many threads. But I'd rather create one instance at startup and pass it in than use a static accessor — same single instance, testable, no global state."
"How would you test this?"
"A latch test: start N threads, hold them all at a
CountDownLatch, release them together, all callingbook(seat). Assert exactly one success and N−1 failures, and that the seat ends up consistent. Run it a few thousand times, because a race that appears one time in fifty proves nothing in a single run."
#Check yourself
What two questions come before choosing any concurrency mechanism?Show answer
List the concurrency techniques from cheapest to costliest.Show answer
Why does a lift often use one thread per car?Show answer
What is compare-and-set, and why prefer it for "grab the last one"?Show answer
What is check-then-act, and the fix?Show answer
How do you avoid deadlock in a two-account transfer?Show answer
With five servers, how do you protect "one hold per seat"?Show answer
How do you test a race?Show answer
#What to carry forward
- Name the shared changing data and the rule before picking a mechanism.
- Cheapest first: immutable, single owner, atomic, smallest lock, database.
- Check-then-act is the bug you'll actually write; make the check and change one step.
- Conditional writes — compareAndSet in memory, UPDATE … WHERE in SQL — work at both levels.
- Blanket synchronized is slow and still wrong across calls.