Skip to lesson

When a Java program hangs, a thread dump shows what every thread is doing at that moment: where it is in the code, what state it is in, and which locks it holds or wants. Reading one turns "the app is stuck" into "these two threads are waiting for each other at line 26".

Taking a dump with jstack or jcmd Thread.print

A thread dump is a snapshot of every thread in a running JVM: its name, its state and its stack trace. It shows where each thread is stuck or busy at that moment.

A thread dump is a snapshot of every thread in a running JVM: its name, state, stack trace and locks. It is the first thing to take when a Java program hangs or is unusually slow.

Terminal
jps -l                        # list Java processes and their PIDsjcmd 7704 Thread.print        # thread dump of process 7704jstack 7704                   # older tool, the same kind of dumpjstack 7704 > dump1.txt       # save it to read later or share

Find the process id (PID) with jps -l, which lists the running Java programs. Then run jcmd <pid> Thread.print, or the older jstack <pid>. Both come with the JDK, print the same kind of dump and do not stop the program. Take two or three dumps a few seconds apart: a thread found at the same line every time is really stuck.

Example 1 · A program that stays stuck long enough to inspect

HungTransferDemo.javaJava
import java.util.concurrent.CountDownLatch;
class Account {    final String owner;    int balance;
    Account(String owner, int balance) {        this.owner = owner;        this.balance = balance;    }}
public class HungTransferDemo {    static final CountDownLatch bothHoldOne = new CountDownLatch(2);   // forces the deadlock
    static void transfer(Account from, Account to, int amount) {        synchronized (from) {            bothHoldOne.countDown();            try {                bothHoldOne.await();            } catch (InterruptedException e) {                Thread.currentThread().interrupt();                return;            }            synchronized (to) {                from.balance -= amount;                to.balance += amount;            }        }    }
    public static void main(String[] args) throws InterruptedException {        Account asha = new Account("Asha", 1000);        Account ravi = new Account("Ravi", 500);
        Thread t1 = new Thread(() -> transfer(asha, ravi, 100), "transfer-asha-to-ravi");        Thread t2 = new Thread(() -> transfer(ravi, asha, 50), "transfer-ravi-to-asha");        t1.setDaemon(true);        t2.setDaemon(true);        t1.start();        t2.start();
        System.out.println("PID: " + ProcessHandle.current().pid());        System.out.println("Stuck on purpose. Take a thread dump in another terminal now.");        System.out.println("This program exits by itself after 30 seconds.");        t1.join(30_000);        System.out.println("Done waiting, exiting.");    }}
Sample output
PID: 7704
Stuck on purpose. Take a thread dump in another terminal now.
This program exits by itself after 30 seconds.
Done waiting, exiting.

What this code does

  • The program deadlocks on purpose and stays stuck for 30 seconds, long enough to take a dump from a second terminal. It prints its own PID with ProcessHandle.current().pid(); your PID will be different.
  • Both stuck threads are daemon threads, so the program still exits once main stops waiting.

Example 2 · jps and jcmd on the stuck program

Terminal
jps -ljcmd 7704 Thread.print
Sample output
$ jps -l
30600 jdk.jcmd/sun.tools.jps.Jps
7704 HungTransferDemo

$ jcmd 7704 Thread.print
7704:
2026-10-15 23:46:30
Full thread dump OpenJDK 64-Bit Server VM (21.0.7+9-b895.130 mixed mode, sharing):
...
"main" #1 [30564] prio=5 os_prio=0 cpu=93.75ms elapsed=8.85s tid=0x000002e839d3f930 nid=30564 in Object.wait()  [0x000000ebe89ff000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
        at java.lang.Object.wait0(java.base@21.0.7/Native Method)
        - waiting on <0x0000000091a92e90> (a java.lang.Thread)
        at java.lang.Object.wait(java.base@21.0.7/Object.java:366)
        at java.lang.Thread.join(java.base@21.0.7/Thread.java:2073)
        - locked <0x0000000091a92e90> (a java.lang.Thread)
        at HungTransferDemo.main(HungTransferDemo.java:46)

...
"transfer-asha-to-ravi" #21 [25844] daemon prio=5 os_prio=0 cpu=0.00ms elapsed=8.76s tid=0x000002e85269aae0 nid=25844 waiting for monitor entry  [0x000000ebe9bff000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at HungTransferDemo.transfer(HungTransferDemo.java:26)
        - waiting to lock <0x0000000091a92da8> (a Account)
        - locked <0x0000000091a92d60> (a Account)
        at HungTransferDemo.lambda$main$0(HungTransferDemo.java:36)
        at HungTransferDemo$$Lambda/0x000002e854000c38.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)

"transfer-ravi-to-asha" #22 [228] daemon prio=5 os_prio=0 cpu=0.00ms elapsed=8.76s tid=0x000002e85269b550 nid=228 waiting for monitor entry  [0x000000ebe9cff000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at HungTransferDemo.transfer(HungTransferDemo.java:26)
        - waiting to lock <0x0000000091a92d60> (a Account)
        - locked <0x0000000091a92da8> (a Account)
        at HungTransferDemo.lambda$main$1(HungTransferDemo.java:37)
        at HungTransferDemo$$Lambda/0x000002e854001000.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)

...

What this code does

  • jps -l shows each PID next to the main class name. jcmd 7704 Thread.print prints the dump; the JVM's own threads (garbage collector, compiler and others) are left out here and shown as ....
  • Both transfer threads are BLOCKED (on object monitor). Each has - locked one Account and is waiting to lock the other. main is TIMED_WAITING inside join, which is expected.
  • Addresses such as <0x0000000091a92da8>, ids and timings change on every run; the structure stays the same.
Without a second terminal, press Ctrl+Break in the Windows console that runs the program, or run kill -3 <pid> on macOS. The dump then appears in the program's own console.

Thread states and stack traces in the dump

Each thread in a dump is one block. Its first line has the thread's name in quotes, a number, daemon for daemon threads, and some ids.

Example 3 · Five threads, five states

ThreadStatesDemo.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.locks.ReentrantLock;
public class ThreadStatesDemo {    static final Object monitor = new Object();    static final ReentrantLock lock = new ReentrantLock();    static final CountDownLatch latch = new CountDownLatch(1);    static volatile boolean spinning = true;
    static void sleepLong() {        try { Thread.sleep(5_000); } catch (InterruptedException e) { /* exit */ }    }
    static void waitForLatch() {        try { latch.await(); } catch (InterruptedException e) { /* exit */ }    }
    static void waitForLock() {        lock.lock();        lock.unlock();    }
    static void waitForMonitor() {        synchronized (monitor) { }    }
    static void spin() {        while (spinning) { }                    // busy loop: uses CPU    }
    // the first frame of our own class in the thread's stack trace    static String whereIs(Thread t) {        for (StackTraceElement e : t.getStackTrace()) {            if (e.getClassName().equals("ThreadStatesDemo")) return e.getMethodName() + "()";        }        return "?";    }
    static Thread start(String name, Runnable task, Thread.State expected) throws InterruptedException {        Thread t = new Thread(task, name);        t.setDaemon(true);        t.start();        for (int i = 0; i < 200 && t.getState() != expected; i++) {            Thread.sleep(10);        }        return t;    }
    public static void main(String[] args) throws InterruptedException {        lock.lock();                            // main holds both locks        synchronized (monitor) {            Thread[] threads = {                start("spinner", ThreadStatesDemo::spin, Thread.State.RUNNABLE),                start("monitor-waiter", ThreadStatesDemo::waitForMonitor, Thread.State.BLOCKED),                start("lock-waiter", ThreadStatesDemo::waitForLock, Thread.State.WAITING),                start("latch-waiter", ThreadStatesDemo::waitForLatch, Thread.State.WAITING),                start("sleeper", ThreadStatesDemo::sleepLong, Thread.State.TIMED_WAITING)            };            for (Thread t : threads) {                System.out.printf("%-15s %-14s in %s%n", t.getName(), t.getState(), whereIs(t));            }        }        spinning = false;        latch.countDown();        lock.unlock();    }}
Output
spinner         RUNNABLE       in spin()
monitor-waiter  BLOCKED        in waitForMonitor()
lock-waiter     WAITING        in waitForLock()
latch-waiter    WAITING        in waitForLatch()
sleeper         TIMED_WAITING  in sleepLong()

What this code does

  • A thread in a busy loop is RUNNABLE; one waiting to enter synchronized is BLOCKED; one in lock() or await() is WAITING; one in sleep is TIMED_WAITING. A dump shows the same states.
  • getStackTrace() returns the stack a dump would print. whereIs reads it from the top until it reaches a method of our own class, which is exactly how you read a real dump.

The next line is the state: the same Thread.State values that getState() returns, with a hint in brackets such as (on object monitor) or (parking).

Below that comes the stack trace. The top line is where the thread is right now; each line below it is the method that called the line above. Read from the top until you reach your own code: that is where your thread is stuck or busy. The lines starting with - describe locks:

  • - locked <0x...> (a Account): the thread holds this lock.
  • - waiting to lock <0x...>: it is BLOCKED, waiting to enter a synchronized block.
  • - waiting on <0x...>: it called wait(), or join(), which uses wait() inside.
  • - parking to wait for <0x...>: it waits for a ReentrantLock, latch, queue or other java.util.concurrent tool.

Predict the output

Which thread state is it?

Read each program and pick its output.

Round 1 of 3

The state of one thread before start() and after join().

public class StateDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> { });
System.out.print(worker.getState() + " ");
worker.start();
worker.join();
System.out.println(worker.getState());
}
}

"Found one Java-level deadlock"

When threads are deadlocked on synchronized locks or ReentrantLocks, the JVM finds the cycle for you. It adds a report at the end of the dump, after all the thread blocks, starting with Found one Java-level deadlock:.

Example 4 · The deadlock report at the end of jstack

Terminal
jstack 7704
Sample output
...
Found one Java-level deadlock:
=============================
"transfer-asha-to-ravi":
  waiting to lock monitor 0x000002e8526ae690 (object 0x0000000091a92da8, a Account),
  which is held by "transfer-ravi-to-asha"

"transfer-ravi-to-asha":
  waiting to lock monitor 0x000002e8526ad5a0 (object 0x0000000091a92d60, a Account),
  which is held by "transfer-asha-to-ravi"

Java stack information for the threads listed above:
===================================================
"transfer-asha-to-ravi":
        at HungTransferDemo.transfer(HungTransferDemo.java:26)
        - waiting to lock <0x0000000091a92da8> (a Account)
        - locked <0x0000000091a92d60> (a Account)
        at HungTransferDemo.lambda$main$0(HungTransferDemo.java:36)
        at HungTransferDemo$$Lambda/0x000002e854000c38.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)
"transfer-ravi-to-asha":
        at HungTransferDemo.transfer(HungTransferDemo.java:26)
        - waiting to lock <0x0000000091a92d60> (a Account)
        - locked <0x0000000091a92da8> (a Account)
        at HungTransferDemo.lambda$main$1(HungTransferDemo.java:37)
        at HungTransferDemo$$Lambda/0x000002e854001000.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)

Found 1 deadlock.

What this code does

  • The report names both threads and both Account locks: transfer-asha-to-ravi waits for a lock held by transfer-ravi-to-asha, and the other way round.
  • The stack traces point at HungTransferDemo.transfer, line 26, at the inner synchronized (to) block, called from lines 36 and 37: the two transfers with opposite argument orders. That is enough to find and fix the bug.

For each thread in the cycle, the report says which lock it is waiting for and which thread holds that lock. Follow the names around the circle: A waits for B, B waits for A. Below that, the stack traces show the exact lines, so you can see which code paths take the locks in opposite orders.

The report covers lock cycles only. A thread waiting forever on a CountDownLatch or an empty queue is not a deadlock to the JVM, so spot it yourself from the stack traces.

Naming threads to make dumps readable

A dump full of Thread-7 and pool-3-thread-2 tells you little. Give every thread a name that says what it does: new Thread(task, "result-mailer"), or a ThreadFactory for a pool so that its threads become tatkal-booking-1, tatkal-booking-2 and so on.

Example 5 · Default pool names versus a ThreadFactory

ThreadNamesDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class ThreadNamesDemo {    // gives every thread of a pool a name that says what it does    static ThreadFactory named(String prefix) {        AtomicInteger next = new AtomicInteger(1);        return task -> new Thread(task, prefix + "-" + next.getAndIncrement());    }
    static List<String> liveThreads(String... prefixes) {        List<String> lines = new ArrayList<>();        for (Thread t : Thread.getAllStackTraces().keySet()) {            for (String p : prefixes) {                if (t.getName().startsWith(p)) lines.add(t.getName() + " " + t.getState());            }        }        Collections.sort(lines);        return lines;    }
    static void waitUntilIdle(String... prefixes) throws InterruptedException {        for (int i = 0; i < 200; i++) {            boolean allWaiting = true;            for (String line : liveThreads(prefixes)) {                if (!line.endsWith("WAITING")) allWaiting = false;            }            if (allWaiting) return;            Thread.sleep(10);        }    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService plain = Executors.newFixedThreadPool(2);        ExecutorService tickets = Executors.newFixedThreadPool(2, named("tatkal-booking"));        for (int i = 0; i < 2; i++) {            plain.submit(() -> { });            tickets.submit(() -> { });        }        waitUntilIdle("pool-", "tatkal-booking");
        System.out.println("Idle pool threads, as a thread dump would name them:");        for (String line : liveThreads("pool-", "tatkal-booking")) {            System.out.println("  " + line);        }
        plain.shutdown();        tickets.shutdown();        plain.awaitTermination(1, TimeUnit.SECONDS);        tickets.awaitTermination(1, TimeUnit.SECONDS);    }}
Output
Idle pool threads, as a thread dump would name them:
  pool-1-thread-1 WAITING
  pool-1-thread-2 WAITING
  tatkal-booking-1 WAITING
  tatkal-booking-2 WAITING

What this code does

  • The plain pool's threads get the default names pool-1-thread-1 and pool-1-thread-2. The second pool's ThreadFactory names its threads tatkal-booking-1 and tatkal-booking-2.
  • Idle pool threads are WAITING: they are parked on the pool's queue until the next task arrives. Many WAITING pool threads in a dump usually mean a quiet pool, not a bug.

Good names turn a dump into a story: "two transfer threads are blocked on each other, the audit thread is fine". The same names appear in logs and in uncaught exception messages, so they help long before anything hangs.

Next step

Check your understanding

12 quick questions