Lesson 4 of 9 · 24m
Deadlocks, Livelocks, and Lock Ordering
Why deadlocks are usually design bugs rather than scheduling accidents, how lock ordering prevents them, and what to do when a production process wedges.
Deadlock rarely arrives as a dramatic crash. It arrives as a service that is up, accepts connections, and stops doing work. CPU is low, memory is stable, health checks may even pass. Then a thread dump shows twenty threads waiting in a perfect circle. Deadlocks feel nondeterministic, but almost all of them are deterministic consequences of inconsistent lock acquisition order.
The canonical deadlock needs four conditions
A deadlock requires all four of these at once:
- mutual exclusion and hold-and-wait — exclusive resources are held while threads wait for more
- no preemption and circular wait — ownership cannot be revoked and the wait chain loops
You prevent deadlock by breaking one condition deliberately. In application code the practical target is usually circular wait: impose a global order and never acquire locks out of order.
Inconsistent transfer order is the classic bug
def transfer(src, dst, amount):
with src.lock:
with dst.lock:
src.balance -= amount
dst.balance += amounttransfer(a, b) acquires a then b; a concurrent transfer(b, a) acquires b then a. If the timing lines up, each thread holds what the other wants. The fix is to order locks by a stable key:
def transfer(src, dst, amount):
first, second = sorted((src, dst), key=lambda account: account.id)
with first.lock:
with second.lock:
src.balance -= amount
dst.balance += amountNotice that the lock order is independent of the operation direction. That is the whole point.
Timeouts detect pain; they do not fix design
try_lock with timeout can keep a wedged system alive, but it changes correctness semantics. If acquisition fails, you must unwind partial work and retry safely. Random backoff can avoid synchronized retries, but it can also create livelock: threads repeatedly acquire, notice conflict, release, and collide again forever.
if (left.tryLock(50, TimeUnit.MILLISECONDS)) {
try {
if (right.tryLock(50, TimeUnit.MILLISECONDS)) {
try {
move(left, right, amount);
} finally {
right.unlock();
}
}
} finally {
left.unlock();
}
}This is appropriate for a bounded subsystem with careful retry logic. It is not a substitute for ordering when ordering is possible.
Deadlock detection in production
The two most useful artifacts are thread dumps and lock ownership graphs. For the JVM, jcmd <pid> Thread.print shows which monitor each thread owns and which one it waits for. On Linux, gdb -p <pid> -batch -ex 'thread apply all bt' can do the same for native code, provided symbols are available.
A graph is simple: nodes are threads or locks, edges are "holds" and "waits for." Any cycle is a deadlock. Many runtimes can find obvious cycles automatically, but application-level lock ordering still needs human review.
Field notes
- Health checks that only test the network socket will happily report a deadlocked service as healthy.
- Lock ordering must include indirect acquisition through callbacks, virtual methods, and dependency injection.
- Never acquire subsystem locks in the order dictated by user input. Canonicalize first.
- Measure lock wait separately from execution time; random sleeps hide deadlocks rather than fixing them.
Was this lesson helpful?