Sub topic 11
Deadlock and How Lock Ordering Prevents It
Locks keep shared data safe. They also bring a new risk. When threads wait on each other's locks, they can get stuck forever.
What Is Deadlock?
A deadlock is a situation where two or more threads each hold a lock and wait for a lock that another of them holds. None of them can move forward, so the program freezes. It does not crash and it prints no error. It just stops.
Here is a real-world example. Two people share one pen and one notebook. Ana grabs the pen and waits for the notebook. Ben grabs the notebook and waits for the pen. Neither one lets go, so neither one can write.
A Deadlock in Code
In this program, thread 1 takes LOCK_A and then wants LOCK_B. Thread 2 takes them in the opposite order. The short sleep gives each thread time to grab its first lock, so the deadlock happens almost every time you run it.
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) {
pause();
synchronized (LOCK_B) {
System.out.println("t1 got both locks");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (LOCK_B) {
pause();
synchronized (LOCK_A) {
System.out.println("t2 got both locks");
}
}
});
t1.start();
t2.start();
}
private static void pause() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}When you run it, nothing prints and the program never ends. Press Ctrl+C to stop it.
Why It Happens
Deadlock needs a circular wait, which is a loop of threads where each one waits for the next. In the diagram, the arrows go around in a circle. If you break the circle, the deadlock cannot happen.
The Fix: Always Lock in the Same Order
Lock ordering is a rule that every thread must take locks in one fixed order. Suppose every thread takes LOCK_A before LOCK_B. Then no thread can hold LOCK_B while it waits for LOCK_A, and the circle can never form.
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
System.out.println(Thread.currentThread().getName() + " got both locks");
}
}
}
public static void main(String[] args) {
new Thread(OrderedLocking::doWork).start();
new Thread(OrderedLocking::doWork).start();
}
}Both threads finish. One of them may wait for a moment, but it will always get the locks in the end.
Other Good Habits
- Hold locks for as short a time as you can.
- Avoid calling unknown code, such as callbacks, while you hold a lock.
- Use one lock instead of two when one lock is enough.
Exercise
Thread X locks orders and then stock. Thread Y locks stock and then orders. Can they deadlock, and how would you fix it?
Show answer
Yes. Each thread can hold one lock while it waits for the other, which forms a circular wait. To fix it, pick one order, such as orders first and stock second, and make both threads follow it.
Exercise
Why does DeadlockDemo print nothing and never exit?
Show answer
Thread 1 holds LOCKA and waits for LOCKB, while thread 2 holds LOCKB and waits for LOCKA. Neither thread can continue, so neither println runs and the threads never finish.