Deadlocks
A deadlock occurs when processes are waiting for each other in a circular chain. Four conditions must ALL be true (Coffman conditions): Mutual Exclusion (resource not sharable), Hold and Wait (holding one, waiting for another), No Preemption (can't force release), Circular Wait (A→B→C→A). Prevention: break any one condition. Detection: resource allocation graph. Recovery: kill a process, preempt resource.
Key Concepts
Deep Dive: The Four Conditions
Thread A holds Lock 1, wants Lock 2
Thread B holds Lock 2, wants Lock 1
→ Deadlock! (circular wait)
| Condition |
How to Prevent |
| Mutual Exclusion |
Use lock-free algorithms |
| Hold and Wait |
Acquire all locks at once |
| No Preemption |
Allow lock timeout |
| Circular Wait |
Lock ordering (always acquire in same order) |
Deep Dive: Deadlock in Java
// DEADLOCK EXAMPLE
Object lock1 = new Object(), lock2 = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock1) {
synchronized (lock2) { /* ... */ }
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) { // Opposite order!
synchronized (lock1) { /* ... */ }
}
});
// FIX: Use consistent lock ordering
Thread t2Fixed = new Thread(() -> {
synchronized (lock1) { // Same order as t1
synchronized (lock2) { /* ... */ }
}
});
Deep Dive: Deadlock vs Livelock vs Starvation
| Problem |
Description |
| Deadlock |
Processes blocked forever, no progress |
| Livelock |
Processes keep changing state but no progress |
| Starvation |
A process never gets resources (low priority) |
Common Interview Questions
- What is a deadlock? What are the four conditions?
- How do you prevent deadlocks?
- How do you detect a deadlock?
- What is the difference between deadlock and livelock?
- Give an example of deadlock in Java.