Reading a thread dump
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a Java program hangs, slows down or eats threads, the heap is often fine and the problem is in what the threads are doing. A thread dump shows exactly that: every thread, its state and the method it is in, at one moment.
jcmd Thread.print and jstack
A thread dump lists every thread with its state and current stack, used to find stuck, blocked or deadlocked threads.
A thread dump is a text report with the stack trace of every thread in a JVM, plus its state and the locks it holds or waits for. jcmd <pid> Thread.print prints one; jstack <pid> is the older tool that prints the same report.
Example 1 · A train-ticket program that deadlocks
public class TicketDeadlock { static final Object SEAT_LOCK = new Object(); static final Object PAYMENT_LOCK = new Object();
static void bookSeat() { synchronized (SEAT_LOCK) { pause(); synchronized (PAYMENT_LOCK) { System.out.println("Seat booked"); } } }
static void refundPayment() { synchronized (PAYMENT_LOCK) { pause(); synchronized (SEAT_LOCK) { System.out.println("Refund done"); } } }
static void pause() { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { Thread booking = new Thread(TicketDeadlock::bookSeat, "booking-thread"); Thread refund = new Thread(TicketDeadlock::refundPayment, "refund-thread"); booking.setDaemon(true); // daemon: the JVM can still exit when main ends refund.setDaemon(true); booking.start(); refund.start(); System.out.println("Both threads started. Waiting 60 seconds."); Thread.sleep(60_000); System.out.println("Main is done. Booked? No. The two threads are still stuck."); }}Both threads started. Waiting 60 seconds. Main is done. Booked? No. The two threads are still stuck.
What this code does
bookSeatlocks the seat, then the payment;refundPaymentlocks the payment, then the seat. Each thread sleeps 200 ms while holding its first lock, so both always grab one lock and wait forever for the other.- The two threads are daemon threads, so the JVM can still exit when
mainfinishes after 60 seconds. That gives you one minute to take a thread dump. The output is labelled "Sample output" only because the run takes longer than the course checker allows.
Example 2 · The start of its thread dump
jcmd <pid> Thread.print6632: 2026-10-15 23:49:51 Full thread dump OpenJDK 64-Bit Server VM (21.0.7+9-b895.130 mixed mode, sharing): ... "main" #1 [23200] prio=5 os_prio=0 cpu=109.38ms elapsed=6.24s tid=0x000001f38ac1fcb0 nid=23200 waiting on condition [0x00000019e48ff000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep0(java.base@21.0.7/Native Method) at java.lang.Thread.sleep(java.base@21.0.7/Thread.java:509) at TicketDeadlock.main(TicketDeadlock.java:39) "Finalizer" #10 [24648] daemon prio=8 os_prio=1 cpu=0.00ms elapsed=6.14s tid=0x000001f3a32fa8c0 nid=24648 in Object.wait() [0x00000019e51ff000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait0(java.base@21.0.7/Native Method) - waiting on <0x0000000091b0c400> (a java.lang.ref.NativeReferenceQueue$Lock) ... "booking-thread" #21 [28784] daemon prio=5 os_prio=0 cpu=0.00ms elapsed=6.09s tid=0x000001f3a32fe570 nid=28784 waiting for monitor entry [0x00000019e5aff000] java.lang.Thread.State: BLOCKED (on object monitor) at TicketDeadlock.bookSeat(TicketDeadlock.java:9) - waiting to lock <0x0000000091a91670> (a java.lang.Object) - locked <0x0000000091a91660> (a java.lang.Object) at TicketDeadlock$$Lambda/0x000001f3a5000a18.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
- A real dump of
TicketDeadlockon JDK 21, about 6 seconds after start (trimmed with...; the full dump has 13 threads).jstack <pid>printed the same threads and states. mainisTIMED_WAITING (sleeping)at line 39, theThread.sleep(60_000). "Finalizer" is a JVM thread waiting for work, which is normal.booking-threadisBLOCKEDat line 9, the innersynchronized (PAYMENT_LOCK). It holds<...660>and wants<...670>. The addresses identify the two lock objects.
Both are cheap: the JVM pauses briefly, prints, and continues. One dump is a photo. Take three dumps a few seconds apart: a thread stuck in the same line in all three is really stuck, while a busy thread shows different lines each time. -l (on both tools) adds java.util.concurrent locks such as ReentrantLock under "Locked ownable synchronizers". Without any tool, pressing Ctrl+Break in a Windows console, or sending kill -3 <pid> on Linux or macOS, makes the JVM print a dump to its own standard output.
Thread states and stack traces
Each thread in a dump starts with a header line (its name in quotes, then details such as daemon), followed by its java.lang.Thread.State and its stack trace, newest method first.
Example 3 · Every thread state in one program
public class ThreadStatesDemo { static final Object COUNTER_LOCK = new Object(); static final Object NOTICE_BOARD = new Object();
public static void main(String[] args) throws InterruptedException { Thread fresh = new Thread(() -> { }, "fresh");
Thread sleeper = new Thread(() -> { try { Thread.sleep(5_000); } catch (InterruptedException e) { // woken up early by interrupt() } }, "sleeper");
Thread waiter = new Thread(() -> { synchronized (NOTICE_BOARD) { try { NOTICE_BOARD.wait(); // waits until someone calls notify } catch (InterruptedException e) { } } }, "waiter");
Thread blocked = new Thread(() -> { synchronized (COUNTER_LOCK) { // main already holds this lock System.out.println("blocked got the lock"); } }, "blocked");
Thread finished = new Thread(() -> { }, "finished");
sleeper.start(); waiter.start(); finished.start(); finished.join();
synchronized (COUNTER_LOCK) { blocked.start(); Thread.sleep(500);
for (Thread t : new Thread[] {Thread.currentThread(), fresh, sleeper, waiter, blocked, finished}) { System.out.println(t.getName() + ": " + t.getState()); } }
blocked.join(); sleeper.interrupt(); waiter.interrupt(); sleeper.join(); waiter.join(); }}main: RUNNABLE fresh: NEW sleeper: TIMED_WAITING waiter: WAITING blocked: BLOCKED finished: TERMINATED blocked got the lock
What this code does
getState()returns the same values a dump shows.freshwas never started (NEW),finishedhas ended (TERMINATED),sleeperis insleep(TIMED_WAITING),waiteris inwait()with no timeout (WAITING), andblockedwantsCOUNTER_LOCK, whichmainholds (BLOCKED).- The 500 ms pause gives each thread time to reach its state before the states are printed. When
mainleaves itssynchronizedblock,blockedgets the lock and prints its line; thenmaininterrupts the sleeper and the waiter so the program ends quickly.
The states are the six values of the Thread.State enum:
NEW: created, not started yet.TERMINATED: finished. Neither appears in a dump, which lists only live threads.RUNNABLE: running, or ready to run. Threads reading a socket or file in native code also show asRUNNABLE.BLOCKED: waiting to enter asynchronizedblock that another thread holds ("waiting for monitor entry").WAITINGandTIMED_WAITING: waiting for another thread or for time to pass, for examplewait(),join(),LockSupport.park()(shown as "parking"), orsleep()(shown as "sleeping").
Under a frame you may see lock lines: - locked <0x...> means this thread holds that object's monitor, - waiting to lock <0x...> means it wants it, and - parking to wait for <0x...> means it waits on a java.util.concurrent lock or condition.
Finding deadlocks and very deep stacks
A deadlock happens when two or more threads each hold a lock the other one needs, so none of them can ever continue.
Example 4 · The deadlock report at the end of the dump
jcmd <pid> Thread.print... Found one Java-level deadlock: ============================= "booking-thread": waiting to lock monitor 0x000001f388869000 (object 0x0000000091a91670, a java.lang.Object), which is held by "refund-thread" "refund-thread": waiting to lock monitor 0x000001f388869a80 (object 0x0000000091a91660, a java.lang.Object), which is held by "booking-thread" Java stack information for the threads listed above: =================================================== "booking-thread": at TicketDeadlock.bookSeat(TicketDeadlock.java:9) - waiting to lock <0x0000000091a91670> (a java.lang.Object) - locked <0x0000000091a91660> (a java.lang.Object) ... "refund-thread": at TicketDeadlock.refundPayment(TicketDeadlock.java:18) - waiting to lock <0x0000000091a91660> (a java.lang.Object) - locked <0x0000000091a91670> (a java.lang.Object) ... Found 1 deadlock.
What this code does
- The JVM found the cycle for you:
booking-threadwaits for a lock held byrefund-thread, andrefund-threadwaits for a lock held bybooking-thread. Lines 9 and 18 are the two innersynchronizedblocks. - The fix is one lock order everywhere: if
refundPaymentalso lockedSEAT_LOCKfirst andPAYMENT_LOCKsecond, the cycle could not form.
Example 5 · A very deep stack: runaway recursion
java CategoryTreeServerjcmd <pid> Thread.printWorking out category depth. Running for 60 seconds. 22948: ... "main" #1 [26592] prio=5 os_prio=0 cpu=46.88ms elapsed=4.71s tid=0x0000018697c34510 nid=26592 waiting on condition [0x0000004b57dbf000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep0(java.base@21.0.7/Native Method) at java.lang.Thread.sleep(java.base@21.0.7/Thread.java:509) at CategoryTreeServer.depthOf(CategoryTreeServer.java:5) at CategoryTreeServer.depthOf(CategoryTreeServer.java:8) at CategoryTreeServer.depthOf(CategoryTreeServer.java:8) at CategoryTreeServer.depthOf(CategoryTreeServer.java:8) ... (the same line 1018 more times) at CategoryTreeServer.depthOf(CategoryTreeServer.java:8) "Reference Handler" #9 ...
What this code does
CategoryTreeServerrecurses 3000 levels deep indepthOf(line 8 calls itself) and then sleeps at the bottom so it can be dumped. A real product catalogue with a category that lists itself as its parent would do the same untilStackOverflowError.- The dump shows 1022
depthOfframes plus 2sleepframes: 1024 in total, and nomain. HotSpot stopped printing this thread after 1024 frames, so the top-level caller is hidden. The repeated frame and its line number are what you need.
HotSpot detects deadlocks on synchronized monitors and on java.util.concurrent locks, and prints "Found one Java-level deadlock" at the end of the dump, naming each thread, the lock it wants and who holds it. The fix is a code change: always take locks in the same order (seat lock, then payment lock, everywhere), hold locks for less time, or use tryLock with a timeout. Restarting only resets the clock until the same timing happens again. A very deep stack shows the same frame repeated hundreds of times, such as depthOf calling itself. It is the thread dump view of runaway recursion, the same problem that ends in StackOverflowError. HotSpot prints at most 1024 frames of one thread in this dump, so the bottom of a deep stack, including main, can be cut off.
Too many threads and unable to create native thread
Every platform thread (a normal new Thread(...) or pool thread) is backed by an operating system thread with its own native stack, outside the heap: about 1 MB reserved per thread by default on 64-bit Linux, changed with -Xss.
// AlertServer: the bug behind Example 6static void sendAlerts(int request) { ExecutorService pool = Executors.newFixedThreadPool(2); // a new pool per request pool.submit(() -> "SMS for request " + request); pool.submit(() -> "Email for request " + request); // missing: pool.shutdown(); its 2 threads wait for work forever}Thousands of threads also cost CPU time for switching between them.
When the JVM cannot get another OS thread, start() throws OutOfMemoryError: unable to create native thread. On JDK 21 the message continues with "possibly out of memory or process/resource limits reached". The usual cause is a thread leak: a new thread pool per request that is never shut down, or a thread per task that never ends. The OS limit on processes per user, or a container's limit, can also be hit. In the dump, a thread leak looks like hundreds of threads with the same name pattern, such as pool-37-thread-1, all WAITING (parking) for work that never comes. More heap does not help, because thread stacks are not in the heap. Fix the code: one shared pool, shutdown() when done, or virtual threads (Java 21) for many blocking tasks.
Example 6 · Count the threads of a thread leak
jcmd <pid> Thread.print > alert-dump.txtgrep -c '"pool-' alert-dump.txtgrep -A 3 '"pool-50-thread-2"' alert-dump.txt100 "pool-50-thread-2" #120 [27092] prio=5 os_prio=0 cpu=0.00ms elapsed=4.35s tid=0x000001c76822e1a0 nid=27092 waiting on condition [0x00000021030fe000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.7/Native Method) - parking to wait for <0x0000000090427980> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
What this code does
AlertServercalled thesendAlertsmethod shown above for 50 requests, then slept. The dump (JDK 21) has 100 threads namedpool-N-thread-M: 50 pools of 2 threads, all idle and all kept alive. A real server with this bug keeps adding 2 threads per request untilunable to create native thread.- Further down the stack (trimmed here) is
ThreadPoolExecutor.getTaskandLinkedBlockingQueue.take: an idle pool worker waiting for a task. The pool number in the name (pool-50) tells you how many pools were created.
Next step
Check your understanding
11 quick questions