Sub topic 11
Pinning: When a Virtual Thread Holds Its Carrier
In the chapter on carrier threads, you saw how a virtual thread unmounts when it blocks. Unmounting means the virtual thread steps off its carrier thread, and the carrier is free to run other virtual threads. That is what lets a few carriers serve thousands of virtual threads.
Sometimes a virtual thread cannot step off. It stays stuck to its carrier while it waits. This is called pinning. This chapter explains what pinning is, when it happens, why it can slow your program, and what you can do about it.
What Pinning Means
A carrier thread is a platform thread that the JVM uses to run virtual threads. The JVM keeps only a small number of them, usually one per CPU core.
Pinning happens when a virtual thread blocks but cannot unmount. The virtual thread is "pinned" to its carrier, so the carrier waits along with it. While that happens, no other virtual thread can use that carrier.
Here is a simple way to picture it. A carrier is a taxi and a virtual thread is a passenger. Normally, when a passenger stops to wait for something, they get out and the taxi picks up someone else. A pinned passenger refuses to leave the taxi while they wait. The taxi sits idle at the curb.
Why Pinning Matters
One pinned thread for a short time is harmless. The trouble starts when many virtual threads get pinned at once.
Say your machine has 8 carriers. If 8 virtual threads are pinned at the same moment, all 8 carriers are busy waiting. Every other virtual thread, even one that is ready to run, has to wait for a free carrier. Your program now behaves as if it had only 8 threads. You lose the main benefit of virtual threads.
Pinning does not make your program wrong. Your code still gives correct results. It only hurts scalability, which is how well your program handles more and more work at the same time.
When Pinning Happens
What causes pinning depends on your JDK version. This matters, because a fix you read about for one version may not be needed in another.
| Situation | JDK 21 to 23 | JDK 24 and later |
|---|---|---|
| Blocking inside a `synchronized` block or method | Pins | Does not pin (fixed by JEP 491) |
| Calling `Object.wait()` inside `synchronized` | Pins | Does not pin |
| Blocking inside a native method or foreign function call | Pins | Still pins |
| Blocking while a class is being initialized | Pins | Still pins |
A synchronized block is Java's built-in way to let only one thread at a time run a piece of code. A native method is a method written in another language, such as C, and called from Java.
In everyday code, the most common cause on JDK 21 to 23 is synchronized. Many older libraries use it heavily, so you may hit pinning without writing synchronized yourself.
Seeing Pinning in Action
The program below runs 200 tasks two ways. Each task holds a lock and sleeps for 50 milliseconds. The first version uses synchronized. The second uses a ReentrantLock, which is a lock object from java.util.concurrent.locks that you lock and unlock yourself.
Each task gets its own lock object, so the tasks never wait for each other. Any slowdown comes from pinning alone.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class PinningDemo {
private static final int TASKS = 200;
private static final Object[] MONITORS = new Object[TASKS];
private static final ReentrantLock[] LOCKS = new ReentrantLock[TASKS];
static {
for (int i = 0; i < TASKS; i++) {
MONITORS[i] = new Object();
LOCKS[i] = new ReentrantLock();
}
}
interface Task {
void run(int id) throws InterruptedException;
}
static void withSynchronized(int id) throws InterruptedException {
synchronized (MONITORS[id]) {
Thread.sleep(50); // on JDK 21-23 this pins the virtual thread
}
}
static void withReentrantLock(int id) throws InterruptedException {
LOCKS[id].lock();
try {
Thread.sleep(50); // the virtual thread can unmount while it sleeps
} finally {
LOCKS[id].unlock();
}
}
static long timeIt(Task task) {
Instant start = Instant.now();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < TASKS; i++) {
int id = i;
executor.submit(() -> {
task.run(id);
return null;
});
}
} // close() waits for every task to finish
return Duration.between(start, Instant.now()).toMillis();
}
public static void main(String[] args) {
System.out.println("Java version: " + Runtime.version());
System.out.println("synchronized: " + timeIt(PinningDemo::withSynchronized) + " ms");
System.out.println("ReentrantLock: " + timeIt(PinningDemo::withReentrantLock) + " ms");
}
}Save it as PinningDemo.java and run it. To make the effect easy to see, limit the scheduler to 2 carriers:
java -Djdk.virtualThreadScheduler.parallelism=2 PinningDemo.javaOn JDK 21 to 23, you will see something like this:
Java version: 21.0.5+11
synchronized: 5040 ms
ReentrantLock: 62 msThe synchronized version is slow because only 2 tasks can sleep at a time. 200 tasks divided by 2 carriers, times 50 ms, comes to about 5 seconds. The ReentrantLock version lets every virtual thread unmount, so all 200 sleep together and finish in about 50 ms.
On JDK 24 or later, both lines show a small number. That is JEP 491 at work. Your exact times will differ from these, depending on your machine.
Finding Pinning in Your Program
You cannot fix pinning until you know where it happens. Two tools help.
Trace option (JDK 21 to 23)
The system property jdk.tracePinnedThreads prints a stack trace when a virtual thread blocks while pinned. A stack trace is the list of method calls that led to the current line of code.
java -Djdk.virtualThreadScheduler.parallelism=2 -Djdk.tracePinnedThreads=short PinningDemo.javaUse short for a brief trace or full for the complete one. Look for lines marked <== monitors:1. They point at the synchronized code that caused the pin. JDK 24 removed this option, so on newer versions use JDK Flight Recorder (JFR), described next.
JDK Flight Recorder (all versions)
JDK Flight Recorder (JFR) is a tool built into the JDK that records events while your program runs. It records a jdk.VirtualThreadPinned event when a virtual thread stays pinned for longer than 20 milliseconds.
java -XX:StartFlightRecording=filename=pin.jfr PinningDemo.java
jfr print --events jdk.VirtualThreadPinned pin.jfrEach event shows how long the thread was pinned and the stack trace where it happened. The chapter on observing virtual threads covers JFR in more detail.
Reducing the Impact of Pinning
When you find pinning that matters, you have a few options. Pick the simplest one that fits.
- Upgrade the JDK. On JDK 24 or later,
synchronizedno longer pins. This fixes the most common cause without code changes. - Replace
synchronizedwithReentrantLockwhere the code blocks while holding the lock. This is the fix in the demo above. Always callunlock()in afinallyblock so the lock is released even if an exception is thrown. - Move blocking work out of the lock. Often you can do the slow part, such as a network call, before or after the locked section. Keep only the quick shared-data update inside the lock.
- Update libraries. Many popular libraries, such as JDBC drivers, have released versions that avoid
synchronizedaround I/O. Check the release notes.
Here is option 3 in practice. The slow call happens outside the lock:
import java.util.ArrayList;
import java.util.List;
public class ShortLock {
private final List<String> results = new ArrayList<>();
String fetch(int id) throws InterruptedException {
Thread.sleep(50); // stands in for a slow network call
return "result " + id;
}
void handle(int id) throws InterruptedException {
String value = fetch(id); // blocking work, no lock held
synchronized (results) { // quick update, nothing blocks here
results.add(value);
}
}
public static void main(String[] args) throws InterruptedException {
ShortLock app = new ShortLock();
Thread t = Thread.ofVirtual().start(() -> {
try {
app.handle(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t.join();
System.out.println(app.results);
}
}The synchronized block here is fine even on JDK 21. Nothing inside it blocks, so the pin lasts only an instant.
Exercises
Exercise
In your own words, what is pinning, and why does it hurt scalability but not correctness?
Show answer
Pinning is when a virtual thread blocks but cannot unmount, so its carrier thread waits with it. The code still runs correctly. But pinned carriers cannot run other virtual threads, so when many threads are pinned the program can only do as many things at once as there are carriers.
Exercise
You run on JDK 21. A method holds a synchronized lock while it makes a 2-second HTTP call. Name two ways to stop it from pinning.
Show answer
Replace synchronized with a ReentrantLock and call unlock() in a finally block, or move the HTTP call outside the synchronized block so only the quick update is locked. Upgrading to JDK 24 or later also removes this kind of pinning.
Exercise
Run PinningDemo with -Djdk.virtualThreadScheduler.parallelism=4 on JDK 21 to 23. About how long should the synchronized version take, and why?
Show answer
About 2.5 seconds. Only 4 carriers can hold pinned sleeping threads at once, so 200 tasks run in 50 groups of 4, and each group takes 50 ms: 50 times 50 ms equals 2500 ms.
Exercise
Which JFR event shows pinning, and which tool prints it from a recording file?
Show answer
The jdk.VirtualThreadPinned event. Print it with: jfr print --events jdk.VirtualThreadPinned pin.jfr