Deadlock: Cause and Prevention
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Write code that causes a deadlock, then fix it." is a favourite whiteboard task. The interviewer is checking that you can name the cause (locks taken in opposite order), the four conditions, a prevention rule, and how you would find it in a hung service.
Writing a two-lock deadlock on demand
Deadlock is when two or more threads each hold a lock and wait forever for a lock another one holds, so none of them can continue.
A deadlock needs two locks taken in opposite order. This program forces it every time with a latch, then finds the stuck threads with ThreadMXBean.
Example 1 · A guaranteed deadlock, detected with ThreadMXBean
import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.Arrays;import java.util.concurrent.CountDownLatch;
public class DeadlockDemo { static final Object walletLock = new Object(); static final Object bankLock = new Object(); static final CountDownLatch bothHoldFirstLock = new CountDownLatch(2);
static void lockBoth(Object first, Object second) { synchronized (first) { bothHoldFirstLock.countDown(); try { bothHoldFirstLock.await(); // make sure the other thread holds its first lock } catch (InterruptedException e) { return; } synchronized (second) { // never gets here System.out.println("got both locks"); } } }
public static void main(String[] args) throws InterruptedException { Thread upi = new Thread(() -> lockBoth(walletLock, bankLock), "upi-thread"); Thread refund = new Thread(() -> lockBoth(bankLock, walletLock), "refund-thread"); upi.setDaemon(true); // so the demo can exit refund.setDaemon(true); upi.start(); refund.start();
ThreadMXBean mx = ManagementFactory.getThreadMXBean(); long[] ids; while ((ids = mx.findDeadlockedThreads()) == null) { Thread.sleep(10); } ThreadInfo[] infos = mx.getThreadInfo(ids); String[] names = Arrays.stream(infos).map(ThreadInfo::getThreadName).sorted().toArray(String[]::new); System.out.println("Deadlocked threads: " + Arrays.toString(names)); System.out.println("upi-thread state: " + upi.getState()); System.out.println("refund-thread state: " + refund.getState()); }}Deadlocked threads: [refund-thread, upi-thread] upi-thread state: BLOCKED refund-thread state: BLOCKED
What this code does
- Each thread takes its first lock, then the latch makes sure both are holding one before either asks for the second: the opposite lock order guarantees a cycle, and "got both locks" never prints.
findDeadlockedThreads()finds the cycle, and both threads are BLOCKED. They are daemon threads only so this demo can end; a real deadlocked app simply hangs.
Model answer, spoken: "Deadlock happens when threads wait for each other's locks in a cycle. For example, a payment locks wallet then bank, while a refund locks bank then wallet. I prevent it by always taking locks in the same global order."
How to spot one:
- The app hangs, threads are BLOCKED or WAITING, CPU use is near zero and no exception is thrown.
- A
synchronizeddeadlock cannot be broken from outside; the JVM must be restarted. - It is timing-dependent, so a demo uses a latch or
sleepto make the bad timing certain.
Find the bug
Spot the deadlock risk
Click the line that makes a deadlock possible.
Both methods run at the same time on two threads. Which line is the risk?
Round 1 of 2The four necessary conditions
Coffman conditions are the four conditions that must all hold for a deadlock: mutual exclusion, hold and wait, no preemption and circular wait. Break any one and deadlock cannot happen.
Interviewers ask for the four conditions by name, and then ask which one your fix breaks. Learn each in one line, with a Java example.
upi-thread holds walletLock -> waits for bankLockrefund-thread holds bankLock -> waits for walletLock (a cycle: circular wait)Prevention: lock ordering and tryLock with a timeout
Lock ordering is the rule that every thread takes locks in the same agreed order, such as lowest account id first. It breaks circular wait, so a deadlock cannot form.
Two prevention fixes follow. First, always lock the lower account id first. Second, tryLock with a timeout gives up and backs off instead of waiting forever.
Example 2 · Fix: always lock the lower account id first
class Account { final int id; int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }}
public class LockOrderingDemo { static void transfer(Account from, Account to, int amount) { Account first = from.id < to.id ? from : to; // always lock the smaller id first Account second = from.id < to.id ? to : from; synchronized (first) { synchronized (second) { if (from.balance >= amount) { from.balance -= amount; to.balance += amount; } } } }
public static void main(String[] args) throws InterruptedException { Account asha = new Account(1, 10_000); Account ravi = new Account(2, 10_000);
Thread t1 = new Thread(() -> { for (int i = 0; i < 50_000; i++) transfer(asha, ravi, 1); }); Thread t2 = new Thread(() -> { for (int i = 0; i < 50_000; i++) transfer(ravi, asha, 1); }); t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("Finished without deadlock"); System.out.println("Total money: " + (asha.balance + ravi.balance)); }}Finished without deadlock Total money: 20000
What this code does
- Transfers run in both directions 50000 times each, but
transferalways locks the account with the smaller id first, so no circular wait is possible and the program always finishes. - Money is only moved, never lost: the total stays 20000 because both balances change inside the same pair of locks.
Example 3 · tryLock with a timeout: back off instead of waiting forever
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo { public static void main(String[] args) throws InterruptedException { ReentrantLock seatLock = new ReentrantLock(); CountDownLatch held = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1);
Thread holder = new Thread(() -> { seatLock.lock(); try { held.countDown(); release.await(); // keep the lock until main says so } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { seatLock.unlock(); } }); holder.start(); held.await();
if (seatLock.tryLock(100, TimeUnit.MILLISECONDS)) { seatLock.unlock(); System.out.println("attempt 1: got the lock"); } else { System.out.println("attempt 1: lock busy for 100 ms, backing off"); }
release.countDown(); holder.join();
if (seatLock.tryLock(100, TimeUnit.MILLISECONDS)) { try { System.out.println("attempt 2: got the lock, booking seat"); } finally { seatLock.unlock(); } } }}attempt 1: lock busy for 100 ms, backing off attempt 2: got the lock, booking seat
What this code does
- While another thread holds
seatLock,tryLock(100, MILLISECONDS)waits at most 100 ms and returnsfalse, so the caller can release its own locks and retry instead of deadlocking. - After the holder releases the lock, the second attempt succeeds. Every successful
lock/tryLockis paired withunlock()in afinallyblock.
A transfer from account 5 to 2 and one from 2 to 5 both lock account 2 first, so no cycle can form. This is the standard interview fix. tryLock(timeout) on a ReentrantLock breaks hold-and-wait: if the second lock is not free in time, release what you hold, back off and retry.
Other options are one coarse lock for the whole operation, keeping locked sections small, and never calling unknown code (callbacks, listeners) while holding a lock.
Predict the output
Predict the lock result
Read the code, then pick what it prints.
Round 1 of 2
A thread asks for a lock it already holds.
Detecting a deadlock with a thread dump (jstack)
Thread dump is a snapshot that lists every thread of a running JVM with its state and stack trace. For deadlocks it names the threads and locks in the cycle.
A hung program can be diagnosed from outside. These two commands print a thread dump, and its deadlock section names the threads and locks.
Example 4 · Taking a thread dump with jps and jstack
jps -ljstack 1824418244 DeadlockDemo ... Found one Java-level deadlock: ============================= "upi-thread": waiting to lock monitor 0x000001d2... (object 0x0000000711a0..., a java.lang.Object), which is held by "refund-thread" "refund-thread": waiting to lock monitor 0x000001d3... (object 0x0000000711a1..., a java.lang.Object), which is held by "upi-thread" ... Found 1 deadlock.
What this code does
jps -llists running Java processes with their ids;jstack <pid>prints every thread's stack. Your process id and addresses will differ; the parts shown are trimmed.- The deadlock report names each thread, the lock it waits for and who holds it, which is exactly the cycle to fix with lock ordering.
Get a dump with jstack <pid> (find the id with jps -l), with jcmd <pid> Thread.print, or from VisualVM. For synchronized and java.util.concurrent locks the dump ends with Found one Java-level deadlock:. In code, ManagementFactory.getThreadMXBean().findDeadlockedThreads() returns the ids of deadlocked threads, or null.
One-line answer: "I take a thread dump with jstack; it reports the deadlock and which thread holds which lock."
Order of execution
Order the diagnosis
Put the steps for diagnosing a hung service in order.
Livelock and starvation
Livelock is when threads keep running and reacting to each other but make no progress. Unlike a deadlock they are not blocked, so CPU use stays high.
In a livelock everyone is busy and nothing finishes. This small simulation shows two people stepping aside again and again, then a simple rule that breaks the symmetry.
Example 5 · Livelock in a corridor, and breaking the symmetry
public class LivelockSimulation { public static void main(String[] args) { // Two students meet in a hostel corridor. Each politely steps to the other side. String asha = "left"; String ravi = "left"; for (int round = 1; round <= 4; round++) { if (asha.equals(ravi)) { asha = asha.equals("left") ? "right" : "left"; ravi = ravi.equals("left") ? "right" : "left"; System.out.println("round " + round + ": both move to " + asha + ", still blocked"); } } System.out.println("Busy every round, no progress: that is livelock");
// Fix: break the symmetry with a rule (here: only Ravi steps aside) asha = "left"; ravi = "left"; if (asha.equals(ravi)) { ravi = "right"; } System.out.println("With a rule: Asha " + asha + ", Ravi " + ravi + ", both pass"); }}round 1: both move to right, still blocked round 2: both move to left, still blocked round 3: both move to right, still blocked round 4: both move to left, still blocked Busy every round, no progress: that is livelock With a rule: Asha left, Ravi right, both pass
What this code does
- This single-threaded simulation shows the pattern: both students react the same way every round, so they are always busy and never pass. That is livelock: no thread is blocked, yet nothing progresses.
- A simple rule (only one of them steps aside, or a random wait) breaks the symmetry, the same way random back-off fixes livelocking retry loops.
Retry loops that back off by the same fixed amount can livelock; a random delay or a priority rule fixes it. Starvation is different: a thread can run in principle but never gets the resource, for example with an unfair lock under heavy load. A fair lock, new ReentrantLock(true), hands the lock to the longest-waiting thread, at some cost in throughput.
Next step
Check your understanding
12 quick questions