Topic 5.6
Deadlocks
In one line
Thread A holds lock 1 and wants lock 2; thread B holds lock 2 and wants lock 1 — both wait forever.
Think of it like this
Two cars meeting nose-to-nose on a narrow bridge, each waiting for the other to reverse first. Neither will move unless a rule (like 'always give way to the one on the right') breaks the standoff.
Key ideas
- 01
Four conditions (all must hold): mutual exclusion, hold-and-wait, no preemption, circular wait.
- 02
Fix each: no sharing, acquire-at-once, timeout tryLock, global lock order.
- 03
Interviews: spot the cycle in a design (two services locking each other's rows) and prescribe ordering.
- 04
Lock order mantra: sort resource IDs before locking → no cycles possible.
- 05
tryLock(timeout) converts deadlock into a timeout error — better than a hang.
- 06
Distributed deadlock (HLD): two services holding DB rows → same fix, plus saga/compensation.
Java / Spring map
- →
ReentrantLock.tryLock(2, SECONDS); consistent ordering via Comparator on resource ids.
Code & diagrams
Explain without notes
Why does acquiring resources in sorted-ID order guarantee no circular wait?
Practice
Draw the cycle in 'transfer money' between two accounts locked in send-first order and fix the order.
Trade-offs
- ↔
Timeouts trade liveness for fake latency spikes; ordering trades flexibility for safety.
Completion checklist
I can name the four conditions and show two independent fixes.