What they're testing
Whether you know this is a structured problem rather than bad luck.
The short answer~30 seconds
The four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, and circular wait. In practice I break the last: always acquire locks in a fixed GLOBAL ORDER — for instance sorting ids ascending before locking. It costs essentially nothing, needs no detection machinery, and turns deadlock from a random incident into an impossibility.
The long answer
The canonical example is a transfer: transfer(A, B) locks A then B while a concurrent transfer(B, A) locks B then A — and both stop forever. The fix is locking the lower id first regardless of direction. One sort eliminates an entire class of incident, and it's the most memorable example to reach for in an interview.
Breaking hold-and-wait is the second option: acquire ALL needed locks at once, and on failure release everything and retry. It avoids deadlock and opens the door to livelock — both sides releasing and retrying in step — so it needs randomised backoff. Which is why lock ordering is usually preferred: it doesn't trade one problem for another.
In a database you break none of them — the engine detects the cycle and aborts one transaction. Which means the application MUST handle the deadlock error with a retry, and MySQL additionally records the details in SHOW ENGINE INNODB STATUS so you can find the offending pair of statements.
// Deadlock: thứ tự khoá phụ thuộc vào tham số
void transfer(Account a, Account b, long amount) {
synchronized (a) { synchronized (b) { /* … */ } }
}
// An toàn: thứ tự khoá là toàn cục, không phụ thuộc lời gọi
void transfer(Account a, Account b, long amount) {
Account first = a.id() < b.id() ? a : b;
Account second = a.id() < b.id() ? b : a;
synchronized (first) { synchronized (second) { /* … */ } }
}What they'll ask next
?How is livelock different from deadlock?
In a deadlock the threads are stopped; in a livelock they keep running and burning CPU without progressing — like two people repeatedly stepping aside the same way. Harder to spot, because every metric looks like a system doing work.
These lose points
- Proposing a timeout as the main solution. It converts a permanent hang into a periodic error — better, but tolerating rather than fixing.
Sources
- Coffman, Elphick, Shoshani — System Deadlocks (1971), the four conditions
- MySQL — InnoDB Deadlocks: detection and reading the log