Java Deadlocks
A Java deadlock happens when two or more threads each hold a lock and wait for a lock that another thread holds. None of them can continue, so they wait forever. The program does not crash and prints no error; it simply stops making progress.
Deadlocks usually appear when code needs more than one lock at a time, for example to move money between two accounts. This lesson shows how a deadlock forms, how to detect one, and the techniques that prevent it.
What Is a Deadlock in Java?
Imagine two office workers. One picks up the printer and then wants the scanner. The other picks up the scanner and then wants the printer. Each waits for the other to put their device down, and neither ever does.
public class DeadlockDemo {
static final Object printer = new Object();
static final Object scanner = new Object();
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread officeA = new Thread(() -> {
synchronized (printer) { // lock 1: printer
System.out.println("officeA: locked printer, waiting for scanner...");
pause(100);
synchronized (scanner) { // lock 2: scanner
System.out.println("officeA: printed and scanned");
}
}
}, "officeA");
Thread officeB = new Thread(() -> {
synchronized (scanner) { // lock 1: scanner
System.out.println("officeB: locked scanner, waiting for printer...");
pause(100);
synchronized (printer) { // lock 2: printer
System.out.println("officeB: printed and scanned");
}
}
}, "officeB");
officeA.setDaemon(true); // daemon threads let the JVM exit even while they are stuck
officeB.setDaemon(true);
officeA.start();
officeB.start();
officeA.join(1000); // wait at most one second
officeB.join(1000);
System.out.println("officeA state: " + officeA.getState());
System.out.println("officeB state: " + officeB.getState());
if (officeA.isAlive() && officeB.isAlive()) {
System.out.println("main: both threads are stuck - deadlock!");
}
}
}
Output (the first two lines can swap):
officeA: locked printer, waiting for scanner...
officeB: locked scanner, waiting for printer...
officeA state: BLOCKED
officeB state: BLOCKED
main: both threads are stuck - deadlock!
How it works:
officeAlocksprinter,officeBlocksscanner, and both sleep for 100 ms.officeAthen tries to lockscanner, whichofficeBowns.officeBtries to lockprinter, whichofficeAowns.- Both threads move to the
BLOCKEDstate (see Java Thread States) and stay there forever. "printed and scanned" is never printed. - The threads are daemons and
join()has a timeout only so this demo can finish. In a real program the application would simply hang.
Note:
synchronizedwaits forever. There is no timeout and no way to interrupt a thread that is waiting to enter asynchronizedblock.
The Four Conditions for a Deadlock
A deadlock can only happen when all four of the following conditions are true at the same time. Removing any one of them prevents deadlock.
| Condition | Meaning | In the example |
|---|---|---|
| Mutual exclusion | Only one thread can hold a lock at a time | Only one thread can own printer |
| Hold and wait | A thread holds one lock while waiting for another | officeA holds printer while waiting for scanner |
| No preemption | A lock cannot be taken away; the owner must release it | Java never forces a thread to give up a monitor |
| Circular wait | A cycle of threads, each waiting for the next | A waits for B, B waits for A |
The practical prevention techniques below each break one condition: lock ordering breaks circular wait, tryLock with a timeout breaks hold and wait, and avoiding nested locks removes the need to hold two locks at all.
How to Detect a Deadlock in Java
Using jstack
jstack ships with the JDK. It prints the stack of every thread in a running JVM and reports any deadlock it finds. First find the process ID with jps, then run jstack.
jps -l
jstack 48213
Output (trimmed; addresses and the process ID differ on your machine):
48213 DeadlockDemo
Found one Java-level deadlock:
=============================
"officeA":
waiting to lock monitor 0x00007f2c8c003080 (object 0x0000000711a1f6b0, a java.lang.Object),
which is held by "officeB"
"officeB":
waiting to lock monitor 0x00007f2c8c0050c0 (object 0x0000000711a1f6a0, a java.lang.Object),
which is held by "officeA"
How it works:
jps -llists running Java processes with their main class.jstack <pid>dumps all threads. The "Found one Java-level deadlock" section names the threads and which lock each one is waiting for.- Naming your threads (like
"officeA") makes these dumps much easier to read.
Detecting a Deadlock in Code with ThreadMXBean
A program can also check itself for deadlocks using ThreadMXBean from java.lang.management. Monitoring tools and health checks use this approach.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
public class DetectDeadlock {
static final Object accountLockA = new Object();
static final Object accountLockB = new Object();
static Thread transfer(String name, Object first, Object second) {
Thread t = new Thread(() -> {
synchronized (first) {
try { Thread.sleep(100); } catch (InterruptedException e) { return; }
synchronized (second) {
System.out.println(name + " finished");
}
}
}, name);
t.setDaemon(true);
return t;
}
public static void main(String[] args) throws InterruptedException {
transfer("transfer-1", accountLockA, accountLockB).start();
transfer("transfer-2", accountLockB, accountLockA).start();
Thread.sleep(500); // give the deadlock time to form
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] deadlockedIds = threadBean.findDeadlockedThreads(); // null if none
if (deadlockedIds == null) {
System.out.println("No deadlock found");
return;
}
System.out.println("Deadlock detected between " + deadlockedIds.length + " threads:");
for (ThreadInfo info : threadBean.getThreadInfo(deadlockedIds)) {
System.out.println(info.getThreadName() + " is " + info.getThreadState()
+ ", waiting for a lock held by " + info.getLockOwnerName());
}
}
}
Output (line order can change):
Deadlock detected between 2 threads:
transfer-1 is BLOCKED, waiting for a lock held by transfer-2
transfer-2 is BLOCKED, waiting for a lock held by transfer-1
How it works:
findDeadlockedThreads()returns the IDs of threads stuck in a deadlock cycle, ornullwhen there is none. It detects cycles on bothsynchronizedmonitors andReentrantLocks.getThreadInfo(ids)returns aThreadInfofor each thread, including its state and the name of the thread that owns the lock it wants.- Detection only reports the problem. The JVM cannot undo a deadlock, so the real fix is prevention.
Prevent Deadlock with Lock Ordering
The most reliable fix is to make every thread acquire locks in the same global order. If everyone takes the printer before the scanner, a circular wait is impossible.
public class LockOrdering {
static final Object printer = new Object();
static final Object scanner = new Object();
// Every thread uses this method, so the lock order is always printer -> scanner
static void printAndScan(String office) {
synchronized (printer) {
pause(100);
synchronized (scanner) {
System.out.println(office + ": printed and scanned");
}
}
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread officeA = new Thread(() -> printAndScan("officeA"));
Thread officeB = new Thread(() -> printAndScan("officeB"));
officeA.start();
officeB.start();
officeA.join();
officeB.join();
System.out.println("main: no deadlock");
}
}
Output (which office goes first can change):
officeA: printed and scanned
officeB: printed and scanned
main: no deadlock
How it works:
- Both threads go through
printAndScan(), which always locksprinterfirst. - Whichever thread gets
printerfirst will also getscanner, because the other thread is waiting onprinterand does not hold anything. - When the locks are objects chosen at runtime (like two bank accounts), order them by a stable key such as an account ID. The real-world example at the end of this lesson does exactly that.
Prevent Deadlock with tryLock and a Timeout
ReentrantLock.tryLock(timeout, unit) waits for a lock only for a limited time and returns false if it cannot get it. A thread that fails can release what it holds, wait a little, and try again. This breaks the hold-and-wait condition.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo {
static final ReentrantLock printer = new ReentrantLock();
static final ReentrantLock scanner = new ReentrantLock();
static boolean useBoth(String office, ReentrantLock first, ReentrantLock second)
throws InterruptedException {
if (!first.tryLock(200, TimeUnit.MILLISECONDS)) {
return false;
}
try {
Thread.sleep(100); // hold the first device for a while
if (!second.tryLock(200, TimeUnit.MILLISECONDS)) {
System.out.println(office + ": could not get second device, backing off");
return false; // the finally block releases the first lock
}
try {
System.out.println(office + ": printed and scanned");
return true;
} finally {
second.unlock();
}
} finally {
first.unlock();
}
}
static void runOffice(String office, ReentrantLock first, ReentrantLock second, long backoffMs) {
try {
int attempts = 1;
while (!useBoth(office, first, second)) {
attempts++;
Thread.sleep(backoffMs); // different back-off times avoid retrying in lockstep
}
System.out.println(office + ": done after " + attempts + " attempt(s)");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread officeA = new Thread(() -> runOffice("officeA", printer, scanner, 50));
Thread officeB = new Thread(() -> runOffice("officeB", scanner, printer, 120));
officeA.start();
officeB.start();
officeA.join();
officeB.join();
System.out.println("main: both offices finished");
}
}
Output (the number of attempts can vary between runs):
officeA: could not get second device, backing off
officeB: could not get second device, backing off
officeA: could not get second device, backing off
officeB: printed and scanned
officeB: done after 2 attempt(s)
officeA: printed and scanned
officeA: done after 3 attempt(s)
main: both offices finished
How it works:
- The two offices still take the locks in opposite order, so they block each other at first.
- After 200 ms each
tryLockgives up, the thread releases its first lock infinally, and it sleeps before retrying. - The different back-off times (50 ms and 120 ms) stop the threads from colliding again and again, so both finish.
- Always pair a successful
tryLock()withunlock()in afinallyblock, and only unlock a lock you actually acquired.
| Technique | Breaks condition | Pros | Cons |
|---|---|---|---|
| Lock ordering | Circular wait | Simple, no retries | Every code path must follow the order |
tryLock with timeout | Hold and wait | Works even without a fixed order | Needs retry logic; can waste work |
| One lock / no nesting | Hold and wait | Easiest to reason about | Less concurrency |
Higher-level tools (ExecutorService, concurrent collections) | Avoids manual locks | Fewer locks to manage | Not every problem fits |
Note: Calling unknown code (a listener, a callback, an overridden method) while holding a lock is a hidden source of deadlocks, because that code may take other locks. Copy the data you need, release the lock, and then make the call.
Real-World Example: Deadlock-Free Bank Transfers
Transfers between accounts need two locks: the source and the destination. If one thread moves money from account 1 to 2 while another moves from 2 to 1, naive locking deadlocks. Ordering the locks by account ID fixes it.
import java.util.concurrent.ThreadLocalRandom;
public class SafeBank {
static class Account {
final int id;
private long balance;
Account(int id, long balance) {
this.id = id;
this.balance = balance;
}
}
static void transfer(Account from, Account to, long amount) {
// Always lock the account with the smaller ID first
Account firstLock = from.id < to.id ? from : to;
Account secondLock = from.id < to.id ? to : from;
synchronized (firstLock) {
synchronized (secondLock) {
if (from.balance >= amount) {
from.balance -= amount;
to.balance += amount;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Account[] accounts = {
new Account(1, 10_000), new Account(2, 10_000), new Account(3, 10_000)
};
Thread[] tellers = new Thread[6];
for (int t = 0; t < tellers.length; t++) {
tellers[t] = new Thread(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 10_000; i++) {
int fromIndex = random.nextInt(3);
int toIndex = (fromIndex + 1 + random.nextInt(2)) % 3; // never the same account
transfer(accounts[fromIndex], accounts[toIndex], random.nextInt(1, 101));
}
});
tellers[t].start();
}
for (Thread teller : tellers) teller.join();
long total = 0;
System.out.println("all transfers finished without deadlock");
for (Account account : accounts) {
System.out.println("account " + account.id + ": " + account.balance);
total += account.balance;
}
System.out.println("total money: " + total);
}
}
Output (individual balances change every run; the total never does):
all transfers finished without deadlock
account 1: 9874
account 2: 10342
account 3: 9784
total money: 30000
How it works:
- Random directions. Six teller threads make 60,000 transfers in both directions between three accounts, which is exactly the pattern that deadlocks with naive locking.
- Global lock order.
transfer()always locks the lower account ID first, so two threads can never hold each other's next lock. The program always finishes. - Correct balances. Both balances change while the thread holds both locks, so money is never created or lost. The total stays at 30,000, which proves there was also no race condition (see Java Race Conditions).
- Final read.
mainreads the balances only afterjoin(), when all teller threads have finished, so it sees their final values.
To review how synchronized blocks and monitors work, revisit Java Synchronization.