Sub topic 12
Seeing Virtual Threads: Thread Dumps and JFR
Your program may run thousands of virtual threads. When something goes wrong, such as a request that hangs or a service that slows down, you need to see what those threads are doing. This chapter shows you two standard JDK tools for that job. A thread dump shows where every thread is. JDK Flight Recorder shows what happened over time.
You don't need extra libraries. Both tools ship with JDK 21 and later.
Why Observing Virtual Threads Is Different
A thread dump is a snapshot that lists threads and the stack trace of each one. A stack trace is the list of method calls a thread is in right now, with the newest call at the top.
The classic ways to get a thread dump are the jstack tool and the jcmd <pid> Thread.print command. They were built when every Java thread was a platform thread. Those classic dumps do not list virtual threads. They show the carrier threads (the platform threads that run virtual threads), but not the virtual threads themselves.
There is a reason for this. A classic dump pauses the program and prints every thread as plain text. That works for a few hundred threads. With a million virtual threads, the output would be huge and slow to make. So the JDK added a new kind of thread dump that is built for large numbers of threads.
Some other older APIs also skip virtual threads:
| Tool or API | Shows virtual threads? |
|---|---|
| `jstack <pid>` | No |
| `jcmd <pid> Thread.print` | No |
| `Thread.getAllStackTraces()` | No |
| `ThreadMXBean` (JMX) thread lists | No |
| `jcmd <pid> Thread.dump_to_file` | Yes |
| JDK Flight Recorder virtual thread events | Yes |
| IDE debuggers (recent versions) | Yes |
Give Your Threads Names First
A virtual thread has an empty name by default. In a dump, an unnamed thread is hard to tell apart from thousands of others. Each thread still has an ID number, but a name tells you what the thread is for.
You saw Thread.ofVirtual().name("worker-", 0).factory() in an earlier chapter. It builds a thread factory, an object that creates threads for you. Here it creates threads named worker-0, worker-1, and so on. You can pass a factory like this to Executors.newThreadPerTaskExecutor(). You get one virtual thread per task, and every thread has a useful name.
Making a New-Style Thread Dump
The program below starts five named virtual threads. Each one sleeps for five minutes, which gives you time to take a dump. It also prints its PID (process ID). The PID is the number the operating system uses to identify a running program.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DumpMe {
public static void main(String[] args) {
System.out.println("PID: " + ProcessHandle.current().pid());
var factory = Thread.ofVirtual().name("sleeper-", 0).factory();
try (ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {
for (int i = 0; i < 5; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMinutes(5));
return null;
});
}
}
}
}Run it with java DumpMe.java. While it runs, open a second terminal and use the PID it printed. Here we assume it printed 12345:
jcmd 12345 Thread.dump_to_file -format=text threads.txtjcmd is a JDK tool that sends commands to a running Java program. Thread.dump_to_file is the new dump command. It writes the dump to a file rather than to the screen. Use -format=json to get JSON, which tools and scripts can read:
jcmd 12345 Thread.dump_to_file -format=json threads.jsonIf the file already exists, the command refuses to replace it. Delete the old file or choose a new name.
Reading the dump
Each thread in the text dump has a header line and its stack. A virtual thread looks roughly like this (exact line numbers and IDs vary):
#31 "sleeper-0" virtual
java.base/java.lang.VirtualThread.parkNanos(VirtualThread.java:631)
java.base/java.lang.VirtualThread.sleepNanos(VirtualThread.java:803)
java.base/java.lang.Thread.sleep(Thread.java:507)
DumpMe.lambda$main$0(DumpMe.java:13)
...Here is how to read it:
#31is the thread ID."sleeper-0"is the name you gave it.virtualsays it is a virtual thread.- The top lines show it is parked. A parked thread is waiting and does not use its carrier.
Thread.sleepis the cause. - The line with
DumpMe.java:13shows your own code. Look for your own class names first. They tell you which part of your program the thread is in.
The JSON dump also groups threads into thread containers. A thread container is a group of threads that belong together, such as the threads of one executor. That grouping helps when one executor holds 10,000 threads and you want to know which part of the program owns them.
JDK Flight Recorder
A thread dump is a photo. JDK Flight Recorder (JFR) is more like a video. JFR is a recorder built into the JVM. It collects events, which are small records of things that happened, such as "a virtual thread was pinned for 40 ms". It costs very little to run, so you can use it in production.
JFR has several events for virtual threads:
| Event name | What it records | On by default? |
|---|---|---|
| `jdk.VirtualThreadStart` | A virtual thread started | No |
| `jdk.VirtualThreadEnd` | A virtual thread ended | No |
| `jdk.VirtualThreadPinned` | A virtual thread blocked while pinned to its carrier | Yes, if pinned 20 ms or longer |
| `jdk.VirtualThreadSubmitFailed` | Starting or unparking a virtual thread failed | Yes |
Start and end events are off by default because a busy program creates huge numbers of virtual threads. Recording every start and end would produce floods of data.
The pinned event matters most. Recall from the previous chapter: pinning means a virtual thread cannot unmount from its carrier while it blocks, so the carrier sits idle. The pinned event tells you where this happens and for how long.
Recording to a file
Start a recording when you launch the program:
java -XX:StartFlightRecording=filename=rec.jfr,settings=profile MyApp.javaThe recording is written to rec.jfr when the program exits. Then print only the pinned events with the jfr tool, which comes with the JDK:
jfr print --events jdk.VirtualThreadPinned rec.jfrEach event shows its start time, its duration, the thread, and a stack trace. The stack trace points to the code that pinned the thread, such as a synchronized block.
You can also open .jfr files in JDK Mission Control, a free desktop app that draws charts of the events.
Watching events from inside the program
JFR can also stream events to your own code while the program runs. The example below records pinned events and prints each one. It pins on purpose by sleeping inside synchronized.
import java.time.Duration;
import jdk.jfr.consumer.RecordingStream;
public class WatchPinning {
private static final Object LOCK = new Object();
public static void main(String[] args) throws Exception {
try (var stream = new RecordingStream()) {
stream.enable("jdk.VirtualThreadPinned")
.withThreshold(Duration.ofMillis(10))
.withStackTrace();
stream.onEvent("jdk.VirtualThreadPinned", event ->
System.out.println("Pinned for " + event.getDuration().toMillis() + " ms"));
stream.startAsync();
Thread t = Thread.ofVirtual().name("pinner").start(() -> {
synchronized (LOCK) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
t.join();
Thread.sleep(2000); // JFR delivers events about once a second
}
}
}Here is what each part does:
RecordingStreamis a live JFR recording that your program reads.enable(...)turns on the pinned event.withThresholdlowers the limit to 10 ms, andwithStackTracekeeps the stack.onEvent(...)registers code that runs for each event.startAsync()starts recording in the background.- The final
sleepgives JFR time to deliver the event before the stream closes.
On JDK 21 to 23, this prints a line such as Pinned for 50 ms. On JDK 24 and later, it may print nothing. JEP 491 changed synchronized so it no longer pins in this case. If you see no output on a newer JDK, the JVM is behaving correctly. Pinning can still happen there, for example when a thread blocks inside native code, and the same event reports it.
Choosing the Right Tool
Use these rules of thumb:
- Program seems stuck? Take two new-style thread dumps and compare them.
- Throughput lower than expected? Record with JFR and look for
jdk.VirtualThreadPinnedevents. - Logic bug in one task? Use your IDE debugger. Modern debuggers can step through virtual threads like any other thread.
Common Mistakes
- Using
jstackand seeing no virtual threads. Switch tojcmd <pid> Thread.dump_to_file. - Leaving threads unnamed. Name them with a builder or factory so dumps are readable.
- Turning on start and end events in production. They can produce very large recordings. Turn them on only for short tests.
- Expecting pinned events for
synchronizedon JDK 24 and later. That case no longer pins, so the event no longer fires for it.
Exercise
You run jstack on a server that handles 5,000 requests at once on virtual threads, and the output lists only about 30 threads. What is going on, and what command shows all the virtual threads?
Show answer
The classic jstack dump does not include virtual threads. The 30 threads are platform threads, including the carrier threads. Run jcmd <pid> Thread.dumptofile -format=text threads.txt (or -format=json) to get a dump that lists the virtual threads.
Exercise
Which JFR event helps you find code that blocks while a virtual thread is pinned, and what is its default threshold?
Show answer
jdk.VirtualThreadPinned. It is enabled by default and records pinned blocking that lasts 20 milliseconds or longer. You can lower the threshold, as WatchPinning does with withThreshold(Duration.ofMillis(10)).
Exercise
Change DumpMe so the threads are named "order-0", "order-1", and so on. Take a JSON dump and find them. Which single line of code do you change?
Show answer
Change the factory line to var factory = Thread.ofVirtual().name("order-", 0).factory(); then run jcmd <pid> Thread.dumptofile -format=json threads.json and search the file for "order-".