Sub topic 12
Seeing virtual threads in thread dumps and JFR
This chapter assumes you have enabled spring.threads.virtual.enabled=true in a Spring Boot 3.2+ MVC application on Java 21. It also assumes you know what pinning is and can run jcmd against a local JVM. The goal is to confirm that virtual threads are doing the work and to find out when they are not behaving well.
Why the usual tools show too little
A JVM with thousands of virtual threads has only a handful of platform threads: the carrier threads of the scheduler's ForkJoinPool. Tools built for platform threads therefore give a misleading picture.
jstackandjcmd <pid> Thread.printlist platform threads only. You see carriers such asForkJoinPool-1-worker-1, but not the virtual threads that are mounted on them or waiting.- The Spring Boot Actuator
/actuator/threaddumpendpoint reads threads throughThreadMXBean, which does not report virtual threads either. - A virtual thread that is blocked and unmounted is a heap object, not a native thread. It only shows up in tools that know how to find it.
Java 21 gives you two supported ways to look. One is the JSON thread dump. The other is JFR (Java Flight Recorder), which records virtual-thread events.
Step 1: confirm the property took effect
Start with the cheap check from earlier in the tutorial. The endpoint below returns whether the current request thread is virtual.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class ThreadInfoController {
@GetMapping("/thread")
String thread() {
Thread current = Thread.currentThread();
return "virtual=" + current.isVirtual() + ", thread=" + current;
}
}With the property set, the response looks like virtual=true, thread=VirtualThread[#47,tomcat-handler-0]/runnable@ForkJoinPool-1-worker-1. The text after the / shows the state and the carrier the thread is currently mounted on. If you see virtual=false, check the Java version, the Boot version, and whether a custom TomcatProtocolHandlerCustomizer or executor bean overrides the auto-configuration.
Step 2: take a JSON thread dump
The plain-text dump omits virtual threads, so ask for JSON.
java -Djdk.tracePinnedThreads=full -jar app.jar
jcmd <pid> Thread.dump_to_file -format=json threads.jsonThe first command starts the application with pinning traces enabled (covered below). The second writes a dump that includes virtual threads. The file groups threads into containers. A container is a structured owner of threads, such as the root container for threads created directly, or the one belonging to a newVirtualThreadPerTaskExecutor().
Use jq to get a summary instead of reading thousands of lines.
jq '.threadDump.threadContainers[] | {container, threadCount}' threads.json
jq '.threadDump.threadContainers[].threads[] | select(.name | startswith("tomcat-handler")) | .stack[0:3]' threads.jsonThe first command shows how many threads each container holds. The second prints the top three stack frames of every thread whose name starts with tomcat-handler. Thread names come from the thread factory, so adjust the prefix to match your server and executors.
A healthy I/O-bound service usually shows many virtual threads with stacks that end in a socket read, a JDBC call, or a park inside a lock. If most of them are stuck in the same frame, that frame is the bottleneck. This is often a connection pool wait (HikariPool.getConnection) or a semaphore.
Reading the dump for capacity problems
Virtual threads make it easy to create far more concurrent work than a database can serve. In the dump, look for these patterns:
- Hundreds of threads parked in
HikariPool.getConnection. The pool is the limit, as expected. Add aSemaphorein front of the call, as described earlier, so waiting happens in your code and not in the pool. - Many threads blocked in a client call to one downstream host. That service is the limit.
- Many threads in a
synchronizedframe on the same object. This is lock contention, and on Java 21 it may also be pinning.
Dumping from inside the application
You can also trigger a JSON dump from code, for example behind a protected operations endpoint. HotSpotDiagnosticMXBean.dumpThreads writes the same format.
import com.sun.management.HotSpotDiagnosticMXBean;
import java.io.IOException;
import java.lang.management.ManagementFactory;
class ThreadDumper {
static void dump(String file) throws IOException {
HotSpotDiagnosticMXBean bean =
ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
bean.dumpThreads(file, HotSpotDiagnosticMXBean.ThreadDumpFormat.JSON);
}
}The target file must not already exist, and the path is resolved on the server's file system. Do not expose this to untrusted callers.
Step 3: find pinning
Pinning means a virtual thread blocks while it cannot unmount from its carrier. On Java 21 the main causes are blocking inside synchronized and blocking in a native frame. Use a reproducible example to see what the tools report.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class PinningDemoController {
private final Object monitor = new Object();
@GetMapping("/pinned")
String pinned() throws InterruptedException {
synchronized (monitor) {
Thread.sleep(200);
}
return "done";
}
}Call /pinned while the application runs with -Djdk.tracePinnedThreads=full. When the thread blocks in sleep, the JVM prints a stack trace to standard output. The frame that holds the monitor is marked with <== monitors:1. That marker points to the synchronized block to rewrite.
The property prints only when the blocking happens, so it finds pinning that your traffic actually triggers, not pinning that could happen. Use short instead of full to print only the frames that matter, at the cost of less context.
JFR covers the same case without parsing logs. The jdk.VirtualThreadPinned event is enabled by default and fires when a virtual thread parks while pinned for longer than its threshold, which is 20 ms by default.
java -XX:StartFlightRecording=filename=rec.jfr,settings=profile -jar app.jar
jfr print --events jdk.VirtualThreadPinned rec.jfrEach event includes the duration and a stack trace. Group them by top frame to find the few call sites that account for most of the pinned time. Replace synchronized around blocking code with a ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final ReentrantLock lock = new ReentrantLock();
private long value;
long increment() {
lock.lock();
try {
return ++value;
} finally {
lock.unlock();
}
}
}Native frames are different. If a trace shows a native method or a foreign call between the virtual thread and the blocking call, you cannot fix it with a lock change. Look for a library update or move that call to a separate bounded executor.
Step 4: count virtual threads over time with JFR
Two events record the lifecycle of virtual threads: jdk.VirtualThreadStart and jdk.VirtualThreadEnd. They are disabled by default because a busy service can create them at a very high rate. Enable them for a short test recording only.
java -XX:StartFlightRecording=filename=rec.jfr,settings=profile,jdk.VirtualThreadStart#enabled=true,jdk.VirtualThreadEnd#enabled=true -jar app.jar
jfr summary rec.jfr
jfr print --events jdk.VirtualThreadStart rec.jfrjfr summary lists every event type with its count, which gives you the creation rate directly. A third event, jdk.VirtualThreadSubmitFailed, is enabled by default. It appears when the scheduler cannot start or continue a virtual thread, which points to a resource problem in the JVM and should not appear in normal operation.
You can tune the scheduler and compare results across runs with these system properties:
| Property | Meaning | Default |
|---|---|---|
| `jdk.virtualThreadScheduler.parallelism` | Number of carrier threads that run virtual threads | Number of available processors |
| `jdk.virtualThreadScheduler.maxPoolSize` | Upper bound on carriers, which can grow temporarily when threads block in some operations | 256 |
| `jdk.tracePinnedThreads` | Prints a stack trace on pinned blocking (`full` or `short`) | Off |
Change them only with a measurement in hand. The default parallelism is right for most services.
A verification routine
Use these steps against a staging environment under realistic load.
- Call
/threadand confirmvirtual=true. - Start with
-Djdk.tracePinnedThreads=fulland run a load test. Collect every trace. - Take a JSON dump during the load test. Summarize it with
jqand check for large groups of threads in one frame. - Record a JFR profile and check
jdk.VirtualThreadPinnedevents by top frame and total duration. - Fix the call sites that account for most pinned time, then repeat from step 2.
Exercise
A colleague runs jcmd <pid> Thread.print on a service with virtual threads enabled and sees only a few dozen threads, although the service is handling thousands of concurrent requests. What is happening, and what command should they run instead?
Show answer
The text thread dump lists only platform threads, and virtual threads are not included. The few dozen threads are mostly carrier threads and JVM internals. They should run jcmd <pid> Thread.dump_to_file -format=json threads.json, which includes virtual threads, and then summarize the file with jq.
Exercise
Your JFR recording contains many jdk.VirtualThreadPinned events, and all of them have the same top frame inside a synchronized method that calls a JDBC driver. What do you change on Java 21, and what would you check if the events remain after the change?
Show answer
Replace the synchronized block around the blocking call with a ReentrantLock (or restructure so the blocking call is outside the monitor). If events remain, inspect the stack traces for native or foreign frames between the virtual thread and the blocking call. A native frame pins regardless of locks, so the fix is a library update or moving that call to a separate bounded executor.
Exercise
Why are jdk.VirtualThreadStart and jdk.VirtualThreadEnd disabled by default, and how would you use them safely?
Show answer
A busy service can create thousands of virtual threads per second, so recording an event for each start and end adds noticeable overhead and produces large files. Enable them only for a short test recording with jdk.VirtualThreadStart#enabled=true,jdk.VirtualThreadEnd#enabled=true in -XX:StartFlightRecording, then read the creation rate with jfr summary.