Virtual Thread Pinning in Java: synchronized, ReentrantLock and the Java 24 Fix
What pinning is, why a pinned virtual thread blocks its carrier, and how synchronized pinned on Java 21–23 but not since JEP 491 in Java 24. A one-carrier experiment compares ReentrantLock, synchronized and class initialization, with advice for each Java version.
kvi5hnuCode Sprout team member8 min readOn this page
Virtual threads scale because a blocked one gives its carrier back (article 11). Sometimes it can't. A virtual thread that blocks while it can't unmount is pinned: it stays mounted, and its carrier, a scarce platform thread, sits blocked with it. This article explains when that happens, shows it in a small experiment, and explains what changed in Java 24.
What pinning costs
The scheduler has about one carrier per core. Pinning one of them for a few milliseconds is harmless. The problem is pinning many of them for a long time:
- Throughput drops. With 8 carriers and 8 virtual threads pinned in slow calls, no other virtual thread in the JVM can run until one of them finishes, even if thousands are ready.
- Latency spikes. Requests that have nothing to do with the slow call wait for a carrier.
- Deadlock becomes possible. If every carrier is held by a pinned thread waiting for something that only an unmounted virtual thread can provide, nothing makes progress.
Pinning is not a correctness problem by itself. The code still does the right thing, just with less concurrency. It matters when the pinned section blocks for a long time and happens often.

What pins a virtual thread
| Situation | Pins? |
|---|---|
Blocking while holding a ReentrantLock or other java.util.concurrent lock | no, on every version |
Blocking inside synchronized, waiting to enter it, or Object.wait() | Java 21–23: yes. Java 24 and later: no (JEP 491) |
| Blocking inside a native method or a foreign (FFM) call, or in Java code called back from native code | yes, on every version |
| Blocking inside a class's static initializer, or waiting for another thread to finish initializing a class | yes, on every version |
Why synchronized pinned at first: the JVM's object monitors recorded their owner as the platform thread running the code. If the virtual thread had unmounted, the carrier would have appeared to own the monitor while running some other virtual thread. So the JVM kept the virtual thread mounted. JEP 491 changed monitors to record the virtual thread as owner, which made unmounting safe.
Native frames and class initialization are different. The JVM can't copy native frames to the heap, and class initialization is tied to the thread inside the JVM's own code. Article 14 looks at native code in detail.
The experiment
The cleanest way to see pinning is to give the scheduler a single carrier. A "holder" virtual thread blocks for 300 ms in some situation. A "bystander" virtual thread starts 50 ms later and records when it actually runs. If the holder unmounted, the bystander runs immediately. If the holder is pinned, the bystander has to wait until the holder finishes:
import java.util.concurrent.locks.ReentrantLock;
public class Solution {
static final long START = System.nanoTime();
static long now() { return (System.nanoTime() - START) / 1_000_000; }
static void pause(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
static final ReentrantLock lock = new ReentrantLock();
static final Object monitor = new Object();
/** Its static initializer blocks. Class initialization still pins on every JDK. */
static class SlowConfig {
static final int VALUE;
static { pause(300); VALUE = 1; }
}
/**
* One carrier only. A "holder" virtual thread blocks for 300 ms in some situation; a
* "bystander" starts 50 ms later. If the holder is pinned, the bystander can't run until it ends.
*/
static void test(String situation, Runnable holderWork) throws InterruptedException {
long t0 = now();
Thread holder = Thread.ofVirtual().start(holderWork);
Thread.sleep(50);
long[] ranAt = new long[1];
Thread bystander = Thread.ofVirtual().start(() -> ranAt[0] = now());
bystander.join();
holder.join();
long waited = ranAt[0] - t0;
System.out.printf("%-38s bystander blocked: %s%n", situation, waited >= 250);
}
public static void main(String[] args) throws InterruptedException {
// Must run before the first virtual thread is created
System.setProperty("jdk.virtualThreadScheduler.parallelism", "1");
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "1");
test("sleep while holding a ReentrantLock", () -> {
lock.lock();
try { pause(300); } finally { lock.unlock(); }
});
test("sleep inside synchronized", () -> {
synchronized (monitor) { pause(300); }
});
test("sleep inside a static initializer", () -> {
if (SlowConfig.VALUE != 1) throw new AssertionError();
});
System.out.println("Java " + Runtime.version().feature());
}
}
Output on Java 25:
sleep while holding a ReentrantLock bystander blocked: false
sleep inside synchronized bystander blocked: false
sleep inside a static initializer bystander blocked: true
Java 25
The same program compiled with --release 21 and run on a Java 21 JDK prints:
sleep while holding a ReentrantLock bystander blocked: false
sleep inside synchronized bystander blocked: true
sleep inside a static initializer bystander blocked: true
Java 21
ReentrantLocknever pins: it waits throughLockSupport.park, which unmounts.synchronizedpinned on Java 21 and no longer does on Java 25.- The static initializer pins on both. The class is being initialized by the holder's thread, so the holder stays mounted for the whole 300 ms.
Setting jdk.virtualThreadScheduler.* from main works only because no virtual thread exists yet. Normally you pass these as -D options on the command line. With the default scheduler (one carrier per core, and some extra carriers added for certain blocking calls), the effect is the same but needs more threads to see.
Which lock to use
On Java 24 and later, synchronized and ReentrantLock both work well with virtual threads. Choose by features, not by pinning:
synchronizedis simpler, can't forget to unlock, and is fine for most mutual exclusion.ReentrantLockaddstryLock,tryLock(timeout),lockInterruptibly, fairness and multipleConditions. Use it when you need one of those.
Don't rewrite working synchronized code just for virtual threads.
On Java 21–23, look for synchronized blocks that block for a long time: network calls, database queries, Object.wait() or long sleeps inside the block. Those are worth converting to ReentrantLock:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
class QuoteCache {
private final ReentrantLock lock = new ReentrantLock();
private final Map<String, Integer> prices = new HashMap<>();
// Before (Java 21–23 pins during the slow call):
// synchronized int priceFor(String route) { ... fetchFromPartner(route) ... }
int priceFor(String route) throws InterruptedException {
lock.lock(); // the lock() call comes before try, as with semaphores
try {
Integer cached = prices.get(route);
if (cached != null) return cached;
int fresh = fetchFromPartner(route); // slow I/O while holding the lock
prices.put(route, fresh);
return fresh;
} finally {
lock.unlock();
}
}
private int fetchFromPartner(String route) throws InterruptedException {
Thread.sleep(100); // stands in for an HTTP call
return 240;
}
}
Short synchronized blocks that only update fields are fine on every version: they hold the carrier for nanoseconds. Many libraries (logging frameworks, JDBC drivers, HTTP clients) replaced their long synchronized sections with ReentrantLock for this reason, so keep dependencies up to date.
The best fix is often design, not lock choice: don't do slow I/O while holding a lock at all. In the cache above, one slow partner call blocks every other caller, even for other routes. A ConcurrentHashMap with per-key computation, or fetching outside the lock and then storing the result, avoids that on any version.
Finding pinning
- JDK Flight Recorder records a
jdk.VirtualThreadPinnedevent, with a stack trace, whenever a virtual thread blocks while pinned for longer than a threshold (20 ms by default). Since Java 24 the event also says why it was pinned, such as native frame or class initialization. Article 16 shows how to record and read it. -Djdk.tracePinnedThreads=fullprinted a stack trace on each pinning event in Java 21–23. It was removed in Java 24. Use the JFR event instead.- Thread dumps (article 17) show what each virtual thread is doing, including pinned ones.
What's current
- JEP 491 (Java 24) lets virtual threads unmount when blocking in
synchronizedorObject.wait(). It's included in Java 25 LTS. - Remaining pinning cases: native methods and FFM downcalls, blocking from Java code called by native code, and class initializers. These are rare in typical server code.
- The
jdk.VirtualThreadPinnedJFR event remains the main way to find pinning and now covers every cause.
Common questions
Is synchronized slow with virtual threads?
Not on Java 24 and later. On Java 21–23 it's only a problem when the thread blocks inside the block or waits a long time to enter it. Uncontended, short synchronized blocks cost the same as always.
Does the scheduler compensate for pinned threads?
Sometimes. For a few blocking calls, such as Object.wait() on Java 21–23, DNS lookups, reading or writing a child process's streams and synchronous file writes, the scheduler temporarily adds a carrier, up to maxPoolSize (256 by default). Ordinary file reads and writes were compensated in Java 21–22 but not since Java 23 (article 14). For other pinned blocking, such as sleeping inside a synchronized block on Java 21, it doesn't, and the carrier is simply lost while the thread is blocked.
Should I replace every synchronized with ReentrantLock?
No. On Java 24+, there's no reason to. On Java 21–23, convert only blocks that do slow blocking work, ideally found with JFR rather than by guessing.
Does ConcurrentHashMap.computeIfAbsent pin?
It uses synchronized internally on a bin while the mapping function runs. On Java 21–23, a slow mapping function, such as one making a network call, pins. On Java 24+ it doesn't pin, but it still blocks other updates to that bin, so keep mapping functions fast anyway.
Summary
- A pinned virtual thread can't unmount, so when it blocks, its carrier blocks too.
- Pinning hurts when many virtual threads are pinned in long blocking calls, which reduces the effective carriers.
ReentrantLockand otherjava.util.concurrentwaits never pin.synchronizedandObject.wait()pinned in Java 21–23 and don't since Java 24.- Native calls and class initialization still pin on every version.
- On Java 24+, choose locks by features. On 21–23, convert
synchronizedblocks that do slow blocking work, and use JFR to find them.
Practice questions
On Java 21, eight carriers are available. A service handles each request by entering synchronized (sharedLock) and calling a 200 ms HTTP API inside. What happens under load, and how does Java 25 change it?
Answer
On Java 21, the thread holding the lock is pinned for 200 ms, and threads waiting to enter synchronized are pinned too. Up to eight requests can tie up all eight carriers, so every other virtual thread in the JVM waits. On Java 25, the holder unmounts during the HTTP call and waiters unmount while waiting, so the carriers stay free. But requests still go through the lock one at a time, five per second: the real fix is to not hold a shared lock during the HTTP call.
Which of these pins a virtual thread on Java 25? (a) Thread.sleep inside synchronized, (b) lock.lock() waiting for a ReentrantLock, (c) a blocking call inside a static initializer, (d) a slow FFM downcall to a C function.
Answer
(c) and (d). Since Java 24, (a) no longer pins, and (b) never pinned.
Why is this method a problem on Java 21 but not Java 24?
synchronized void awaitReady() throws InterruptedException {
while (!ready) wait();
}
Answer
On Java 21, Object.wait() inside synchronized pins the virtual thread for as long as it waits. The scheduler may add a temporary carrier, but many such waiters can still exhaust the carriers. Since Java 24, wait() unmounts the virtual thread like any other blocking operation.
Previous: Limiting Concurrency With Virtual Threads: Semaphores and Rate Limiting in Java
Next: Java Virtual Threads and Native Code: FFM Calls, File I/O and Other Limitations

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.