Skip to lesson

Fix deadlocks with lock ordering

Every deadlock fix breaks one of the four conditions. The most common fix is lock ordering: if every thread takes its locks in the same order, a circle of waiting threads can never form.

Lock ordering: always lock in a fixed order

Lock ordering is a rule that every thread takes its locks in one agreed order, for example the account with the smaller id first. With one order for everybody, no circle of waiting can form.

Lock ordering means every thread takes its locks in one agreed order, for example the account with the smaller id first. Whoever gets the first lock is then the only thread that can ask for the second one.

Lock ordering. Thread A locks account 101, then 204, moves the money and unlocks. Thread B also wants 101 first, so it waits while holding no lock. When A has unlocked, B runs the same steps. No circle of waiting can form.

Example 1 · Lock the smaller id first

LockOrderingDemo.javaJava
class Account {    final int id;    final String owner;    private int balance;
    Account(int id, String owner, int balance) {        this.id = id;        this.owner = owner;        this.balance = balance;    }
    void add(int amount) { balance += amount; }    int balance() { return balance; }}
public class LockOrderingDemo {    static void transfer(Account from, Account to, int amount) {        if (from == to) {            throw new IllegalArgumentException("Cannot transfer to the same account");        }        // every thread locks the account with the smaller id first        Account first = from.id < to.id ? from : to;        Account second = from.id < to.id ? to : from;        synchronized (first) {            synchronized (second) {                from.add(-amount);                to.add(amount);            }        }    }
    static Thread repeat(Account from, Account to, String name) {        Thread t = new Thread(() -> {            for (int i = 0; i < 10_000; i++) {                transfer(from, to, 1);            }        }, name);        t.setDaemon(true);   // only a safety net; with ordering it never gets stuck        t.start();        return t;    }
    public static void main(String[] args) throws InterruptedException {        Account asha = new Account(101, "Asha", 1000);        Account ravi = new Account(205, "Ravi", 500);
        Thread t1 = repeat(asha, ravi, "asha-to-ravi");        Thread t2 = repeat(ravi, asha, "ravi-to-asha");        t1.join(5000);        t2.join(5000);
        System.out.println("Both finished: " + (!t1.isAlive() && !t2.isAlive()));        System.out.println("Asha: Rs " + asha.balance() + ", Ravi: Rs " + ravi.balance());        System.out.println("Total: Rs " + (asha.balance() + ravi.balance()));    }}
Output
Both finished: true
Asha: Rs 1000, Ravi: Rs 500
Total: Rs 1500

What this code does

  • Both threads make 10,000 transfers in opposite directions, the exact pattern that deadlocked in the previous lesson. Now both lock account 101 first, so the program always finishes.
  • first and second depend only on the ids, never on the direction of the transfer. The balances end where they started, because each thread moved Rs 10,000 back and forth.

The other thread waits without holding anything, so no circular wait can form. The order must come from something stable and unique, such as an account number or a PNR. The direction of the transfer no longer matters: Asha → Ravi and Ravi → Asha both lock account 101 first.

A transfer to the same account is a special case, because both locks are the same object. Reject it with an exception, as the example does, or handle it separately.

No id to sort by? System.identityHashCode(obj) gives each object a number, but two objects can get the same number, so code that uses it needs an extra tie-breaker lock. A real id is simpler.

tryLock with a timeout and back off

tryLock(timeout, unit) on a ReentrantLock waits at most the given time and returns false if it could not get the lock. Use it for both locks, and if the second one fails, release the first before anything else.

Example 2 · tryLock gives up instead of waiting forever

TryLockGiveUpDemo.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;
class Wallet {    final String owner;    final ReentrantLock lock = new ReentrantLock();    int balance;
    Wallet(String owner, int balance) {        this.owner = owner;        this.balance = balance;    }}
public class TryLockGiveUpDemo {    // returns false instead of waiting forever when it cannot get both locks in time    static boolean tryTransfer(Wallet from, Wallet to, int amount, long timeoutMs)            throws InterruptedException {        if (!from.lock.tryLock(timeoutMs, TimeUnit.MILLISECONDS)) {            return false;        }        try {            if (!to.lock.tryLock(timeoutMs, TimeUnit.MILLISECONDS)) {                return false;                 // the finally below releases 'from'            }            try {                from.balance -= amount;                to.balance += amount;                return true;            } finally {                to.lock.unlock();            }        } finally {            from.lock.unlock();        }    }
    static void print(String label, boolean ok, Wallet a, Wallet b) {        System.out.println(label + (ok ? "done" : "busy, please try again")                + " | " + a.owner + ": " + a.balance + ", " + b.owner + ": " + b.balance);    }
    public static void main(String[] args) throws InterruptedException {        Wallet meena = new Wallet("Meena", 800);        Wallet store = new Wallet("Store", 0);
        print("Pay 1: ", tryTransfer(meena, store, 120, 100), meena, store);
        // a slow audit holds the store's lock for 300 ms        CountDownLatch auditHasLock = new CountDownLatch(1);        Thread audit = new Thread(() -> {            store.lock.lock();            try {                auditHasLock.countDown();                Thread.sleep(300);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            } finally {                store.lock.unlock();            }        }, "audit");        audit.start();        auditHasLock.await();
        print("Pay 2: ", tryTransfer(meena, store, 60, 100), meena, store);        audit.join();        print("Pay 2 retry: ", tryTransfer(meena, store, 60, 100), meena, store);    }}
Output
Pay 1: done | Meena: 680, Store: 120
Pay 2: busy, please try again | Meena: 680, Store: 120
Pay 2 retry: done | Meena: 620, Store: 180

What this code does

  • tryTransfer asks for each lock with a 100 ms limit. When the store wallet is busy, it returns false, and the outer finally releases Meena's lock: the thread never sits holding one lock while waiting for another.
  • Pay 2 fails while the audit holds the store's lock for 300 ms. No money moves, the user sees "busy, please try again", and the retry after the audit succeeds.

Example 3 · Back off with a random wait and retry

BackOffRetryDemo.javaJava
import java.util.concurrent.ThreadLocalRandom;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.locks.ReentrantLock;
class Wallet {    final ReentrantLock lock = new ReentrantLock();    int balance;
    Wallet(int balance) { this.balance = balance; }}
public class BackOffRetryDemo {    static final AtomicInteger retries = new AtomicInteger();
    // opposite lock orders are still used, but nobody waits forever    static void transfer(Wallet from, Wallet to, int amount) throws InterruptedException {        while (true) {            if (from.lock.tryLock()) {                try {                    if (to.lock.tryLock()) {                        try {                            from.balance -= amount;                            to.balance += amount;                            return;                        } finally {                            to.lock.unlock();                        }                    }                } finally {                    from.lock.unlock();      // never hold one lock while waiting                }            }            retries.incrementAndGet();            Thread.sleep(ThreadLocalRandom.current().nextInt(1, 4));   // back off 1-3 ms        }    }
    static Thread repeat(Wallet from, Wallet to, String name) {        Thread t = new Thread(() -> {            try {                for (int i = 0; i < 20_000; i++) {                    transfer(from, to, 1);                }            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, name);        t.start();        return t;    }
    public static void main(String[] args) throws InterruptedException {        Wallet a = new Wallet(50_000);        Wallet b = new Wallet(50_000);        Thread t1 = repeat(a, b, "a-to-b");        Thread t2 = repeat(b, a, "b-to-a");        t1.join();        t2.join();        System.out.println("Transfers done: 40000");        System.out.println("a: " + a.balance + ", b: " + b.balance);        System.out.println("Times a thread backed off and retried: " + retries.get());    }}
Sample output
Transfers done: 40000
a: 50000, b: 50000
Times a thread backed off and retried: 7

What this code does

  • The two threads still lock in opposite orders, but with tryLock() neither ever waits while holding a lock. If the second lock is busy, the thread releases the first, sleeps 1 to 3 ms at random and tries again.
  • The balances are always right. The number of retries changes on every run and is often small: after one thread backs off, the other usually finishes many transfers without meeting it.

A thread then never holds one lock while waiting forever for another, which breaks the hold-and-wait condition.

After a failure you have two choices. Report it ("busy, please try again"), as payment apps do when a bank does not answer in time. Or back off: release everything, sleep a short random time and try again. The random part matters; the "Livelock and starvation" lesson shows why.

Order of execution

Back off when the second lock is busy

The second account is locked by someone else. Put the steps in the order they happen.

One lock instead of two

The simplest fix is one lock for all the data that operations touch together. With a single lock there is nothing to take in the wrong order, so these operations cannot deadlock with each other.

Example 4 · One lock for the whole bank

OneLockBankDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
class Bank {    private final Object lock = new Object();          // one lock for every account    private final Map<String, Integer> balances = new LinkedHashMap<>();
    void open(String name, int amount) {        synchronized (lock) {            balances.put(name, amount);        }    }
    void transfer(String from, String to, int amount) {        synchronized (lock) {                          // only one lock: no cycle possible            balances.put(from, balances.get(from) - amount);            balances.put(to, balances.get(to) + amount);        }    }
    String report() {        synchronized (lock) {            int total = 0;            for (int b : balances.values()) total += b;            return balances + ", total = " + total;        }    }}
public class OneLockBankDemo {    static Thread repeat(Bank bank, String from, String to) {        Thread t = new Thread(() -> {            for (int i = 0; i < 10_000; i++) {                bank.transfer(from, to, 2);            }        }, from + "-to-" + to);        t.start();        return t;    }
    public static void main(String[] args) throws InterruptedException {        Bank bank = new Bank();        bank.open("Asha", 50_000);        bank.open("Ravi", 50_000);        bank.open("Zoya", 50_000);
        // a ring of transfers: with two locks per transfer this could deadlock        Thread t1 = repeat(bank, "Asha", "Ravi");        Thread t2 = repeat(bank, "Ravi", "Zoya");        Thread t3 = repeat(bank, "Zoya", "Asha");        t1.join();        t2.join();        t3.join();        System.out.println(bank.report());    }}
Output
{Asha=50000, Ravi=50000, Zoya=50000}, total = 150000

What this code does

  • Three threads move money in a ring: Asha → Ravi → Zoya → Asha. With one lock per account this ring could deadlock with three threads, like the roommates in the previous lesson.
  • Every method of Bank uses the same private lock, so only one transfer runs at a time. It is simple and safe, but transfers that touch different accounts can no longer run side by side.

The price is speed under load. A transfer between Asha and Ravi now waits for an unrelated transfer between Zoya and Kabir. For a hostel mess or a college fest app that is fine. For a bank with millions of accounts, one lock becomes the bottleneck, and ordering per account is the better choice.

Avoid calling unknown code while holding a lock

An alien method is code your class does not control: a listener, a callback, a lambda passed in by the caller, or a method a subclass can override.

Example 5 · Bug: a listener called while holding a lock

ListenerDeadlockDemo.javaJava
import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.concurrent.CountDownLatch;
interface BookingListener {    void onBooked(String seat, int seatsLeft);}
class Show {    private int seatsLeft = 100;    private BookingListener listener;
    void setListener(BookingListener listener) { this.listener = listener; }
    synchronized void book(String seat) {        seatsLeft--;        ListenerDeadlockDemo.pause();           // demo only: forces the bad timing        listener.onBooked(seat, seatsLeft);     // unknown code, called while holding Show's lock    }
    synchronized int seatsLeft() { return seatsLeft; }}
class SmsLog implements BookingListener {    private final Show show;    private final List<String> lines = new ArrayList<>();
    SmsLog(Show show) { this.show = show; }
    public synchronized void onBooked(String seat, int seatsLeft) {        lines.add("Booked " + seat + ", " + seatsLeft + " left");    }
    synchronized void dailySummary() {        ListenerDeadlockDemo.pause();        lines.add("Summary: " + show.seatsLeft() + " seats left");   // needs Show's lock    }
    synchronized List<String> lines() { return new ArrayList<>(lines); }}
public class ListenerDeadlockDemo {    static final CountDownLatch bothInside = new CountDownLatch(2);
    static void pause() {        bothInside.countDown();        try {            bothInside.await();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        Show show = new Show();        SmsLog log = new SmsLog(show);        show.setListener(log);
        Thread booking = new Thread(() -> show.book("A1"), "booking");        Thread summary = new Thread(log::dailySummary, "sms-summary");        booking.setDaemon(true);        summary.setDaemon(true);        booking.start();        summary.start();        booking.join(500);        summary.join(500);
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();        long[] ids = mx.findDeadlockedThreads();        if (ids == null) {            System.out.println("No deadlock");            return;        }        ThreadInfo[] infos = mx.getThreadInfo(ids);        Arrays.sort(infos, Comparator.comparing(ThreadInfo::getThreadName));        for (ThreadInfo info : infos) {            System.out.println(info.getThreadName() + " waits for the lock held by " + info.getLockOwnerName());        }    }}
Output
booking waits for the lock held by sms-summary
sms-summary waits for the lock held by booking

What this code does

  • book holds the Show lock and calls onBooked, which needs the SmsLog lock. At the same moment dailySummary holds the SmsLog lock and calls seatsLeft, which needs the Show lock. That is the opposite-order pattern, hidden inside two classes.
  • The author of Show never wrote a second synchronized block. The second lock came from the listener, which is exactly why calling unknown code under a lock is dangerous.

Example 6 · Fix: an open call after releasing the lock

OpenCallDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;
interface BookingListener {    void onBooked(String seat, int seatsLeft);}
class Show {    private int seatsLeft = 100;    private BookingListener listener;
    void setListener(BookingListener listener) { this.listener = listener; }
    void book(String seat) {        int left;        synchronized (this) {                   // lock only for our own state            seatsLeft--;            left = seatsLeft;        }        OpenCallDemo.pause();                   // same forced timing as before        listener.onBooked(seat, left);          // open call: no lock held    }
    synchronized int seatsLeft() { return seatsLeft; }}
class SmsLog implements BookingListener {    private final Show show;    private final List<String> lines = new ArrayList<>();
    SmsLog(Show show) { this.show = show; }
    public synchronized void onBooked(String seat, int seatsLeft) {        lines.add("Booked " + seat + ", " + seatsLeft + " left");    }
    synchronized void dailySummary() {        OpenCallDemo.pause();        lines.add("Summary: " + show.seatsLeft() + " seats left");    }
    synchronized List<String> lines() { return new ArrayList<>(lines); }}
public class OpenCallDemo {    static final CountDownLatch bothInside = new CountDownLatch(2);
    static void pause() {        bothInside.countDown();        try {            bothInside.await();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        Show show = new Show();        SmsLog log = new SmsLog(show);        show.setListener(log);
        Thread booking = new Thread(() -> show.book("A1"), "booking");        Thread summary = new Thread(log::dailySummary, "sms-summary");        booking.start();        summary.start();        booking.join();        summary.join();
        System.out.println("Both threads finished");        for (String line : log.lines()) {            System.out.println(line);        }    }}
Output
Both threads finished
Summary: 99 seats left
Booked A1, 99 left

What this code does

  • book now changes seatsLeft inside a short synchronized block, copies the value into left, and calls the listener after the block ends. The forced timing is the same as before, yet both threads finish.
  • The booking thread waits for the SmsLog lock while holding nothing, so the summary can finish first. That is why the summary line comes before the booking line.

If you call it while holding your lock, it may take other locks in an order you cannot see, and that can close a deadlock cycle.

The fix is an open call: update your own state under the lock, copy what the callback needs into local variables, release the lock, and only then call the unknown code. Example 5 shows the bug and Example 6 the fix, with the same forced timing in both.

Choosing a fix: ordering, tryLock or one lock

Ordering breaks circular wait, tryLock breaks hold and wait, and one lock leaves nothing to wait for in a circle. Pick by what your code needs:

  • Lock ordering: the default when two or more locks have a natural id, such as accounts or seats. No retries and no failures, but every developer must follow the same order.
  • tryLock with a timeout: when you cannot control the order (locks picked at run time, code from several teams), or when "try again" is better than waiting.
  • One lock: when operations are short and the data is small. Easiest to get right; slow under heavy load.
  • Open calls: always, whichever fix you choose. Never call listeners or callbacks while holding a lock.

Next step

Check your understanding

11 quick questions