A deadlock is a situation in multithreaded programming where two or more threads are blocked forever, each waiting for the other to release a lock.
It’s like two people trying to pass each other in a narrow hallway:
- Person A won’t move until Person B moves,
- and Person B won’t move until Person A moves.
→ So neither moves – and that’s deadlock.
🧱 Deadlock Conditions (Coffman Conditions)
For a deadlock to occur, all four of these must be true:
- Mutual Exclusion – Only one thread can hold a lock at a time.
- Hold and Wait – A thread holding a lock is waiting to acquire another lock held by another thread.
- No Preemption – Locks can’t be forcibly taken; they must be released voluntarily.
- Circular Wait – There’s a cycle of threads, each waiting on a lock held by the next in the cycle.
public class DeadlockExample {
static final Object Lock1 = new Object();
static final Object Lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (Lock1) {
System.out.println("Thread 1: Holding Lock1...");
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
System.out.println("Thread 1: Waiting for Lock2...");
synchronized (Lock2) {
System.out.println("Thread 1: Acquired Lock2.");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (Lock2) {
System.out.println("Thread 2: Holding Lock2...");
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
System.out.println("Thread 2: Waiting for Lock1...");
synchronized (Lock1) {
System.out.println("Thread 2: Acquired Lock1.");
}
}
});
t1.start();
t2.start();
}
}
🧠 What Happens Here?
t1locksLock1and waits forLock2.t2locksLock2and waits forLock1.- Both threads wait forever → 💥 deadlock.
🛡️ How to Avoid Deadlocks
- Lock ordering: Always acquire locks in a consistent global order.
- Try-and-timeout: Use
tryLock()with timeout (fromReentrantLock) to back out if deadlock might occur. - Avoid nested locks: Minimize holding multiple locks at once.
- Deadlock detection: Use tools or thread dumps to analyze blocked threads.