Deadlocks
The four Coffman conditions, resource allocation graphs, prevention, avoidance (Banker's algorithm), detection and recovery, plus livelock and starvation.
A deadlock is a set of threads each waiting for a resource held by another thread in the set, so none of them can ever proceed. The program doesn't crash; it just stops making progress.
The four Coffman conditions
A deadlock can happen only if all four hold at once:
| Condition | Meaning |
|---|---|
| Mutual exclusion | A resource can be held by only one thread at a time |
| Hold and wait | A thread holds resources while waiting for more |
| No preemption | Resources can't be forcibly taken away |
| Circular wait | There's a cycle of threads, each waiting for the next |
Break any one and deadlock becomes impossible.
Classic example
// Thread 1: transfer(a, b) Thread 2: transfer(b, a)
void transfer(Account from, Account to, long amt) {
synchronized (from) { // T1 locks a T2 locks b
synchronized (to) { // T1 waits for b T2 waits for a → deadlock
from.balance -= amt;
to.balance += amt;
}
}
}
// Fix: lock in a global order (e.g. by id)
void transferSafe(Account from, Account to, long amt) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) { synchronized (second) {
from.balance -= amt; to.balance += amt;
} }
}def transfer_safe(a, b, amt):
first, second = sorted((a, b), key=lambda acc: acc.id)
with first.lock, second.lock:
a.balance -= amt
b.balance += amt// Databases detect this for you: two transactions updating rows in opposite
// orders → one is aborted with "deadlock detected"; retry it.
async function transfer(db: Db, from: number, to: number, amt: number) {
const [x, y] = from < to ? [from, to] : [to, from]; // consistent order
await db.tx(async (t) => {
await t.query("SELECT ... WHERE id IN ($1, $2) ORDER BY id FOR UPDATE", [x, y]);
// ... update both rows
});
}Four ways to handle deadlock
1. Prevention — make a condition impossible
| Break | Technique | Cost |
|---|---|---|
| Mutual exclusion | Use shareable resources (read-only data, lock-free structures) | Not always possible |
| Hold and wait | Acquire all resources at once, or release everything before requesting more | Low utilisation; must know needs upfront |
| No preemption | If a request fails, release what you hold and retry (tryLock with timeout) | Can livelock; wasted work |
| Circular wait | Global ordering of resources | Discipline — the most practical |
2. Avoidance — only grant safe requests
The system knows each thread's maximum need and grants a request only if the resulting state is safe: there's some order in which every thread can finish. Banker's algorithm:
- Let
Availablebe the free resources andNeed = Max − Allocationfor each thread. - Find a thread whose
Need ≤ Available. Pretend it runs to completion and releases its allocation:Available += Allocation. - Repeat. If every thread can finish, the state is safe; otherwise it's unsafe and the request must wait.
Example with one resource type and 12 units:
| Thread | Max | Allocated | Need |
|---|---|---|---|
| T0 | 10 | 5 | 5 |
| T1 | 4 | 2 | 2 |
| T2 | 9 | 2 | 7 |
Available = 12 − 9 = 3. T1 can finish (2 ≤ 3) → available 5. T0 can finish (5 ≤ 5) → 10. T2 can finish (7 ≤ 10). Safe sequence: T1, T0, T2.
Elegant, but rarely used in general-purpose OSes: maximum needs are unknown, and the check costs O(m × n²).
3. Detection and recovery
Let deadlocks happen, detect cycles in the wait-for graph periodically or when a request times out, then recover by aborting a victim (or rolling it back). Databases do exactly this: PostgreSQL checks for cycles after deadlock_timeout (1 s by default) and aborts one transaction.
4. Ignore it (the ostrich algorithm)
Most OSes don't handle deadlocks among application locks at all: it's the programmer's job. The rationale is that deadlocks are rare and prevention is expensive.
Livelock and starvation
- Livelock — threads keep changing state in response to each other but make no progress, like two people stepping aside in a corridor in the same direction over and over. Common with naive "release and retry" schemes. Fix: randomised backoff.
- Starvation — a thread waits indefinitely because others are always preferred (low priority, unfair locks, writer starvation). Fix: fairness, aging.
Debugging deadlocks in practice
- Java:
jstack <pid>or a thread dump prints "Found one Java-level deadlock" with the cycle. - Python:
faulthandler.dump_traceback_later, orpy-spy dump --pid. - Databases: deadlock reports in the logs (
SHOW ENGINE INNODB STATUSin MySQL). - Use
tryLock(timeout)to fail loudly instead of hanging forever.
- Deadlock needs mutual exclusion, hold and wait, no preemption, and circular wait.
- Prevention breaks a condition; lock ordering (breaking circular wait) is the practical fix.
- Avoidance (Banker's) grants only requests that keep the system in a safe state.
- Detection finds cycles in the wait-for graph and aborts a victim, as databases do.
- Livelock = busy but no progress; starvation = indefinite waiting; fix with backoff and fairness.
QWhat are the necessary conditions for deadlock?easy
Mutual exclusion, hold and wait, no preemption, and circular wait (the Coffman conditions). All four must hold simultaneously.
QHow would you prevent deadlocks in a money-transfer service?medium
Always lock accounts in a consistent order (for example ascending account ID), keep transactions short, and use timeouts with retries. In a database, update rows in ID order, and handle deadlock-abort errors by retrying the transaction.