Deadlock: Conditions, Detection and Prevention

Difficulty: Advanced

Question

What is a deadlock? Write code that can deadlock, explain the four conditions, and describe how to detect and prevent it.

Answer

A deadlock is what happens when two people each hold one key of a two-key safe and refuse to hand over their key until the other one gives up his. Nobody moves, forever. In Java, that means threads blocked permanently, each waiting for a lock held by another, and your service silently stops making progress without any exception or crash. That silent nature is what makes deadlocks so scary in production.

Here is the classic scenario. Thread 1 executes synchronized(A) and then tries to take B. Thread 2 executes synchronized(B) and then tries to take A. If Thread 1 gets A and Thread 2 gets B at roughly the same time, each now waits for the lock the other holds. Neither can proceed. A real-life version is a bank transfer: transfer(from, to) locks the from account first and then the to account. If one thread transfers X to Y while another transfers Y to X, they lock in opposite orders and can deadlock.

Theory says a deadlock needs four Coffman conditions simultaneously. Mutual exclusion: a resource can be held by only one thread. Hold and wait: a thread holds a resource while waiting for another. No preemption: locks cannot be forcibly taken away. Circular wait: there is a cycle of threads each waiting for a resource held by the next. Break any one condition and deadlock becomes impossible.

Prevention techniques, ranked by how often you use them. The best and cheapest is consistent lock ordering: define a global order (for example by account id or System.identityHashCode with a tie-breaker) and always acquire locks in that order. This breaks circular wait. Second, use timeouts with ReentrantLock.tryLock(timeout): if you cannot get the second lock within a time, release the first, back off and retry, which breaks hold and wait. Third, reduce lock scope and avoid calling foreign or overridable code (callbacks, listeners) while holding a lock. Fourth, prefer higher-level constructs: concurrent collections, atomic classes and immutable objects that avoid locks entirely. Fifth, hold only one lock at a time when the design allows.

Detection: Java can spot deadlocks. Take a thread dump with jstack pid, jcmd pid Thread.print, or kill -3, and the JVM prints a section titled Found one Java-level deadlock listing the threads and which monitors they own and wait for. VisualVM and JConsole show it too, and programmatically ThreadMXBean.findDeadlockedThreads returns the deadlocked thread ids so you can build health checks. Once a deadlock exists in a JVM, the only cure is restarting the process, since synchronized blocks cannot be interrupted.

Related liveness problems: livelock, where threads keep responding to each other and changing state but make no progress (two people repeatedly stepping aside in a corridor); and starvation, where a thread never gets CPU or a lock because others always win, which can be improved with fair locks such as new ReentrantLock(true).

In an interview, after writing the code, show the fix by imposing an ordering, and mention thread dumps for diagnosis. That complete story is what gets you a strong hire signal.

Code examples

Deadlock-prone code (do not run in production)

public class DeadlockRisk {
    static final Object A = new Object();
    static final Object B = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (A) {
                pause();
                synchronized (B) {
                    System.out.println("T1 done");
                }
            }
        }).start();
        new Thread(() -> {
            synchronized (B) {
                pause();
                synchronized (A) {
                    System.out.println("T2 done");
                }
            }
        }).start();
    }

    static void pause() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
    }
}

Each thread takes its first lock, sleeps to let the other take its lock, then waits forever for the second lock. The program hangs without printing anything; jstack would report a Java-level deadlock.

Fix with a global lock order

public class OrderedTransfer {
    static class Account {
        final int id;
        int balance;
        Account(int id, int balance) {
            this.id = id;
            this.balance = balance;
        }
    }

    static void transfer(Account from, Account to, int amount) {
        Account first = from.id < to.id ? from : to;
        Account second = first == from ? to : from;
        synchronized (first) {
            synchronized (second) {
                from.balance -= amount;
                to.balance += amount;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Account x = new Account(1, 1000);
        Account y = new Account(2, 1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                transfer(x, y, 1);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                transfer(y, x, 1);
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(x.balance + " " + y.balance);
    }
}

Both threads always lock the account with the smaller id first, so a circular wait is impossible. The two opposite transfers cancel each other out.

Key points

Common follow-up questions

Interview tips

Concepts covered

Deadlock, Lock Ordering, tryLock, Livelock, Starvation

More Core Java & Collections questions