Path 3 · lesson 1 of 6
Thread lifecycle and the Java Memory Model
What a platform thread costs, the six thread states and how each one looks in a thread dump, interruption, daemon threads, and why one thread may never see another's write.
What you will learn
- Say what one platform thread costs in memory and why the operating system, not the JVM, decides when it runs
- Name the six
Thread.Statevalues and recognise each one in the output ofjcmd <pid> Thread.print - Read a thread dump header line field by field and use
nidandcputo find the thread that is burning CPU - Stop a worker thread with interruption and explain which blocking calls respond to it and which do not
- Predict whether a JVM will exit from the daemon status of its remaining threads
- Explain why a write by one thread is only guaranteed to be seen by another when a happens-before edge links them
Before you start
The concept
A Java program does its work on threads. Until Java 21 every java.lang.Thread was a platform thread, and in a Spring Boot service most still are: the request threads of the embedded web server, the scheduler, the connection pool housekeeper, the garbage collector's helpers. The Thread documentation describes platform threads as typically mapped 1:1 to kernel threads scheduled by the operating system, usually with a large stack and other resources maintained by the operating system.
Three consequences follow, and each one shows up in incidents.
- A thread costs memory outside the heap. Each platform thread has its own stack. On Linux x64 the default stack size is 1024 KB (
-Xss), so 200 request threads reserve about 200 MB of address space for stacks alone. The operating system backs that reservation with physical memory only as the stack is actually used. - The operating system decides who runs. The JVM does not schedule platform threads. If 8 threads want to run and the container has 2 CPUs, the kernel gives each a slice in turn. More threads than CPUs does not add capacity for CPU work, it adds switching.
- A thread that waits still exists. A thread blocked on a slow database call holds its stack and its place in a pool while doing nothing. That is why a pool of 200 threads can be fully occupied at 2% CPU.
At any moment a thread is in exactly one of six states, reported by Thread.getState() and printed in every thread dump. These are JVM states, not operating system states: they tell you what the thread is doing from Java's point of view.
| State | The thread is… | Typical cause in a service |
|---|---|---|
NEW | created, start() not called yet | Never appears in a thread dump: the dump lists started threads |
RUNNABLE | executing in the JVM, or ready to and waiting for a CPU, or inside a native call such as a socket read | Computing, or blocked in I/O the JVM cannot see into |
BLOCKED | waiting to enter a synchronized block or method whose monitor another thread owns | Lock contention, or a deadlock |
WAITING | waiting with no time limit for another thread: Object.wait(), Thread.join(), LockSupport.park() | An idle pool worker waiting for a task; a caller stuck in Future.get() or CompletableFuture.join() |
TIMED_WAITING | the same with a time limit: Thread.sleep, wait(timeout), join(timeout), parkNanos, parkUntil | A scheduler between runs; a poll(timeout) on a queue |
TERMINATED | finished: run() returned or threw | Never appears in a thread dump |
Two more properties decide how a thread ends. Interruption is a request, not a kill: interrupt() sets a flag on the target thread, and it is the target's code that notices and stops. Daemon status decides whether the thread keeps the JVM alive: the shutdown sequence begins when all started non-daemon threads have terminated.
The last idea in this lesson is the one the rest of the path builds on. Threads share the heap, but the Java Memory Model (JMM) does not promise that a value written by one thread is seen by another. In the words of the java.util.concurrent documentation, the results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. Without such an edge the reader may see the new value, an old value, or keep seeing the old value forever.
Why it exists
Most JVM incidents that are not about memory are about threads that are not doing what you think: all of them waiting on the same lock, all of them waiting on each other, one of them spinning, or none of them left to take new work. The artefact that shows this is the thread dump, and it takes ten seconds to capture. Reading it is the single most useful diagnostic skill in this path.
- Requests hang, CPU is idle. The dump shows whether threads are
BLOCKEDon one monitor, parked inCompletableFuture.join(), or deadlocked. Each has a different fix. See requests that never return. - Latency climbs, CPU is moderate. The dump shows a pool whose threads are all waiting on a slow dependency. See checkout latency climbs.
- CPU is pinned. The
cpu=field and thenidfield in the header lines identify which thread is burning it and where. - The service does not stop on deploy. A non-daemon thread that ignores interruption keeps the JVM alive until the orchestrator kills the process.
- A flag is set and nothing happens. A value written without a happens-before edge is not guaranteed to reach the thread that reads it. This is a memory model problem, and no amount of staring at the code's order of statements will reveal it.
How it works inside
What a platform thread is made of
One Java thread is three things that live and die together: the java.lang.Thread object on the heap, a thread structure inside HotSpot (its address is the tid= field of a dump), and an operating system thread with its own stack (its id is the nid= field). start() creates the last two. Until then the state is NEW and the object is just an object.
| Resource | Size | Where it shows |
|---|---|---|
| Thread stack | 1024 KB reserved by default on Linux x64, 2048 KB on Linux AArch64 (-Xss). Physical memory is used only for the part of the stack that has been touched. | Native memory, not the heap. jcmd <pid> VM.native_memory summary reports it under Thread when the JVM was started with -XX:NativeMemoryTracking=summary. |
Thread object and thread-locals | Small, on the heap | Heap dump |
| Kernel thread | One schedulable entity per platform thread | top -H -p <pid> or /proc/<pid>/task |
Java 21 also has virtual threads, which are scheduled by the JDK on a few carrier platform threads and are cheap enough to create per task. Their states and the memory model are the same; what differs is cost and scheduling. They have their own lesson: Virtual threads in Java 21. Everything in the dumps below is a platform thread.
The states, on a real JVM
The program extras/ThreadLifecycle.java starts one thread for each situation and prints Thread.getState(). lock-holder takes a monitor and sleeps inside it. lock-waiter tries to take the same monitor. queue-taker calls take() on an empty LinkedBlockingQueue. socket-acceptor calls ServerSocket.accept() with no client connecting.
Program outputjava -XX:ActiveProcessorCount=2 -Xmx64m ThreadLifecycle.java
Real JVM outputThread.getState() for each thread: not-started NEW daemon=false alive=false busy-worker RUNNABLE daemon=false alive=true socket-acceptor RUNNABLE daemon=false alive=true lock-waiter BLOCKED daemon=false alive=true lock-holder TIMED_WAITING daemon=false alive=true sleeper TIMED_WAITING daemon=false alive=true queue-taker WAITING daemon=false alive=true wait-notify WAITING daemon=false alive=true housekeeper TIMED_WAITING daemon=true alive=true finished TERMINATED daemon=false alive=false
socket-acceptor is RUNNABLE although it is doing nothing: it is inside a native accept call. lock-holder is TIMED_WAITING although it owns a lock that another thread needs: the state describes what the thread itself is doing, not what it holds.The same JVM, a moment later, seen from outside with jcmd <pid> Thread.print. Four of its threads:
Thread dumpjcmd <pid> Thread.print (four of the application threads)
Real JVM output6546: 2026-11-15 21:37:31 Full thread dump OpenJDK 64-Bit Server VM (21.0.13+9-LTS mixed mode, sharing) "lock-holder" #22 [6566] prio=5 os_prio=0 cpu=0.09ms elapsed=2.90s tid=0x00007661044bbe80 nid=6566 waiting on condition [0x00007660dd1e9000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep0(java.base@21.0.13/Native Method) at java.lang.Thread.sleep(java.base@21.0.13/Thread.java:509) at ThreadLifecycle.lambda$main$3(ThreadLifecycle.java:35) - locked <0x00000000ff576820> (a java.lang.Object) ... "lock-waiter" #23 [6568] prio=5 os_prio=0 cpu=0.25ms elapsed=2.70s tid=0x00007661044c8f10 nid=6568 waiting for monitor entry [0x00007660dcfe9000] java.lang.Thread.State: BLOCKED (on object monitor) at ThreadLifecycle.lambda$main$4(ThreadLifecycle.java:40) - waiting to lock <0x00000000ff576820> (a java.lang.Object) ... "busy-worker" #21 [6567] prio=5 os_prio=0 cpu=2381.35ms elapsed=2.70s tid=0x00007661044c7ff0 nid=6567 runnable [0x00007660dd0e8000] java.lang.Thread.State: RUNNABLE at ThreadLifecycle.lambda$main$2(ThreadLifecycle.java:30) ... "socket-acceptor" #27 [6572] prio=5 os_prio=0 cpu=0.51ms elapsed=2.70s tid=0x00007661044cd4c0 nid=6572 runnable [0x00007660dcbe9000] java.lang.Thread.State: RUNNABLE at sun.nio.ch.Net.accept(java.base@21.0.13/Native Method) at sun.nio.ch.NioSocketImpl.accept(java.base@21.0.13/NioSocketImpl.java:748) ...
lock-holder shows - locked <0x00000000ff576820> and lock-waiter shows - waiting to lock <0x00000000ff576820>: the same address, so you know exactly who is blocking whom, and the holder's stack says why (it is asleep inside the synchronized block). Then compare the two RUNNABLE threads: busy-worker has cpu=2381.35ms after 2.70 s of life, socket-acceptor has cpu=0.51ms and its top frame is a native method.The header line, field by field
Each thread in a dump starts with one header line. Taking lock-waiter from the dump above:
| Field | Value here | Meaning and use |
|---|---|---|
| Name | "lock-waiter" | The thread's name. Name your threads and pools: http-nio-8080-exec-7 or outbox-relay tells you the subsystem, Thread-12 tells you nothing. |
#23 | 23 | The Java thread id, the value of Thread.threadId(). JFR events refer to threads by this number (javaThreadId). |
[6568] and nid=6568 | 6568 | The operating system's id for the thread. On Linux it is the id shown by top -H -p <pid>, so it links a hot thread in top to its stack in the dump. |
daemon | absent | Present only for daemon threads. A thread without it keeps the JVM alive. |
prio=5 os_prio=0 | 5, 0 | Java priority and the operating system's priority. Rarely the cause of anything. |
cpu=0.25ms | 0.25 ms | CPU time the thread has consumed in total. Take two dumps: the thread whose cpu grew by the length of the interval is the one on a CPU. |
elapsed=2.70s | 2.70 s | Time since the thread started. A request thread with a very small elapsed in every dump means threads are being created and discarded. |
tid=0x00007661044c8f10 | an address | Address of HotSpot's thread structure. Deadlock reports and some logs refer to it. |
| State phrase | waiting for monitor entry | HotSpot's own wording: runnable, waiting on condition (parked or sleeping), in Object.wait(), waiting for monitor entry (BLOCKED). |
[0x00007660dcfe9000] | an address | An estimate of the thread's valid stack region. |
The second line, java.lang.Thread.State: BLOCKED (on object monitor), is the Java state with a qualifier. The qualifiers you will meet are (on object monitor) for both BLOCKED and Object.wait(), (parking) for LockSupport.park, which is how every java.util.concurrent lock, queue and future waits, and (sleeping). Below it comes the stack, newest frame first, with lock lines interleaved: - locked <addr> under the frame that took a monitor, - waiting to lock <addr> for a BLOCKED thread, - waiting on <addr> for a thread in Object.wait(), and - parking to wait for <addr> for a parked one.
Interruption is cooperative
thread.interrupt() does one of two things. If the target is blocked in sleep, wait or join, that call throws InterruptedException and the interrupt status is cleared. Otherwise the status is simply set, and nothing else happens until the target's code checks it with Thread.currentThread().isInterrupted() or reaches a blocking call that does. A thread blocked on a synchronized monitor does not respond at all. The same run shows all three cases:
Program outputThreadLifecycle.java, interruption part
Real JVM outputinterrupt() on a sleeping thread: sleeper: InterruptedException thrown, isInterrupted() is now false sleeper state after join: TERMINATED interrupt() on a thread blocked on a monitor: lock-waiter state 500 ms later: BLOCKED, isInterrupted() true interrupt() on a busy thread that checks the flag: busy-worker state after join: TERMINATED
interrupt() the thread waiting for the monitor is still BLOCKED with the flag set. It only left when the holder released the lock.- If you catch
InterruptedExceptionand cannot rethrow it, restore the flag withThread.currentThread().interrupt()so that the code above you can still see the request. Thread.interrupted()(static) reads and clears the flag.isInterrupted()only reads it.- Executors use interruption to cancel:
Future.cancel(true)andExecutorService.shutdownNow()interrupt the worker. Code that swallows interrupts cannot be cancelled. - A thread blocked in classic socket I/O does not react to interruption either. Bound such calls with timeouts.
Daemon threads and JVM exit
A thread inherits its daemon status from the thread that creates it, and setDaemon must be called before start(). The JVM begins its shutdown sequence when the last started non-daemon thread ends. Daemon threads are not waited for and get no chance to finish: in the run above the JVM exited with code 0 while housekeeper was still asleep. Use daemon threads for work that is safe to abandon mid-step, and stop everything else explicitly. Virtual threads are always daemon threads.
The Java Memory Model, as an engineer needs it
The JMM is a contract between your code and everything that executes it: the JIT compiler, the CPU and its caches. It gives those layers freedom to keep a field in a register, to reorder independent writes and to delay a store, as long as a single thread cannot tell the difference. Other threads can tell the difference, unless you use one of the constructs that create a happens-before edge:
| Edge | What it guarantees |
|---|---|
| Program order | Within one thread, each action happens-before the actions that come later in that thread |
| Monitor | An unlock of a monitor happens-before every later lock of the same monitor |
volatile | A write to a volatile field happens-before every later read of that field |
Thread.start() | The call to start() happens-before any action in the started thread |
Thread.join() | All actions in a thread happen-before another thread returns from join() on it |
java.util.concurrent | Submitting a task to an executor happens-before its execution; putting an object into a concurrent collection happens-before taking it out; Lock.unlock happens-before a later Lock.lock |
When two threads access the same variable, at least one of them writes, and no happens-before edge orders the accesses, the specification calls it a data race. The specification gives its own example of what is then allowed: for a non-volatile done field, a loop while (!this.done) Thread.sleep(1000) may read the field once and reuse the cached value, so the loop never ends even after another thread sets done. It also states that Thread.sleep and Thread.yield have no synchronisation semantics, so adding a sleep to a loop repairs nothing.
- A reader may never see the write (visibility). The next lesson shows this happening on a real JVM.
- A reader may see writes in a different order from the one in the source (ordering), for example a reference to an object before the values of its non-final fields.
- A non-volatile
longordoublemay be written as two 32-bit halves, so a reader could see half of one value and half of another. Writes and reads of volatilelonganddoubleare always atomic.
A thread dump cannot show a missing happens-before edge. The thread that never sees the flag looks perfectly healthy: RUNNABLE, burning CPU, in the loop it was told to run. That is why this half of the lesson is about reasoning from rules, and the first half about reading evidence.
Architecture
Drawing diagram…
A flowchart of thread states. NEW moves to RUNNABLE on start. RUNNABLE moves to BLOCKED when a monitor is owned by another thread, to WAITING on wait, join or park, to TIMED_WAITING on sleep or a timed wait, and to TERMINATED when run returns. BLOCKED, WAITING and TIMED_WAITING return to RUNNABLE, and a notified waiter passes through BLOCKED to retake the monitor.
flowchart TD
N["NEW"] -->|"start()"| R["RUNNABLE"]
R -->|"monitor owned by another thread"| B["BLOCKED"]
B -->|"monitor acquired"| R
R -->|"wait(), join(), park()"| W["WAITING"]
W -->|"unpark, or the joined thread ends"| R
W -->|"notify: must retake the monitor"| B
R -->|"sleep, timed wait, parkNanos"| TW["TIMED_WAITING"]
TW -->|"time is up, or woken early"| R
R -->|"run() returns or throws"| T["TERMINATED"]- Every path into BLOCKED, WAITING or TIMED_WAITING starts from RUNNABLE: a thread parks itself by running code. That is why the top frame of the stack always tells you what the thread is waiting for.
- RUNNABLE covers three situations the JVM does not distinguish: on a CPU, ready and waiting for a CPU, and inside a native call. Use
cpu=across two dumps to separate them. - A thread that is notified out of
Object.wait()does not go straight back to running. It must take the monitor again and can sit in BLOCKED while the notifier still holds it. - There is no arrow out of TERMINATED. A thread cannot be restarted;
start()on it throwsIllegalThreadStateException.
Step by step
Drawing diagram…
A sequence diagram with a lifecycle thread and a worker thread. The lifecycle thread writes a field and starts the worker, which is guaranteed to see the field. Later it interrupts the worker, whose sleep throws InterruptedException. The worker leaves its loop and writes a result. The lifecycle thread joins the worker and is then guaranteed to see the result.
sequenceDiagram
participant M as Lifecycle thread
participant W as Worker thread
M->>M: write batchSize = 100 to a plain field
M->>W: start
Note over M,W: start happens-before every action of the worker
W->>W: read batchSize, sees 100
W->>W: loop, then sleep 500 ms
M->>W: interrupt
W-->>W: sleep throws InterruptedException
W->>W: restore the flag, leave the loop, write processed = 4200
M->>W: join with a 10 s limit
Note over M,W: all actions of the worker happen-before join returns
M->>M: read processed, sees 4200- The field written before
start()needs novolatileand no lock. The start edge makes everything the starting thread did before the call visible to the new thread. - The interrupt lands while the worker sleeps, so
sleepthrows at once. Had the worker been computing, only the flag would be set and the worker would notice at its next check. - The result written by the worker is read after
join()returns. The join edge makes every write of the finished thread visible. Reading it before the join, or after ajoin(timeout)that timed out, would be a data race. - Between those two edges, anything the two threads share needs its own edge: a
volatilefield, a lock, or ajava.util.concurrentclass.
In a real system
In an incident you rarely know which thread matters. The routine is always the same: take three dumps about five seconds apart, group the threads by pool name, state and top application frame, and look at what does not change between dumps.
- Capture:
jcmd <pid> Thread.print > dump-1.txt, three times. In a container the JVM is usually pid 1:kubectl exec <pod> -- jcmd 1 Thread.print. With Spring Boot Actuator'sthreaddumpendpoint exposed,curl -H 'Accept: text/plain' http://localhost:8080/actuator/threaddumpreturns the same kind of text. - Go to the end of the dump first. If it says
Found one Java-level deadlock, you are done searching. - Count states per pool. Twenty request threads all
BLOCKEDon one address is contention. AllWAITING (parking)under the same frame is starvation or a slow dependency. - For the threads that matter, read down the stack to the first frame of your own code. That line is where the time goes.
- Compare
cpu=between the first and last dump for the suspects. No growth means waiting, whatever the state says.
Contention. In the lock contention lab, 8 threads update one HashMap inside synchronized on 2 CPUs. The dump shows seven threads like the first one below and exactly one like the second:
Thread dumplabs/jvm/lock-contention: jcmd <pid> Thread.print
Real JVM output"view-counter-0" #23 [4626] prio=5 os_prio=0 cpu=830.58ms elapsed=3.65s tid=0x00007e8754631690 nid=4626 waiting for monitor entry [0x00007e872dbfc000] java.lang.Thread.State: BLOCKED (on object monitor) at LockContention.recordGlobal(LockContention.java:23) - waiting to lock <0x00000000f3500540> (a java.util.HashMap) ... "view-counter-5" #28 [4631] prio=5 os_prio=0 cpu=890.45ms elapsed=3.65s tid=0x00007e87546375f0 nid=4631 runnable [0x00007e872d6fb000] java.lang.Thread.State: RUNNABLE at LockContention.spin(LockContention.java:37) at LockContention.recordGlobal(LockContention.java:25) - locked <0x00000000f3500540> (a java.util.HashMap) ...
view-counter-0 is waiting to lock <0x00000000f3500540>. Searching the dump for - locked <0x00000000f3500540> finds view-counter-5, RUNNABLE inside recordGlobal. The lock is healthy and simply too popular. Every one of these threads has about 800 ms of cpu after 3.65 s: they take turns. The fix is in lock contention.Starvation. In the CompletableFuture lab a pool of 2 threads runs tasks that each wait for another task on the same pool. Nothing is BLOCKED and there is no deadlock report, yet no request finishes:
Thread dumplabs/jvm/completablefuture-starvation: jcmd <pid> Thread.print
Real JVM output"order-pool-19" #19 [4074] daemon prio=5 os_prio=0 cpu=0.11ms elapsed=5.74s tid=0x00007384bc58a9a0 nid=4074 waiting on condition [0x00007384957fd000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000f7183c30> (a java.util.concurrent.CompletableFuture$Signaller) ... at java.util.concurrent.ForkJoinPool.managedBlock(java.base@21.0.13/ForkJoinPool.java:3725) at java.util.concurrent.CompletableFuture.waitingGet(java.base@21.0.13/CompletableFuture.java:1898) at java.util.concurrent.CompletableFuture.join(java.base@21.0.13/CompletableFuture.java:2117) at CfStarvation.lambda$main$2(CfStarvation.java:33) ...
WAITING (parking) with CompletableFuture.join on the stack, cpu=0.11ms after 5.74 s. The second pool thread, order-pool-20, looks the same. Both workers are waiting for work that only a free worker could do. The JVM's deadlock detector does not report this because no lock is involved. See CompletableFuture starvation.Deadlock. When threads wait for each other's monitors in a cycle, HotSpot says so at the end of the dump and names the threads and the objects:
Thread dumplabs/jvm/deadlock: end of jcmd <pid> Thread.print
Real JVM outputFound one Java-level deadlock: ============================= "transfer-A-to-B": waiting to lock monitor 0x00007cfef0001760 (object 0x00000000f7654bc0, a Deadlock$Account), which is held by "transfer-B-to-A" "transfer-B-to-A": waiting to lock monitor 0x00007cfefc0015d0 (object 0x00000000f7654ba0, a Deadlock$Account), which is held by "transfer-A-to-B"
cpu well under a millisecond. Nothing will ever change without a restart, and the code fix is a fixed lock order: deadlocks, livelocks and starvation.Java and Spring Boot
A background worker in a Spring Boot 3.x service, written so that it shows up clearly in a dump and stops when asked. OutboxRelay was compiled with javac 21 against stand-in stubs for the Spring and SLF4J types, not against Spring itself. ThreadStates.java is plain Java, was compiled and run on OpenJDK 21.0.13, and is the program used in the exercise.
package com.example.orders.outbox;import java.time.Duration;import java.util.List;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.SmartLifecycle;import org.springframework.stereotype.Component;/** Publishes rows of the outbox table. One named platform thread, started and stopped with the context. */@Componentpublic class OutboxRelay implements SmartLifecycle { private static final Logger log = LoggerFactory.getLogger(OutboxRelay.class); private static final Duration IDLE_PAUSE = Duration.ofMillis(500); private static final Duration STOP_TIMEOUT = Duration.ofSeconds(10); private final OutboxRepository outbox; private final EventPublisher publisher; private volatile Thread worker; public OutboxRelay(OutboxRepository outbox, EventPublisher publisher) { this.outbox = outbox; this.publisher = publisher; } @Override public void start() { worker = Thread.ofPlatform() .name("outbox-relay") .daemon(false) .uncaughtExceptionHandler((t, e) -> log.error("{} died", t.getName(), e)) .start(this::relayLoop); } private void relayLoop() { while (!Thread.currentThread().isInterrupted()) { try { List<OutboxEvent> batch = outbox.nextBatch(100); if (batch.isEmpty()) { Thread.sleep(IDLE_PAUSE); continue; } publisher.publish(batch); outbox.markPublished(batch); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (RuntimeException e) { log.warn("outbox batch failed, will retry", e); } } log.info("outbox-relay stopped"); } @Override public void stop() { Thread t = worker; if (t == null) return; t.interrupt(); try { if (!t.join(STOP_TIMEOUT)) { log.warn("outbox-relay still {} after {}", t.getState(), STOP_TIMEOUT); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Override public boolean isRunning() { Thread t = worker; return t != null && t.isAlive(); }}Why it is written this way
Thread.ofPlatform().name("outbox-relay")gives the thread a name you can search for in a dump. The builder API is standard in Java 21.daemon(false)is deliberate: a half-published batch should not be abandoned, so the thread must be stopped explicitly andstop()waits for it.- The loop condition is the interrupt flag. There is no separate
runningfield to forget to make volatile. catch (InterruptedException e)restores the flag.sleepcleared it when it threw, and without the restore thewhilecondition would never become true.workeris volatile becausestart()andstop()can run on different threads: the main thread at startup and the shutdown hook at exit.join(STOP_TIMEOUT)returns false if the thread is still alive. Logging its state at that point tells you whether it is stuck in I/O or still working.- The uncaught exception handler logs the death of the thread. Without it a
RuntimeExceptionthat escapes the loop ends the thread and the outbox silently stops draining.
import java.util.concurrent.locks.LockSupport;/** Run: java ThreadStates.java then, in a second terminal: jcmd <pid> Thread.print */public class ThreadStates { static final Object lock = new Object(); static volatile long sink; public static void main(String[] args) throws Exception { System.out.println("pid " + ProcessHandle.current().pid()); Thread holder = new Thread(() -> { synchronized (lock) { sleepQuietly(60_000); } }, "lock-holder"); Thread waiter = new Thread(() -> { synchronized (lock) { sink++; } }, "lock-waiter"); Thread parked = new Thread(LockSupport::park, "parked"); Thread busy = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) sink++; }, "busy-worker"); Thread housekeeper = new Thread(() -> sleepQuietly(3_600_000), "housekeeper"); housekeeper.setDaemon(true); holder.start(); Thread.sleep(200); // lock-holder owns the monitor before lock-waiter asks for (Thread t : new Thread[] {waiter, parked, busy, housekeeper}) t.start(); Thread.sleep(500); for (Thread t : new Thread[] {holder, waiter, parked, busy, housekeeper}) { System.out.printf("%-12s %-14s daemon=%s%n", t.getName(), t.getState(), t.isDaemon()); } Thread.sleep(30_000); // take the thread dump now waiter.interrupt(); // does not free a thread that is BLOCKED on a monitor Thread.sleep(200); System.out.println("lock-waiter after interrupt(): " + waiter.getState()); holder.interrupt(); // sleep() throws, the monitor is released busy.interrupt(); LockSupport.unpark(parked); } static void sleepQuietly(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}Why it is written this way
lock-holdersleeps insidesynchronized, so it is TIMED_WAITING while owning the monitor thatlock-waiterneeds.LockSupport.park()is what everyjava.util.concurrentlock and queue calls underneath, soparkedlooks like an idle pool worker in the dump.sleepQuietlyrestores the interrupt flag instead of swallowing it.housekeeperis a daemon. The program ends while it is still sleeping.
Wrong, then right
A price table refreshed every five seconds by a background thread in a singleton @Service. Both versions were compiled with javac 21 against stand-in stubs for the Spring annotations; neither was run inside a Spring context here.
Incorrect implementation
package com.example.pricing;import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;import org.springframework.stereotype.Service;@Servicepublic class PriceRefresher { private final PriceFeedClient feed; private final PriceTable prices; private boolean running = true; // read by the worker, written by the shutdown thread public PriceRefresher(PriceFeedClient feed, PriceTable prices) { this.feed = feed; this.prices = prices; } @PostConstruct void start() { new Thread(() -> { // unnamed ("Thread-0"), non-daemon, nobody keeps a reference while (running) { prices.replaceAll(feed.fetchAll()); try { Thread.sleep(5_000); } catch (InterruptedException ignored) { // swallowed: the interrupt is lost and the loop goes round again } } }).start(); } @PreDestroy void stop() { running = false; // no happens-before edge to the read in the loop }}Why it is written this way
- Three separate faults: a stop flag with no happens-before edge, an interrupt that is caught and dropped, and an anonymous non-daemon thread that nothing can join.
Why it fails
runningis a plain field written by the shutdown thread and read by the worker. No happens-before edge links the two, so this is a data race and the JMM allows the worker to keep using a value it read earlier. The specification's own example of a loop that may never end is exactly this shape, with a sleep inside. On most runs the worker will in fact see the write here; the point is that nothing guarantees it, and the behaviour can change with the JDK version or with what the JIT compiler does to the loop.- Even when the flag is seen, the worker notices it only after the current
sleep(5_000)ends, because the interrupt that would have woken it is caught and ignored. Shutdown is delayed by up to five seconds plus one full fetch. - The thread is not a daemon and nothing waits for it, so the application context closes its beans while the thread may still be inside
prices.replaceAll(...), using collaborators that are already destroyed. In production you see errors logged after the shutdown messages. - If the loop does not end, the JVM cannot exit, because a non-daemon thread is alive. The orchestrator waits out its termination grace period and then kills the process. In a thread dump taken at that moment you would find
Thread-0without the worddaemon, inTIMED_WAITING (sleeping), next to aDestroyJavaVMthread. - The thread is called
Thread-0. Nobody reading a dump can tell what it belongs to.
Corrected implementation
package com.example.pricing;import java.time.Duration;import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;@Servicepublic class PriceRefresher { private static final Logger log = LoggerFactory.getLogger(PriceRefresher.class); private final PriceFeedClient feed; private final PriceTable prices; private volatile Thread worker; // written at startup, read later by the shutdown thread public PriceRefresher(PriceFeedClient feed, PriceTable prices) { this.feed = feed; this.prices = prices; } @PostConstruct void start() { worker = Thread.ofPlatform().name("price-refresher").start(this::refreshLoop); } private void refreshLoop() { while (!Thread.currentThread().isInterrupted()) { try { prices.replaceAll(feed.fetchAll()); Thread.sleep(Duration.ofSeconds(5)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // restore the flag so the loop condition sees it } catch (RuntimeException e) { log.warn("price refresh failed, keeping the previous table", e); } } } @PreDestroy void stop() throws InterruptedException { worker.interrupt(); // wakes sleep() at once and sets the flag otherwise if (!worker.join(Duration.ofSeconds(10))) { log.warn("price-refresher did not stop within 10 s, state {}", worker.getState()); } }}Why it is written this way
- Interruption replaces the flag. It is visible to the worker by definition and it wakes
sleepimmediately. - The
trynow wraps the fetch as well, and a failed fetch is logged and retried on the next round instead of killing the thread. stop()joins with a limit, so the bean is not destroyed until the worker has finished its current round or ten seconds have passed.- The reference to the thread is kept in a volatile field, because the shutdown hook thread reads what the startup thread wrote.
Trade-offs
- Shutdown now waits for the worker: up to 10 seconds here. That time comes out of the pod's termination grace period, so the limit has to be shorter than it.
- Interruption only reaches code that cooperates. If
feed.fetchAll()blocks in a socket read without a timeout,interrupt()does nothing until the read returns, and the join limit is what bounds the wait. The HTTP client needs its own timeouts. - A hand-made thread is more code than
@Scheduled(fixedDelay = 5000), which gives you a named, managed scheduler thread and is the better choice when the work is a simple periodic task. Write your own thread when you need control over its lifecycle, as here. - Making the thread a daemon instead would let the JVM exit at once, at the price of abandoning a refresh halfway. That is acceptable for a cache and not for anything that writes.
Configuration
The settings that decide what a platform thread costs and what a thread dump contains. Defaults are those documented for JDK 21.
-Xss (same as -XX:ThreadStackSize)Default Platform dependent: 1024 KB on Linux x64 and macOS x64, 2048 KB on Linux AArch64 and macOS AArch64
- What it does
- The stack size of each Java thread. The actual size may be rounded up to a multiple of the system page size.
- When to change it
- Leave it alone unless you have evidence. Raise it for
StackOverflowErrorin legitimately deep recursion. Lowering it to fit more threads is rarely the right answer: fewer threads, or virtual threads, usually are.
jcmd <pid> Thread.print -lDefault false
- What it does
- Also prints
java.util.concurrentlocks: aLocked ownable synchronizerssection per thread, which shows who owns aReentrantLock. - When to change it
- Add it when threads are
WAITING (parking)on a lock and you need the owner. Without it the dump only identifies owners ofsynchronizedmonitors.
jcmd <pid> Thread.print -eDefault false
- What it does
- Prints extended thread information. On this JDK the header line gained
allocated=anddefined_classes=fields. - When to change it
- Useful when hunting a thread that allocates heavily. Not needed for lock problems.
-XX:ActiveProcessorCountDefault none (the JVM asks the operating system)
- What it does
- Overrides the number of CPUs the JVM uses to size its own thread pools, such as GC threads and the common ForkJoinPool.
- When to change it
- Used in the labs to reproduce a 2 CPU machine. In containers the JVM normally detects the CPU limit itself.
Hands-on exercise
Produce every state, then find them in a dump
Run a small program on your own JDK 21, take a thread dump from a second terminal, and match each thread's state, lock lines and cpu time to what the code is doing.
Steps · 0 of 6 done
What you should see
The program prints lock-holder TIMED_WAITING, lock-waiter BLOCKED, parked WAITING, busy-worker RUNNABLE and housekeeper TIMED_WAITING with daemon=true. In the dump, lock-holder has a - locked <address> line and lock-waiter has - waiting to lock with the same address under BLOCKED (on object monitor). parked shows WAITING (parking) with LockSupport.park on top. busy-worker's cpu is a large share of its elapsed time and keeps growing if you take a second dump; the others stay under a millisecond. Only housekeeper has daemon in its header. No deadlock is reported, because lock-holder is not waiting for anything lock-waiter owns. The last line reads lock-waiter after interrupt(): BLOCKED, and the JVM then exits although housekeeper never finished.
What can go wrong
Reading RUNNABLE as busy
- Symptom
- A dump shows 150 request threads RUNNABLE and the team concludes the service is CPU bound, but the host shows 5% CPU.
- Cause
- Threads inside native socket reads and accepts are RUNNABLE. The state says the JVM is not making them wait; it says nothing about the operating system.
- Fix
- Read the top frame and compare
cpu=across two dumps. Frames such assun.nio.ch.Net.acceptor a socket read with flat cpu time mean the thread is waiting for the network.
Swallowing InterruptedException
- Symptom
shutdownNow()orFuture.cancel(true)returns, but the task carries on. A shutdown that waits for the pool withawaitTerminationruns into its time limit on every deploy.- Cause
catch (InterruptedException e) {}discards the request, and the throwing call has already cleared the flag, so no later check can see it.- Fix
- Rethrow, or call
Thread.currentThread().interrupt()in the catch block and leave the loop.
Unnamed threads and pools
- Symptom
- The dump is full of
Thread-7andpool-3-thread-12, and nobody can say which component owns the stuck ones. - Cause
- Threads were created with
new Thread(runnable)or an executor without a thread factory. - Fix
- Name every thread:
Thread.ofPlatform().name("outbox-relay"), or a factory such asThread.ofPlatform().name("report-", 0).factory()for a pool.
Trusting a plain field across threads
- Symptom
- A flag or a configuration value is updated and one thread keeps using the old value, sometimes for good. It cannot be reproduced in a debugger.
- Cause
- No happens-before edge between the write and the read. The JIT compiler and the CPU are allowed to act as if the field belonged to one thread.
- Fix
- Give the pair an edge:
volatilefor a single value, a lock for several, or hand the value over through ajava.util.concurrentclass. The next two lessons cover the choice.
One dump
- Symptom
- A single dump shows a thread deep in JSON serialisation and an hour is spent optimising it.
- Cause
- One dump is one instant. Any thread is somewhere at any instant.
- Fix
- Take three, five seconds apart. Only what stays the same across them is evidence.
How to troubleshoot
Requests hang and CPU is near zero
Check
jcmd <pid> Thread.print | grep -A 12 'Java-level deadlock'
- How to read it
- Output means a monitor deadlock: the report names the threads and the objects. No output means look at the states instead: count
grep -c 'BLOCKED (on object monitor)'andgrep -c 'WAITING (parking)'and read the top frames of the largest group.
One or two CPUs are pinned
Check
top -H -p <pid> then jcmd <pid> Thread.print | grep 'nid=<thread id from top>'
- How to read it
top -Hlists threads with their own ids and CPU share. The id of the hottest one equalsnid=in the dump on Linux with JDK 21, which gives you its name and stack. A hot thread namedGC Thread#0orC2 CompilerThread0is the JVM itself, not your code.
Many threads BLOCKED
Check
jcmd <pid> Thread.print | grep 'waiting to lock' | sort | uniq -c | sort -rn
- How to read it
- Groups the blocked threads by monitor address. One address with a large count is one hot lock. Search for
- locked <that address>to find the owner and what it is doing while holding it.
The process stays up after the application has finished or was told to stop
Check
jcmd <pid> Thread.print | grep '^"' | grep -v ' daemon '
- How to read it
- Lists the non-daemon threads. If
DestroyJavaVMis among them,mainhas returned and the JVM is waiting for the other non-daemon threads in the list: their stacks show what they are doing. If the process was sentSIGTERMand is still up, look instead for a shutdown hook thread that is stuck, typically in ajoinorawaitTerminationwithout a limit.
Native memory or thread count keeps growing
Check
jcmd <pid> Thread.print | grep -c 'java.lang.Thread.State'
- How to read it
- Counts Java threads. Run it a few minutes apart. A steadily rising count with names like
pool-41-thread-1means executors are being created per request and never shut down. Each thread reserves a stack of-Xss.
Threads parked on a ReentrantLock and no owner in sight
Check
jcmd <pid> Thread.print -l
- How to read it
- Adds a
Locked ownable synchronizerssection to every thread. The thread that lists the lock the others areparking to wait foris the owner.
Key takeaways
- A platform thread is an operating system thread with its own stack, 1024 KB by default on Linux x64. The kernel schedules it, and it costs memory whether it runs or waits.
- A thread dump lists every started thread with one of four live states. BLOCKED means a
synchronizedmonitor, WAITING and TIMED_WAITING mean the thread parked itself, RUNNABLE means the JVM is not holding it back. - RUNNABLE is not proof of CPU use. Check the top frame and the growth of
cpu=between two dumps. - waiting to lock <addr>and- locked <addr>with the same address connect a blocked thread to the owner.- Interruption is a flag and a wake-up for sleep, wait and join. Never swallow
InterruptedException; a thread blocked on a monitor does not respond to it. - Left alone, the JVM exits when the last non-daemon thread ends. On
System.exitorSIGTERMit runs the shutdown hooks and then stops every thread where it is, so stop and join your workers from a lifecycle callback, with a time limit. - A write is guaranteed visible to another thread only across a happens-before edge: a lock, a volatile field, start, join, or a
java.util.concurrenthand-over.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 4
A payment service stops answering. CPU is at 3%. Three thread dumps taken five seconds apart all show the 40 threads named pay-exec-* in WAITING (parking) with CompletableFuture.join near the top of the stack, each with cpu= unchanged between dumps. The end of every dump has no deadlock section.
What do the dumps tell you?
Scenario 2 of 4
A report service runs on 4 CPUs and one of them sits at 100% with flat traffic. top -H -p 1 shows thread id 4711 using 99% CPU. In a thread dump, 180 threads are RUNNABLE, most of them with sun.nio.ch frames on top.
What is the quickest way to the stack of the code that is burning the CPU?
Scenario 3 of 4
A nightly batch job built on Spring Boot logs that its work is done and that the context is closed, and then the process stays up until the scheduler kills it 30 minutes later. A dump taken in between shows "Thread-3" #41 prio=5 ... waiting on condition in TIMED_WAITING (sleeping) inside a while (running) loop whose catch block for InterruptedException is empty, plus a DestroyJavaVM thread.
Which change addresses the cause?
Scenario 4 of 4
A worker thread fills a plain long processed field and a plain List<String> errors field while it runs. The thread that started it calls worker.join() with no timeout and then reads both fields to build a report. Neither field is volatile and no lock is used anywhere.
Is the report guaranteed to see the worker's final values?
References
References: Java SE 21 API: Thread.State (the six states and what causes them) ↗ · Java SE 21 API: Thread (platform and virtual threads, interrupt, daemon, join) ↗ · Java SE 21 API: Runtime (shutdown sequence and JVM termination) ↗ · Java Language Specification, Java SE 21, chapter 17: Threads and Locks (17.3 sleep and yield, 17.4.5 happens-before, 17.7 long and double) ↗ · Java SE 21 API: java.util.concurrent, Memory Consistency Properties ↗ · JDK 21 Troubleshooting Guide: Diagnostic Tools (jcmd, thread dump header line, thread states, deadlock detection) ↗ · JDK 21 tool reference: jcmd (Thread.print and its -l and -e options) ↗ · JDK 21 tool reference: java (-Xss, -XX:ThreadStackSize, -XX:ActiveProcessorCount) ↗ · Spring Boot Actuator API: threaddump endpoint ↗ · Report a problem