Sub topic 9
Pinning: when a virtual thread cannot unmount
This chapter assumes you know how virtual threads are mounted on carrier threads, that you can enable them in Spring Boot with spring.threads.virtual.enabled=true, and that you are comfortable with synchronized, ReentrantLock, and java.util.concurrent. The behavior described here applies to Java 21. Later releases changed part of it, as noted below.
What pinning means
A virtual thread runs by being mounted on a carrier thread. A carrier thread is a platform thread from the scheduler's small pool (a ForkJoinPool). When the virtual thread blocks on something the JDK knows about, such as a socket read, Thread.sleep, or Lock.lock, it unmounts. Its stack is copied to the heap, and the carrier is free to run another virtual thread. When the blocking operation finishes, the virtual thread is scheduled again, possibly on a different carrier.
Pinning is the case where unmounting is not possible. The virtual thread stays attached to its carrier while it blocks. The carrier is then blocked too, and no other virtual thread can use it until the blocking call returns.
Pinning does not cause incorrect results. It costs throughput, because each pinned thread holds a whole carrier. The scheduler's parallelism defaults to the number of CPU cores. If that many virtual threads are pinned and blocked at once, no other virtual thread can run, and the application can look frozen.
What causes pinning on Java 21
Two situations pin a virtual thread on Java 21.
- The thread blocks while inside a
synchronizedblock or method. - The thread blocks while a native method or a foreign function call is on its stack.
The reason is how the JVM stores stack frames. A frame that holds a monitor, or a frame for native code, cannot be copied to the heap and restored later. So the JVM keeps the thread on its carrier.
Pinning happens only when the thread blocks in one of these states. Holding a synchronized block around a short in-memory update does not hurt. The problem is blocking I/O or a blocking wait inside it.
class StockCache {
private final Object monitor = new Object();
private String cached;
String get(String sku) {
synchronized (monitor) {
if (cached == null) {
cached = remoteLookup(sku); // blocking HTTP call while holding the monitor
}
return cached;
}
}
private String remoteLookup(String sku) {
// blocking network call
return "stock-" + sku;
}
}In this example, a virtual thread that enters get and waits on the network stays pinned for the whole call. Other threads that need the monitor also wait. On a platform thread this was only slow. With virtual threads, it also removes carriers from the pool.
The diagram below shows the difference between a normal block and a pinned block.
Where pinning shows up in a Spring Boot application
Your own code is only one source. Pinning often comes from libraries.
- Older JDBC drivers and connection pools that use
synchronizedaround network I/O. - Logging appenders that synchronize while writing to a file or socket.
- Legacy caching or client code that wraps remote calls in
synchronizedmethods. - Native libraries called through JNI, where a blocking call sits below a native frame.
Spring Boot itself is not the usual cause, but any dependency can be. Check which versions you run before blaming the framework. Many libraries replaced synchronized with ReentrantLock after Java 21 shipped, so upgrading a driver or pool is often the first fix.
Fixing pinning with ReentrantLock
When you own the code, replace synchronized sections that block with a ReentrantLock. A virtual thread that waits for a ReentrantLock can unmount.
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();
}
}
}Always release the lock in a finally block. Unlike synchronized, a ReentrantLock is not released automatically when the block exits.
Apply the change where it matters:
- Change sections that perform blocking I/O, sleep, or wait on other threads while holding the lock.
- Leave short, non-blocking
synchronizedsections alone. Rewriting them adds risk and gains nothing. - Do not rewrite
synchronizedcode you do not control. Upgrade the dependency instead.
You can also reduce the time spent inside the lock. Do the remote call first, outside any lock, then enter the lock only to store the result.
Changes after Java 21
Java 24 (JEP 491) changed how monitors work for virtual threads. A virtual thread that blocks inside synchronized can now unmount, so the first cause above mostly goes away on Java 24 and later. Pinning for native frames and foreign function calls remains. If you run Java 21, which is the minimum for Spring Boot virtual threads and a common long-term support choice, you still need the guidance in this chapter.
| Cause | Java 21 | Java 24 and later |
|---|---|---|
| Blocking inside `synchronized` | Pins the carrier | Virtual thread can unmount |
| Blocking with a native or foreign frame on the stack | Pins the carrier | Still pins the carrier |
| Blocking on `ReentrantLock` | Unmounts | Unmounts |
Detecting pinning
Look for pinning before production, using a load test that includes realistic blocking calls.
The jdk.tracePinnedThreads system property prints a stack trace when a virtual thread blocks while pinned on Java 21. Use full for every frame, or short for only the frames that cause the pinning.
java -Djdk.tracePinnedThreads=full -jar app.jar
jcmd <pid> Thread.dump_to_file -format=json threads.jsonThe first command starts the application with tracing on. The trace names the method and the monitor or native frame that holds the thread. The second command writes a JSON thread dump that includes virtual threads, so you can see what blocked threads are doing.
Java Flight Recorder also records a jdk.VirtualThreadPinned event. By default it fires when a pinned thread blocks for longer than 20 ms. This is better for production because it adds little overhead and does not print to the console. Chapter 12 covers JFR in detail.
A useful workflow:
- Enable
-Djdk.tracePinnedThreads=fullin a test environment. - Run a load test that exercises your slowest endpoints and dependencies.
- Collect the stack traces and group them by the top frame in your code or library.
- Fix the frequent and long ones first. A pin that lasts microseconds is not worth the effort.
Tuning as a stopgap
The scheduler has system properties that control how many carriers it uses. These include jdk.virtualThreadScheduler.parallelism and jdk.virtualThreadScheduler.maxPoolSize. Raising them gives pinned threads more carriers to occupy. This can reduce the symptom, but it moves the application back toward the thread-count limits that virtual threads were meant to remove. Treat it as a temporary measure while you fix or upgrade the pinning code.
Common errors
- Assuming all
synchronizedis bad. Only blocking inside it causes pinning. - Fixing the wrong layer. A trace that ends in a driver class needs a driver upgrade, not a rewrite of your service.
- Forgetting
unlock. After moving toReentrantLock, a missingfinallyleaves the lock held forever. - Reading the trace once. Pinning depends on the code path. Test the paths that make real downstream calls.
- Using a pool to hide the issue. Limiting concurrency with a
Semaphoreprotects a database, but it does not remove pinning.
Exercise
A Spring Boot service on Java 21 uses virtual threads. Under load, throughput drops and -Djdk.tracePinnedThreads=full shows many traces ending in a third-party client's synchronized method that performs an HTTP call. You cannot change the library's source. Name two actions you can take, and explain why raising jdk.virtualThreadScheduler.maxPoolSize is not a lasting fix.
Show answer
Upgrade the library to a version that uses ReentrantLock or non-blocking synchronization, or move the call behind your own wrapper so it does not run inside the library's monitor where possible. Upgrading to Java 24 or later also removes pinning for synchronized. Raising maxPoolSize only adds carriers for pinned threads to occupy. It brings back a limit on how many blocking calls can run at once, which is the limit virtual threads are meant to remove, and it does not fix the cause.
Exercise
In the StockCache example, which change removes the pinning risk on Java 21 while keeping the cache correct for concurrent callers?
Show answer
Replace the synchronized (monitor) block with a ReentrantLock, locking before the check and unlocking in a finally block. A virtual thread waiting on the remote call inside that lock can then unmount. Better still, perform the remote lookup outside the lock and use the lock only to read and write cached, accepting that two threads may occasionally both perform the lookup.