Deadlock of Threads
1. What Is Deadlock? (beginner — traffic jam!)
Deadlock = two threads wait for each other's lock FOREVER (A holds lock1 wants lock2, B holds lock2 wants lock1!). Both freeze! Like two doors, each holds one key!
2. Code — Classic Two-Lock Trap!
Object pen = new Object(), paper = new Object();
// Thread 1: pen → paper
new Thread(() -> {
synchronized (pen) {
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (paper) { System.out.println("wrote!"); }
}
}).start();
// Thread 2: paper → pen (OPPOSITE order — deadlock!)
new Thread(() -> {
synchronized (paper) {
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (pen) { System.out.println("drew!"); }
}
}).start();
// May freeze! (neither prints — both wait forever!)
3. Four Conditions (exam list — all needed!)
| Condition | Meaning |
|---|---|
| Mutual exclusion | lock owned by one! |
| Hold + wait | holds one, wants another! |
| No preemption | can't snatch lock! |
| Circular wait | A→B→A cycle! |
Break ANY one → no deadlock!
4. Fixes (exam!)
Same lock ORDER everywhere (both pen→paper!). Timeout (tryLock(1, SECONDS)). Fewer locks (one big lock!).
5. Exam Points
- Two-lock program + four conditions — 7 marks, very frequent.
- Fix (same order) — 3 marks, frequent.