Java Deadlocks

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 192 of 306

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:

  • officeA locks printer, officeB locks scanner, and both sleep for 100 ms.
  • officeA then tries to lock scanner, which officeB owns. officeB tries to lock printer, which officeA owns.
  • Both threads move to the BLOCKED state (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: synchronized waits forever. There is no timeout and no way to interrupt a thread that is waiting to enter a synchronized block.


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.

ConditionMeaningIn the example
Mutual exclusionOnly one thread can hold a lock at a timeOnly one thread can own printer
Hold and waitA thread holds one lock while waiting for anotherofficeA holds printer while waiting for scanner
No preemptionA lock cannot be taken away; the owner must release itJava never forces a thread to give up a monitor
Circular waitA cycle of threads, each waiting for the nextA 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 -l lists 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, or null when there is none. It detects cycles on both synchronized monitors and ReentrantLocks.
  • getThreadInfo(ids) returns a ThreadInfo for 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 locks printer first.
  • Whichever thread gets printer first will also get scanner, because the other thread is waiting on printer and 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 tryLock gives up, the thread releases its first lock in finally, 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() with unlock() in a finally block, and only unlock a lock you actually acquired.
TechniqueBreaks conditionProsCons
Lock orderingCircular waitSimple, no retriesEvery code path must follow the order
tryLock with timeoutHold and waitWorks even without a fixed orderNeeds retry logic; can waste work
One lock / no nestingHold and waitEasiest to reason aboutLess concurrency
Higher-level tools (ExecutorService, concurrent collections)Avoids manual locksFewer locks to manageNot 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:

  1. 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.
  2. 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.
  3. 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).
  4. Final read. main reads the balances only after join(), when all teller threads have finished, so it sees their final values.

To review how synchronized blocks and monitors work, revisit Java Synchronization.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Deadlocks and get answers drawn from it.

Signed-in readers only.