Sub topic 11
Deadlock and How Lock Ordering Prevents It
Locks keep shared data safe, but they can also cause a new problem. If two threads each hold one lock and wait for the other's lock, neither one can move. This chapter shows how that happens, how to spot it, and how one simple rule, lock ordering, prevents it.
What Deadlock Is
A deadlock is a situation where two or more threads wait for each other forever. Each thread holds something the other one needs. None of them will let go, so none of them can finish.
Think of two people at a narrow door. Each one says, "You first," and each one waits for the other. Nobody walks through. A deadlocked program behaves the same way. It does not crash and it prints no error. It simply stops making progress.
In Java, deadlock usually involves intrinsic locks, which are the locks you take with synchronized. Remember that a thread entering a synchronized block must wait until no other thread holds that lock.
Watching a Deadlock Happen
The program below creates two lock objects and two threads. The first thread takes LOCK_A and then tries to take LOCK_B. The second thread takes them in the opposite order.
public class DeadlockDemo {
private static final Object LOCK_A = new Object();
private static final Object LOCK_B = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (LOCK_A) {
System.out.println("t1 holds A, wants B");
pause();
synchronized (LOCK_B) {
System.out.println("t1 has both locks");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (LOCK_B) {
System.out.println("t2 holds B, wants A");
pause();
synchronized (LOCK_A) {
System.out.println("t2 has both locks");
}
}
});
t1.start();
t2.start();
}
private static void pause() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}Run it and you will almost always see only two lines:
t1 holds A, wants B
t2 holds B, wants AAfter that the program hangs. You have to stop it by hand, for example with Ctrl+C.
The short pause() is there to make the bad timing happen every time. Without it, the deadlock would still be possible, just rarer. Rare deadlocks are worse, because they pass your tests and then appear in production.
The Circular Wait
The diagram below shows what each thread holds and what it wants.
Follow the arrows: t1 waits for B, B belongs to t2, t2 waits for A, and A belongs to t1. The waiting goes around in a circle. A circular wait is a chain of threads where each one waits for a lock held by the next, and the last one waits for the first.
The Four Conditions for Deadlock
A deadlock can only happen when all four of these conditions are true at the same time:
| Condition | Meaning | True for `synchronized`? |
|---|---|---|
| Mutual exclusion | Only one thread can hold a lock at a time | Yes, always |
| Hold and wait | A thread keeps one lock while waiting for another | Yes, with nested blocks |
| No preemption | Nobody can take a lock away from a thread | Yes, always |
| Circular wait | Threads wait for each other in a loop | Only if lock order differs |
You cannot change the first three for synchronized. They are part of how intrinsic locks work. The fourth condition is the one you control. If you break the circle, deadlock becomes impossible.
The Fix: A Consistent Lock Order
Lock ordering is a rule that every thread must take locks in the same fixed order. If every thread always takes LOCK_A before LOCK_B, no thread can hold B while waiting for A. The circle cannot close.
public class OrderedLocking {
private static final Object LOCK_A = new Object();
private static final Object LOCK_B = new Object();
static void doWork() {
synchronized (LOCK_A) {
synchronized (LOCK_B) {
// every thread acquires LOCK_A before LOCK_B,
// so no thread can hold LOCK_B while waiting for LOCK_A
}
}
}
}Now suppose two threads call doWork() at once. One gets LOCK_A first. The other thread waits for LOCK_A while holding nothing. The first thread then takes LOCK_B, finishes, and releases both. The waiting thread goes next. Threads still wait for each other here, but the wait always ends.
A Harder Case: Ordering Locks You Choose at Run Time
Fixed lock names are easy to order. Things get harder when the locks depend on the arguments. A bank transfer is the classic example:
// DANGEROUS: lock order depends on argument order
synchronized (from.lock) {
synchronized (to.lock) {
// move money
}
}If one thread calls transfer(alice, bob, 10) and another calls transfer(bob, alice, 5), they lock in opposite orders. That is the same deadlock as before.
The fix is to choose the order from something stable about the objects, such as a unique ID. The class below always locks the account with the smaller ID first. Each account uses a private lock object, as recommended in the chapter on synchronized blocks.
public class Account {
private final int id;
private final Object lock = new Object();
private int balance;
public Account(int id, int balance) {
this.id = id;
this.balance = balance;
}
public 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.lock) {
synchronized (second.lock) {
from.balance -= amount;
to.balance += amount;
}
}
}
public int balance() {
synchronized (lock) {
return balance;
}
}
public static void main(String[] args) throws InterruptedException {
Account alice = new Account(1, 1000);
Account bob = new Account(2, 1000);
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10_000; i++) transfer(alice, bob, 1);
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10_000; i++) transfer(bob, alice, 1);
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(alice.balance() + " " + bob.balance());
}
}This program finishes and prints 1000 1000. Both threads lock account 1 before account 2, whatever order the arguments come in.
Edge cases to watch
- IDs must be unique. If two accounts shared an ID, the order between them would be undefined. Avoid ordering by
hashCode(), because two different objects can have the same hash code. - Transferring to the same account. If
fromandtoare the same object,firstandsecondare the same lock. The thread takes the lock twice. That works because intrinsic locks are reentrant, which means a thread can take a lock it already holds without blocking. - Every code path must follow the rule. One method that locks in the wrong order is enough to bring back the deadlock.
Other Ways to Lower the Risk
- Hold fewer locks. Code that never holds two locks at once cannot have this kind of deadlock.
- Keep critical sections short. Do slow work, like I/O, outside the lock.
- Do not call unknown code while holding a lock. A callback or listener may take its own locks in an order you cannot see.
- Use a timeout. The
ReentrantLockclass, covered in a later chapter, hastryLockwith a time limit, so a thread can give up instead of waiting forever.
Finding a Deadlock in a Running Program
When a Java program hangs, you can ask the JVM what its threads are doing. Find the process ID with jps, then run:
jstack <pid>At the end of its output, jstack reports Found one Java-level deadlock: and lists each thread, the lock it holds, and the lock it is waiting for. That list shows you the circle directly.
Exercises
Exercise
In DeadlockDemo, which of the four deadlock conditions does lock ordering remove, and why can't you remove the others when using synchronized?
Show answer
Lock ordering removes circular wait. Mutual exclusion, hold and wait (with nested blocks), and no preemption are built into how synchronized works: only one thread holds the lock, a thread keeps its outer lock while it waits for the inner one, and nothing can force a thread to release a lock.
Exercise
Change thread t2 in DeadlockDemo so the program never deadlocks. What exactly do you change?
Show answer
Make t2 take the locks in the same order as t1: synchronized (LOCKA) on the outside and synchronized (LOCKB) on the inside. Both threads now take A before B, so no circular wait can form and the program prints all four lines and exits.
Exercise
A teammate orders the two account locks with System.identityHashCode(account) instead of a unique ID. What can go wrong?
Show answer
Two different objects can have the same identity hash code. When they do, the code has no defined order between them, so two threads could lock them in opposite orders and deadlock. A unique ID gives every pair of accounts one fixed order.
Exercise
Why does Account.transfer(alice, alice, 5) not deadlock, even though the thread locks the same lock twice?
Show answer
Intrinsic locks are reentrant. The thread already holds alice.lock when it reaches the inner synchronized block, so it enters without waiting. The lock is fully released only when both blocks have exited.