Java Virtual Threads: One Million Threads and the Pinning Trap

Virtual threads let you write plain blocking code that scales to a million concurrent tasks — until a synchronized block pins your carrier threads and throughput collapses. The mechanism, the JDK 24 fix, and an interactive lab.

For twenty years, the thread-per-request model was the obviously correct way to write a server — and the obviously unaffordable one. Each request got its own thread, the code read top-to-bottom, and then the thread count hit a few thousand and the JVM fell over. So we learned the workaround curriculum: bounded pools, callbacks, CompletableFuture chains, reactive frameworks. All of them trade readability for throughput, and all of them make “read a row, call an API, write a row” read like an obstacle course.

Project Loom’s answer, finalized as virtual threads in JDK 21 (JEP 444), was to stop working around the cost of threads and delete it instead. A virtual thread is still a java.lang.Thread — your debuggers, profilers, and thread dumps all keep working — but it isn’t an OS thread. The JVM schedules millions of them onto a handful of platform threads called carriers. When a virtual thread blocks on I/O, it unmounts from its carrier, freeing the OS thread for another virtual thread. When the I/O completes, the scheduler mounts it again — possibly on a different carrier — and it resumes where it left off.

Mount, park, unmount

The entire mental model fits in three words. A virtual thread mounts onto a carrier to run code, parks when it blocks (on a socket read, a lock, a queue take), and unmounts so the carrier can run something else. The default scheduler is a ForkJoinPool sized to your CPU count, so on an 8-core box you get 8 carriers juggling however many virtual threads you create.

The API is deliberately boring — that’s the point:

// Fire and forget
Thread.startVirtualThread(() -> handle(request));

// One virtual thread per task, auto-closed
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var request : requests) {
        executor.submit(() -> handle(request));
    }
} // close() waits for every submitted task

Thread.ofVirtual() gives you a builder (name(...), uncaughtExceptionHandler(...), then .start(runnable) or .unstarted(runnable)) when you want one thread by hand. Executors.newVirtualThreadPerTaskExecutor() is the workhorse: it creates one virtual thread per submitted task and returns a closeable ExecutorService, so try-with-resources replaces all the pool-shutdown ceremony.

Platform threads map one task to one OS thread with a ~1 MB stack each; virtual threads map millions of tiny tasks onto a handful of carrier threads
Two thread models: 1:1 with the OS, or M:N through the JVM’s scheduler.

What virtual threads are not

Three misconceptions to clear before the trap, because the trap only makes sense once these are settled:

They are not faster threads. A virtual thread runs your bytecode at exactly the same speed as a platform thread. What improves is throughput under waiting: ten thousand requests that each spend 49 of 50 milliseconds waiting on a database can now each hold a thread, instead of sharing eight. If your workload is CPU-bound — number crunching, serialization, hashing — nothing ever unmounts and you gain nothing. Virtual threads buy concurrency for waiting, not speed for computing.

You never pool them. A virtual thread is cheap enough to create per task, the way you’d use a String per name. Pooling them reintroduces exactly the queuing and sizing problems they were built to eliminate. If you need to limit concurrency — say, a downstream service that accepts ten simultaneous calls — reach for a Semaphore. Queues of blocked virtual threads are equivalent to queues of tasks, and the semaphore is the honest way to say “at most N at once.”

A million threads is a real number, not a slogan. Because an idle virtual thread is a small heap object whose stack grows and shrinks on demand, the per-thread footprint is measured in kilobytes, not the ~1 MB a platform thread reserves for its stack. The design target was always applications running millions of concurrent threads — and on modern JDKs, that works, right up until you hit the trap.

The pinning trap

JEP 444 names exactly two situations where a virtual thread cannot unmount and is pinned to its carrier:

  1. It executes code inside a synchronized block or method.
  2. It executes a native method or a foreign function.

Pinning doesn’t make your program wrong — it makes it slow in a way that points at the wrong place. Consider the classic: a virtual thread enters a synchronized block and then blocks on a socket read. The read parks the virtual thread, but the virtual thread can’t unmount, so its carrier — a real OS thread — sits blocked too. Do this across all 8 carriers and your “million thread” application quietly degrades into an 8-thread application. Throughput doesn’t dip; it falls off a cliff.

Why couldn’t the JVM just unmount anyway? Because of how monitors are tracked. The JVM records which platform thread holds an object’s monitor, not which virtual thread. If the virtual thread unmounted inside synchronized, the scheduler would mount some other virtual thread on the freed carrier — and the JVM would then believe that other thread held the monitor. Mutual exclusion would be silently lost. So the JVM actively prevents the unmount, and the carrier stays stuck.

The cruelest detail, straight from JEP 444: the scheduler does not compensate for pinning by expanding its parallelism. When carriers get captured by pinned threads, no replacements arrive. Pinning directly shrinks your thread pool, one carrier at a time, until there’s nothing left to schedule on.

Scenario A: a virtual thread that parks on I/O unmounts and frees its carrier. Scenario B: a virtual thread blocked inside synchronized on JDK 21 to 23 pins its carrier, and waiting threads pile up.
Park and unmount (the fast path) versus pinning (the trap): same blocking call, different carrier fate.

The era’s standard advice was mechanical: audit your blocking paths, and wherever a synchronized block guards a potentially long blocking operation, replace it with a java.util.concurrent.locks.ReentrantLock — locks from java.util.concurrent never pinned. Short, infrequent synchronized usage (startup code, in-memory guards) was fine to leave alone. And to find the offenders, the JDK shipped two diagnostics: the JFR event jdk.VirtualThreadPinned, emitted when a thread blocks while pinned, and the system property -Djdk.tracePinnedThreads=full, which printed a stack trace highlighting the monitor-holding frames.

JDK 24 removed the trap

If you’re on a current JDK, here’s the plot twist: the synchronized half of the pinning story is over. JEP 491, Synchronize Virtual Threads without Pinning, delivered in JDK 24 (and riding the JDK 25 LTS), changed the JVM’s monitor bookkeeping so that virtual threads acquire, hold, and release monitors independently of their carriers. A virtual thread that blocks inside synchronized — or blocks acquiring a monitor, or waits in Object.wait() — now unmounts and releases its carrier like any other parked thread.

The JEP is admirably blunt about what this retires: the old guidance to migrate synchronized to ReentrantLock “will no longer be necessary,” the jdk.tracePinnedThreads property was removed outright (setting it now does nothing), and the jdk.VirtualThreadPinned JFR event was kept but repurposed — it now fires for the remaining pinning cases and carries the reason plus the carrier’s identity.

What still pins, per JEP 491? The cases that were never about monitors: a native frame on the stack — calling into JNI or the Foreign Function & Memory API where native code calls back into Java that then blocks — and class loading, where a virtual thread blocks while resolving a class. JEP 444’s second limitation was always “required for proper interaction with native code,” and that part hasn’t changed. The practical upshot: on JDK 24+, synchronized is a free choice again (pick it for simplicity, ReentrantLock for timeouts/fairness/interruptibility), but keep JNI and FFM calls off your hot virtual-thread paths.

One honest caveat from the JEP’s own summary: it promises to eliminate “nearly all cases” of pinning, not all. The mechanism is new, and edge cases in monitor bookkeeping are exactly the kind of thing that surfaces under production load. If you’re migrating a high-throughput service, keep the jdk.VirtualThreadPinned JFR event on your dashboard for the first few releases — trust, but verify.

Try it: the thread lab

Enough theory. The lab below simulates the scheduler semantics — pick the thread model, slide the task count, choose the workload, toggle the synchronized block, and switch JDKs to watch JEP 491 change the outcome:

THREADLAB — LIVE
One million threads and the pinning trap, simulated
Configure the workload, then watch the carriers. On JDK 21 a synchronized block around the blocking call pins every carrier and throughput collapses — on JDK 24+ (JEP 491) the same code unmounts and scales.
Thread model
Workload
JDK version
Concurrent tasks
50,000 simulated
1,000100,000
Carrier threads (simulating an 8-core machine)
carrier 1
PINNED
carrier 2
PINNED
carrier 3
PINNED
carrier 4
PINNED
carrier 5
PINNED
carrier 6
PINNED
carrier 7
PINNED
carrier 8
PINNED
50,000 virtual threads exist, but only 8 can run — the rest wait.
⛔ PINNED — throughput collapses to platform levels
Every virtual thread parks inside synchronized, so none can unmount. All 8 carriers are stuck and the scheduler does not add more. Your 50,000 virtual threads perform exactly like 8 platform threads. Flip the JDK to 24 to see the JEP 491 fix.
Completion time
5.2 min
simulated
Throughput
160/s
simulated
Thread-stack memory
≈ 98 MB
illustrative
Carriers stuck
8/8
pinned!
The code you're simulating
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 50000; i++) { executor.submit(() -> { // JDK 21: blocks inside synchronized → pins the carrier synchronized (lock) { socket.getInputStream().read(buf); // blocks ~50 ms } }); } } // close() waits for every task
Note: this simulates scheduler semantics in your browser — no JVM was harmed. All timings and memory figures are illustrative, not benchmarks. Pinning behavior follows JEP 444 (JDK 21) and JEP 491 (JDK 24+).

Two experiments worth running. First, with the defaults (virtual threads, I/O-bound, synchronized on, JDK 21): watch all eight carriers go red and throughput sit at platform levels no matter how high you push the task slider — that flat red line is the trap. Then flip the JDK to 24 and change nothing else: the same code unmounts, the carriers go green, and throughput scales with the task count. That one toggle is the entire JEP 491 story.

Simulated throughput chart: platform threads plateau at 160 tasks per second while virtual threads scale to 148k per second; virtual threads with synchronized pinning on JDK 21 to 23 collapse back to the plateau
Simulated throughput: platform threads plateau, virtual threads scale — until pinning drags them back to the plateau. (Illustrative numbers, not benchmarks.)

Second experiment: switch the workload to CPU-bound and notice that nothing about virtual threads helps — the carriers do all the work either way, and the numbers match the platform pool exactly. That’s the “not faster threads” section made visible.

Rules of thumb

If you take one checklist from this post:

  1. Write boring blocking code. The thread-per-request style is the whole point — don’t wrap it in reactive scaffolding that defeats unmounting.
  2. Never pool virtual threads. One executor per task via newVirtualThreadPerTaskExecutor(), closed with try-with-resources. Use a Semaphore to cap concurrency against downstream limits.
  3. Know your JDK. On 21–23, synchronized around blocking calls pins carriers — audit with the JFR jdk.VirtualThreadPinned event and prefer ReentrantLock there. On 24+, JEP 491 fixed it; choose locks on ergonomics, not fear.
  4. Keep native frames off the hot path. JNI and FFM calls that block still pin, on every JDK. That’s the remaining trap, and it’s in your dependencies as often as in your code.
  5. CPU-bound work gets nothing. Eight carriers are eight carriers. Virtual threads widen waiting, not computing.

The deeper lesson is about what virtual threads actually changed. They didn’t change how fast code runs — they changed which code is worth writing. For twenty years we contorted straightforward logic into async shapes because threads were expensive. Now the straightforward shape scales to a million concurrent tasks, as long as you know the two ways a thread can get stuck to its carrier, and which JDK you’re standing on.

Sources

Keep reading