Interview frequency: …
Short answer
The four deadlock conditions are: (1) mutual exclusion; (2) hold and wait; (3) no preemption; and (4) circular wait. Breaking any one of them prevents deadlock.
Explanation
A classic deadlock occurs when Thread 1 holds lock A and waits for lock B while Thread 2 holds lock B and waits for lock A; the system stops forever. A straightforward, effective strategy is to break circular wait by enforcing lock ordering: all system threads must acquire lock A before lock B according to the same fixed hierarchy.
Code example
// Break deadlock by enforcing global lock ordering:
void transfer(Account from, Account to) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized(first) {
synchronized(second) {
// Deadlock is impossible because all operations follow the same order!
}
}
}Common mistakes
- Trying to solve deadlock with a random Thread.sleep() delay instead of fixing lock order structurally.