Skip to lesson

What is a deadlock?

Two bank transfers run at the same time, each locking an account and then waiting for the other one. Nothing crashes and nothing prints; the program just freezes. Why does this happen?

Deadlock: two transfers locking in opposite order

A deadlock is when two or more threads each hold a lock the other needs, so all of them wait forever.

A deadlock happens when thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Neither thread will ever let go, so both wait forever.

A circle: Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Each thread needs the lock the other one holds, so neither can move.

Example 1 · Two transfers that deadlock every time

TransferDeadlockDemo.javaJava
import java.util.concurrent.CountDownLatch;
class Account {    private final String owner;    private int balance;
    Account(String owner, int balance) {        this.owner = owner;        this.balance = balance;    }
    String owner() { return owner; }    int balance() { return balance; }    void add(int amount) { balance += amount; }}
public class TransferDeadlockDemo {    static final CountDownLatch bothHoldFirstLock = new CountDownLatch(2);
    static void transfer(Account from, Account to, int amount) throws InterruptedException {        synchronized (from) {                 // lock 1            bothHoldFirstLock.countDown();            bothHoldFirstLock.await();            synchronized (to) {               // lock 2: never granted                from.add(-amount);                to.add(amount);            }        }    }
    static Thread transferThread(Account from, Account to, int amount, String name) {        Thread t = new Thread(() -> {            try {                transfer(from, to, amount);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, name);        t.setDaemon(true);        return t;    }
    public static void main(String[] args) throws InterruptedException {        Account asha = new Account("Asha", 1000);        Account ravi = new Account("Ravi", 500);
        Thread t1 = transferThread(asha, ravi, 100, "transfer-1");        Thread t2 = transferThread(ravi, asha, 50, "transfer-2");        t1.start();        t2.start();
        t1.join(1000);   // wait at most 1 second        t2.join(1000);
        System.out.println("After waiting 1 second each:");        System.out.println(t1.getName() + " alive: " + t1.isAlive() + ", state: " + t1.getState());        System.out.println(t2.getName() + " alive: " + t2.isAlive() + ", state: " + t2.getState());        System.out.println("Asha: Rs " + asha.balance() + ", Ravi: Rs " + ravi.balance());    }}
Output
After waiting 1 second each:
transfer-1 alive: true, state: BLOCKED
transfer-2 alive: true, state: BLOCKED
Asha: Rs 1000, Ravi: Rs 500

What this code does

  • The CountDownLatch is only there to force the bad timing on every run: each thread takes its first lock, counts down, and waits until the other thread holds its first lock too. Real code has no latch; there the timing happens only sometimes.
  • After the waits, both threads are still alive and BLOCKED: each is waiting to enter a synchronized block whose lock the other thread holds. No money moved, so the balances are unchanged.
  • Both threads are daemon threads, so the JVM can exit while they are stuck. With normal threads this program would never end.

The classic case is a bank transfer that locks the sender's account first and then the receiver's. Transfer 1 sends money from Asha to Ravi, so it locks Asha, then Ravi. Transfer 2 sends money from Ravi to Asha at the same moment, so it locks Ravi, then Asha. Each one gets its first lock and then waits for the other one's.

Every deadlock program in this module ends by itself: the stuck threads are daemon threads and main waits with a timeout. Do the same in your own experiments.

A program that hangs without an error

A deadlock gives no exception, no stack trace and no message. The stuck threads are BLOCKED (waiting to enter a synchronized block) or WAITING (waiting for a Lock), so they use almost no CPU.

Example 2 · No error, but the JVM can find the cycle

BerthSwapHangDemo.javaJava
import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.Arrays;import java.util.Comparator;import java.util.concurrent.CountDownLatch;
class Berth {    final String label;    String passenger;
    Berth(String label, String passenger) {        this.label = label;        this.passenger = passenger;    }}
public class BerthSwapHangDemo {    static final CountDownLatch bothHoldFirstLock = new CountDownLatch(2); // demo only
    // swap the passengers of two berths: lock mine, then the other one    static void swap(Berth mine, Berth other) throws InterruptedException {        synchronized (mine) {            bothHoldFirstLock.countDown();            bothHoldFirstLock.await();            synchronized (other) {                String p = mine.passenger;                mine.passenger = other.passenger;                other.passenger = p;            }        }    }
    static Thread swapThread(Berth mine, Berth other, String name) {        Thread t = new Thread(() -> {            try {                swap(mine, other);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, name);        t.setDaemon(true);        return t;    }
    public static void main(String[] args) throws InterruptedException {        Berth lower = new Berth("S4-17 lower", "Meena");        Berth upper = new Berth("S4-20 upper", "Kabir");
        Thread s1 = swapThread(lower, upper, "swap-1");        Thread s2 = swapThread(upper, lower, "swap-2");        s1.start();        s2.start();
        System.out.println("Main: waiting up to 1 second for both swaps...");        s1.join(1000);        s2.join(1000);        System.out.println("swap-1 finished? " + !s1.isAlive());        System.out.println("swap-2 finished? " + !s2.isAlive());        System.out.println("No exception, no error message. Asking the JVM:");
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();        long[] ids = mx.findDeadlockedThreads();      // null when there is no deadlock        ThreadInfo[] infos = mx.getThreadInfo(ids);        Arrays.sort(infos, Comparator.comparing(ThreadInfo::getThreadName));        for (ThreadInfo info : infos) {            System.out.println(info.getThreadName() + " is " + info.getThreadState()                    + ", waiting for a lock held by " + info.getLockOwnerName());        }    }}
Output
Main: waiting up to 1 second for both swaps...
swap-1 finished? false
swap-2 finished? false
No exception, no error message. Asking the JVM:
swap-1 is BLOCKED, waiting for a lock held by swap-2
swap-2 is BLOCKED, waiting for a lock held by swap-1

What this code does

  • Two passengers swap berths at the same moment, each locking their own berth first. join(1000) gives each swap one second; both are still running afterwards, and no exception was thrown.
  • findDeadlockedThreads() returns the ids of the stuck threads. getThreadInfo turns them into ThreadInfo objects, and getLockOwnerName() names the thread that holds the lock each one is waiting for.
  • The report shows the cycle in plain words: swap-1 waits for swap-2, and swap-2 waits for swap-1.

From the outside, the program or one of its features just freezes. If main calls a plain join() on a deadlocked thread, main waits forever too. join(timeout) returns after the timeout, so you can notice the problem and report it.

The JVM can find deadlocks for you. ManagementFactory.getThreadMXBean().findDeadlockedThreads() returns the ids of the threads stuck in a lock cycle, or null when there is none. The "Read a thread dump" lesson shows the same information from outside the program.

The four conditions for deadlock

A deadlock can happen only when all four of these conditions are true at the same time. They are called the Coffman conditions, after E. G. Coffman, who described them with two colleagues in 1971.

Example 3 · Three roommates: a circular wait with three threads

HostelCycleDemo.javaJava
import java.lang.management.ManagementFactory;import java.lang.management.MonitorInfo;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;import java.util.Map;import java.util.concurrent.CountDownLatch;
class Item {    final String name;    Item(String name) { this.name = name; }}
public class HostelCycleDemo {    static final CountDownLatch allHoldOne = new CountDownLatch(3); // demo only    static final Map<Integer, String> nameOfLock = new HashMap<>();
    static void borrow(Item have, Item want) throws InterruptedException {        synchronized (have) {               // hold one item...            allHoldOne.countDown();            allHoldOne.await();            synchronized (want) {           // ...and wait for the next one                System.out.println("never printed");            }        }    }
    static Thread roommate(Item have, Item want, String name) {        nameOfLock.put(System.identityHashCode(have), have.name);        Thread t = new Thread(() -> {            try {                borrow(have, want);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, name);        t.setDaemon(true);        return t;    }
    public static void main(String[] args) throws InterruptedException {        Item iron = new Item("Iron");        Item kettle = new Item("Kettle");        Item charger = new Item("Charger");
        Thread[] all = {            roommate(iron, kettle, "roommate-1"),            roommate(kettle, charger, "roommate-2"),            roommate(charger, iron, "roommate-3")        };        for (Thread t : all) t.start();        for (Thread t : all) t.join(500);
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();        ThreadInfo[] infos = mx.getThreadInfo(mx.findDeadlockedThreads(), true, false);        Arrays.sort(infos, Comparator.comparing(ThreadInfo::getThreadName));        System.out.println("Deadlocked threads: " + infos.length);        for (ThreadInfo info : infos) {            MonitorInfo held = info.getLockedMonitors()[0];            String holds = nameOfLock.get(held.getIdentityHashCode());            String wants = nameOfLock.get(info.getLockInfo().getIdentityHashCode());            System.out.println(info.getThreadName() + " holds " + holds + ", waits for "                    + wants + " (held by " + info.getLockOwnerName() + ")");        }    }}
Output
Deadlocked threads: 3
roommate-1 holds Iron, waits for Kettle (held by roommate-2)
roommate-2 holds Kettle, waits for Charger (held by roommate-3)
roommate-3 holds Charger, waits for Iron (held by roommate-1)

What this code does

  • Each roommate holds one item and waits for the next; the last one waits for the first. That is a circular wait with three threads instead of two.
  • All four conditions are true: one owner per item (mutual exclusion), each keeps their item while waiting (hold and wait), nobody can grab an item from another (no preemption), and the waits form a closed chain (circular wait).
  • getLockedMonitors() lists the locks a thread holds and getLockInfo() describes the lock it waits for. The demo turns them into item names with System.identityHashCode.
  • Mutual exclusion: a lock can be held by only one thread at a time.
  • Hold and wait: a thread keeps the locks it already has while it waits for another one.
  • No preemption: nobody can take a lock away from a thread; the thread must release it itself.
  • Circular wait: there is a closed chain of threads, each waiting for a lock held by the next one.

Break any one of them and a deadlock cannot happen. Every fix in the next lesson works by breaking one condition, most often circular wait.

Why a deadlock appears only sometimes

A deadlock needs bad timing: both threads must take their first lock before either one takes its second. Taking a lock takes a tiny moment, so most of the time one thread grabs both locks and finishes before the other starts.

Example 4 · The same bug without forcing: sometimes stuck, sometimes fine

DeadlockSometimesDemo.javaJava
class Wallet {    int balance = 1_000_000;}
public class DeadlockSometimesDemo {    // the same opposite-order bug, with no latch to force the timing    static void transfer(Wallet from, Wallet to, int amount) {        synchronized (from) {            synchronized (to) {                from.balance -= amount;                to.balance += amount;            }        }    }
    static Thread start(Wallet from, Wallet to, String name) {        Thread t = new Thread(() -> {            for (int i = 0; i < 5_000; i++) {                transfer(from, to, 1);            }        }, name);        t.setDaemon(true);        t.start();        return t;    }
    public static void main(String[] args) throws InterruptedException {        int stuck = 0;        for (int trial = 1; trial <= 10; trial++) {            Wallet a = new Wallet();            Wallet b = new Wallet();            Thread t1 = start(a, b, "t1-trial" + trial);            Thread t2 = start(b, a, "t2-trial" + trial);            t1.join(200);            t2.join(200);            boolean deadlocked = t1.isAlive() || t2.isAlive();            if (deadlocked) stuck++;            System.out.println("Trial " + trial + ": " + (deadlocked ? "DEADLOCKED" : "finished"));        }        System.out.println("Deadlocked in " + stuck + " of 10 trials");    }}
Sample output
Trial 1: DEADLOCKED
Trial 2: DEADLOCKED
Trial 3: DEADLOCKED
Trial 4: finished
Trial 5: finished
Trial 6: finished
Trial 7: finished
Trial 8: finished
Trial 9: finished
Trial 10: finished
Deadlocked in 3 of 10 trials

What this code does

  • No latch this time. Each trial starts two threads that make 5,000 transfers each in opposite directions, then waits 200 ms for them.
  • Your result will differ on every run: one run here froze in 3 of 10 trials, the next run in only 1. On another machine it could be 0 or 10. The bug is always in the code; only the timing changes.
  • Stuck trials do not stop the program, because the threads are daemon threads and each trial uses fresh wallets.

The thread scheduler decides that timing, and it changes with CPU load, the number of cores and other programs on the machine. So the same code can pass every test on your laptop and freeze once a week on a busy server, for example during the Tatkal booking rush. That is why running a program can never prove it is free of deadlock. You prove it by reading the code: if two threads can take the same locks in different orders, a deadlock is possible.

Find the bug

Spot the line that can deadlock

Two threads may run this code at the same time. Click the risky line.

Two transfers run together: transfer(a, b) and transfer(b, a).

Round 1 of 3

Next step

Check your understanding

11 quick questions