Virtual Threads in Java: What They Are and How to Use Them
A virtual thread is a lightweight thread managed by the JVM rather than by the operating system. Virtual threads came out of Project Loom and became a final feature in Java 21 (JEP 444). Thousands or even millions of them run on a small pool of ordinary carrier threads (internally a ForkJoinPool). When a virtual thread blocks — sleeps, waits for a network response, waits for a lock — the JVM unmounts it from its carrier, and the carrier picks up another virtual thread in the meantime. The point is to write server code in the plain thread-per-task style even when tens of thousands of blocking I/O operations are in flight at once.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> callRemoteService()); // a new virtual thread per task
}
} // close() waits for all 10,000 tasks Swapping a thread pool for virtual threads is not a magic switch, though. Move a service to newVirtualThreadPerTaskExecutor() on Java 21 while the database call still sits inside a synchronized method, and the number of concurrent queries will never exceed the number of CPU cores: every thread waiting for the database under a monitor holds on to its carrier. No error, no warning — just none of the expected gain. Why this happens and what changed in Java 24 is covered in Pinning: When a Virtual Thread Sticks to Its Carrier.
Virtual Threads vs Platform Threads
A platform thread is a thin wrapper around an operating system thread: the OS schedules it, its stack memory is reserved up front, and creating thousands of them is expensive. A virtual thread is an object on the JVM heap: the JVM schedules it, its stack grows and shrinks as needed, and creating a million of them is feasible. In code, both are the same class, java.lang.Thread.
Before Java 21 there was no other kind of thread in Java, so the term "platform thread" only appeared together with virtual threads. Here is how they differ:
| Aspect | Platform thread | Virtual thread |
|---|---|---|
| Who schedules it | The operating system scheduler (1:1 with an OS thread) | The JVM: virtual threads take turns on ForkJoinPool carrier threads (M:N) |
| Stack | Fixed size, reserved at creation (about 1 MB by default on 64-bit Linux, -Xss flag) | Stored on the heap, grows and shrinks with call depth |
| Creation cost | A system call that creates an OS thread | Like an ordinary object: cheap |
| How many you can create | Thousands — then you hit memory and OS limits | Hundreds of thousands to millions — heap size is the limit |
| Daemon | Inherited from the creating thread, changed with setDaemon() | Always a daemon; setDaemon(false) throws IllegalArgumentException |
| Priority | 1 to 10, inherited | Always NORM_PRIORITY (5); setPriority() is ignored |
| Default name | Thread-0, Thread-1… | Empty string |
ThreadLocal | Supported | Supported, but a million threads means a million copies of the value |
| Pooling | Yes: threads are expensive, so they are reused via an ExecutorService | No: you create a new thread for every task |
| When to use | Computation (CPU-bound), long-lived background threads, code that needs a real OS thread | Many concurrent tasks that mostly wait: HTTP, databases, queues, files |
A virtual thread is not faster than a platform thread: its code runs on the same CPU with the same instructions. It is cheaper. So the win is measured not by the speed of a single task but by how many tasks you can keep in flight at once (more in When Virtual Threads Don't Help).
How to Create a Virtual Thread
You create a virtual thread with the Thread.ofVirtual() builder, the shortcut Thread.startVirtualThread(), or the Executors.newVirtualThreadPerTaskExecutor() executor, which starts a new virtual thread for each task. The new Thread(...) constructor always creates a platform thread — there is no way to get a virtual one through it.
| Method | Returns | When it fits |
|---|---|---|
Thread.ofVirtual().start(task) | A started Thread | You need a name or an exception handler; unstarted(task) creates it without starting |
Thread.startVirtualThread(task) | A started Thread | Quickly start a single unnamed thread |
Thread.ofVirtual().name("w-", 0).factory() | ThreadFactory | Pass it to an API that accepts a factory; threads get names w-0, w-1… |
Executors.newVirtualThreadPerTaskExecutor() | ExecutorService | The default choice: submit(), Future, invokeAll(), closing with try-with-resources |
The first two methods, with output, are covered in the Thread class lesson (Thread.ofPlatform() and Thread.ofVirtual()), and where this executor fits among the other Executors factories is shown in the ExecutorService pool table. If you want readable thread names in your logs, combine a factory with newThreadPerTaskExecutor():
ThreadFactory factory = Thread.ofVirtual().name("order-", 0).factory();
try (ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {
executor.submit(() -> System.out.println(Thread.currentThread().getName()));
executor.submit(() -> System.out.println(Thread.currentThread().getName()));
}
// Output (line order may vary):
// order-0
// order-1 The word "executor" in newVirtualThreadPerTaskExecutor() does not mean a pool: there is no task queue and no fixed set of threads inside. Every submit() creates a new virtual thread that ends when its task finishes. close() waits until every submitted task is done.
Example: 2,000 Blocking Tasks on Virtual Threads vs a Pool
Virtual threads win where tasks spend most of their time waiting. Two thousand tasks, each waiting 100 ms (here it's sleep(), in real life it would be a service response), finish on virtual threads in roughly the time of a single task, while a pool of 100 threads processes them in "waves" of 100 and needs at least two seconds.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class VirtualVsPool {
static final int TASKS = 2_000;
public static void main(String[] args) {
long virtual = run(Executors.newVirtualThreadPerTaskExecutor());
System.out.println("Virtual threads: " + virtual + " ms");
long pooled = run(Executors.newFixedThreadPool(100));
System.out.println("Pool of 100 threads: " + pooled + " ms");
}
static long run(ExecutorService executor) {
long start = System.nanoTime();
try (executor) { // close() waits for all tasks
IntStream.range(0, TASKS).forEach(i -> executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // "waiting for a response" for 100 ms
return i;
}));
}
return (System.nanoTime() - start) / 1_000_000;
}
} Virtual threads: 142 ms
Pool of 100 threads: 2031 ms The exact numbers depend on the machine, but the ratio holds. The lower bound for the pool can be worked out on paper: 2,000 tasks / 100 threads = 20 waves of 100 ms, so no less than 2,000 ms. The virtual version created 2,000 threads, they all fell asleep almost at once, and while they slept the carriers were free. The extra few dozen milliseconds above 100 are thread creation and JVM warm-up.
Raise TASKS to 100,000 and the pool needs 100 seconds (1,000 waves), while the virtual version still finishes in about the time of one task plus the cost of creating the threads. Growing the pool to 100,000 platform threads won't work on an ordinary machine: that's 100,000 OS threads, and long before you get there you'll see OutOfMemoryError: unable to create native thread or hit an OS limit.
How It Works: Continuations, Mount and Unmount
A virtual thread is a task plus its stack, stored on the heap as a continuation: an object that can suspend at any point and later resume where it left off. To run, a virtual thread is mounted on a carrier thread; when it blocks, the JVM copies its stack frames to the heap and unmounts it, freeing the carrier for another virtual thread.
Carriers are ordinary platform threads owned by a built-in scheduler. It is a dedicated ForkJoinPool running in FIFO mode (not to be confused with ForkJoinPool.commonPool(), which runs parallelStream() and CompletableFuture.supplyAsync()). By default there are as many carriers as available processors (Runtime.getRuntime().availableProcessors()). You can change that with the system property -Djdk.virtualThreadScheduler.parallelism=N, while -Djdk.virtualThreadScheduler.maxPoolSize caps how many carriers the scheduler may temporarily grow to (more on that below).
Unmounting happens when a virtual thread waits: Thread.sleep(), join(), BlockingQueue.take(), Lock.lock(), await() on synchronizers, Future.get(), network I/O through java.net and java.nio.channels. Some operations can't release the carrier — most file operations, for example (an OS limitation), and, on Java 21–23, Object.wait(). In those cases the scheduler temporarily adds another carrier so the remaining virtual threads don't stall. Pinning is a separate story, and there is no such compensation for it.
Code running in a virtual thread can't see its carrier: Thread.currentThread() returns the virtual thread itself. The carrier only shows up in toString():
import java.time.Duration;
public class MountUnmount {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
System.out.println("before sleep: " + Thread.currentThread());
try {
Thread.sleep(Duration.ofMillis(50)); // unmount: the carrier is free
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println("after sleep: " + Thread.currentThread()); // mount, possibly on another carrier
};
Thread.Builder builder = Thread.ofVirtual().name("w-", 0);
Thread first = builder.start(task);
Thread second = builder.start(task);
first.join();
second.join();
System.out.println("isVirtual: " + first.isVirtual()
+ ", cores: " + Runtime.getRuntime().availableProcessors());
}
} before sleep: VirtualThread[#21,w-0]/runnable@ForkJoinPool-1-worker-1
before sleep: VirtualThread[#23,w-1]/runnable@ForkJoinPool-1-worker-2
after sleep: VirtualThread[#21,w-0]/runnable@ForkJoinPool-1-worker-2
after sleep: VirtualThread[#23,w-1]/runnable@ForkJoinPool-1-worker-1
isVirtual: true, cores: 8 The format is VirtualThread[#id,name]/state@carrier-name. Thread ids, line order and worker numbers change from run to run, but the key point is visible: after sleep(), thread w-0 continued on a different carrier. That's why tying anything to the carrier thread makes no sense; everything a virtual thread owns lives in the virtual thread itself — its stack, its ThreadLocal values, its interrupt flag.
Pinning: When a Virtual Thread Sticks to Its Carrier
Pinning is the situation where a virtual thread blocks but the JVM can't unmount it, so the carrier sits idle along with it. On Java 21–23 this happens when a thread blocks inside a synchronized block or method, or inside a native method. In Java 24 (JEP 491), synchronized no longer pins the thread; native methods and calls through the Foreign Function API still do.
Pinning isn't a bug: the program still produces correct results. The problem is that carriers are few. If all of them are held by pinned threads, the other virtual threads wait even though the CPU is idle. What will the program below print? There is one carrier, and four virtual threads each sleep for 200 ms — first under their own synchronized monitor, then under their own ReentrantLock. Each thread has its own lock object, so the threads never wait for each other.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class PinningDemo {
public static void main(String[] args) throws InterruptedException {
// one carrier; the -Djdk.virtualThreadScheduler.parallelism=1 flag is more reliable
System.setProperty("jdk.virtualThreadScheduler.parallelism", "1");
System.out.println("Java " + Runtime.version().feature());
System.out.println("synchronized: " + run(PinningDemo::withSynchronized) + " ms");
System.out.println("ReentrantLock: " + run(PinningDemo::withLock) + " ms");
}
static void withSynchronized() {
Object monitor = new Object(); // each thread has its own monitor
synchronized (monitor) {
pause(); // Java 21-23: the thread is pinned to its carrier
}
}
static void withLock() {
ReentrantLock lock = new ReentrantLock(); // each thread has its own lock
lock.lock();
try {
pause(); // the thread is unmounted from the carrier
} finally {
lock.unlock();
}
}
static void pause() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static long run(Runnable task) throws InterruptedException {
long start = System.nanoTime();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 4; i++) {
threads.add(Thread.ofVirtual().start(task));
}
for (Thread t : threads) {
t.join();
}
return (System.nanoTime() - start) / 1_000_000;
}
} Java 22
synchronized: 807 ms
ReentrantLock: 203 ms On Java 21–23 the four threads under synchronized run strictly one after another: the first one falls asleep holding the only carrier, and the other three wait — 4 × 200 = 800 ms. With ReentrantLock, a thread is unmounted during sleep(), so all four sleep at the same time — 200 ms. On Java 24 and later both lines show about 200 ms. The milliseconds above 800 and 200 vary from run to run.
The JVM reads jdk.virtualThreadScheduler.parallelism once, when it creates the scheduler — that is, on the first virtual thread. In the example the property is set on the first line of main so the program runs without flags; in a real application you set it at launch: java -Djdk.virtualThreadScheduler.parallelism=1 PinningDemo. On a multi-core machine without this property the effect is still there, it just shows up once there are more pinned threads than cores.
The advice depends on your Java version
"Replace synchronized with ReentrantLock for virtual threads" applies to Java 21–23, and only to blocks where the thread waits for a long time: I/O, sleep(), wait(). Short critical sections with no waiting aren't hurt by pinning. On Java 24 and later there's no need to rewrite synchronized for virtual threads. The two mechanisms are compared in Lock vs synchronized, and monitor behavior is covered in synchronized and virtual threads.
How to Detect Pinning
On Java 21–23 you can spot pinning with the system property -Djdk.tracePinnedThreads=full (or =short for a shorter version): whenever a virtual thread blocks while pinned, the JVM prints its stack and marks the frame holding the monitor. For PinningDemo the output looks roughly like this (trimmed):
VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 reason:MONITOR
java.base/java.lang.VirtualThread$VThreadContinuation.onPinned(VirtualThread.java:199)
...
PinningDemo.withSynchronized(PinningDemo.java:18) <== monitors:1
... Java 24 removed this property along with the reason it existed. The approach that works on every version from 21 onward is the JDK Flight Recorder event jdk.VirtualThreadPinned. By default it is recorded when a thread stays pinned for longer than 20 ms:
java -XX:StartFlightRecording=filename=rec.jfr PinningDemo
jfr print --events jdk.VirtualThreadPinned rec.jfr In production JFR is the better option: it needs no special debug flag and shows the duration of each pinning event with a stack trace. The official description of the mechanism is in JEP 444 and JEP 491.
When Virtual Threads Don't Help
Virtual threads don't speed up computation. A task that keeps the CPU busy the whole time (compression, encryption, image processing) runs on a virtual thread exactly as it does on a platform thread, and the number of threads actually running at once is still the number of cores. The gain appears only when tasks spend most of their time waiting.
In VirtualVsPool it all comes down to sleep(). Replace it with 100 ms of computation and the virtual version stops winning: 2,000 tasks of 100 ms CPU time each take at least 25 seconds on 8 cores, no matter which threads run them. Compute-heavy work still needs a pool sized around the core count (how to choose a pool size), and the difference between I/O-bound and CPU-bound tasks is explained in why multithreading is needed and when it doesn't speed things up.
There's a flip side too. A virtual thread doing a long computation doesn't give up its carrier on its own: the scheduler doesn't preempt virtual threads on a time slice. If there are as many such threads as carriers, every other virtual thread waits — including the ones that just got their network response. So heavy computation shouldn't be mixed with I/O tasks on virtual threads; hand it to a separate pool of platform threads.
Finally, virtual threads won't help when there are only a few tasks in flight. A service handling 50 concurrent requests is fine with an ordinary 200-thread pool. They start to pay off when you have thousands of concurrent waiting tasks.
What Not to Do with Virtual Threads
Habits that made sense for expensive platform threads work against you with virtual ones. Don't pool virtual threads, limit access to a resource with a semaphore rather than with pool size, and don't cache heavy objects in ThreadLocal: each of these rules follows from the fact that a virtual thread lives for exactly one task.
| What people do | What happens | What to do instead |
|---|---|---|
Pool virtual threads: Executors.newFixedThreadPool(100, Thread.ofVirtual().factory()) | It works, but no more than 100 tasks run at once — you've lost the very thing you adopted virtual threads for | newVirtualThreadPerTaskExecutor(): one thread per task |
| Rely on pool size to limit database load | There's no pool any more — 10,000 tasks open 10,000 connections at once, and the database or the connection pool gives up | A Semaphore sized to the allowed number of calls to the resource (Semaphore) |
Cache a heavy object in a ThreadLocal (buffer, SimpleDateFormat, client) | The cache is rebuilt for every task and never reused; with a million threads, that's a million copies on the heap | A shared thread-safe object (DateTimeFormatter) or an explicit object pool |
Keep synchronized around a network call on Java 21–23 | Pinning: concurrency is capped by the number of carriers | ReentrantLock around blocking operations, or move to Java 24+ (pinning) |
| Run compute-heavy tasks on virtual threads | No speedup, and long computations hold carriers and delay I/O tasks | A pool of platform threads sized around the core count |
Look for a stuck virtual thread with jstack | Virtual threads aren't in a regular dump — only carriers are | jcmd <pid> Thread.dump_to_file (debugging) |
The second row is the one that bites hardest during migration. A newFixedThreadPool(20) used to protect the database as a side effect: no more than 20 queries could be in flight. Switch to virtual threads and that implicit limit is gone. You bring it back explicitly: acquire() on a semaphore before touching the resource, release() in finally. While a thread waits for a permit it is unmounted and doesn't occupy a carrier — see the example in Synchronizers and virtual threads.
A virtual thread is a task, not a resource
Pools exist to reuse something expensive. A virtual thread costs about as much as a task object, so treat it like one: every new piece of work gets a new thread, and there's no queue. If you feel the urge to limit "the number of threads", what you actually need to limit is something else — connections, API calls, memory — so limit that directly.
A bit more on ThreadLocal. Virtual threads support it, and legacy code that passes request context through it (the user, the transaction, a trace id) keeps working. The only issue is volume: a million threads means a million values. To find the places where virtual threads write to a ThreadLocal, use -Djdk.traceVirtualThreadLocals: the JVM prints a stack trace on every such write. For passing immutable context, newer Java versions offer ScopedValue — covered in the last section.
Virtual Thread Properties: Daemon, Priority, States
A virtual thread is a regular Thread, and almost everything you know about threads applies to it: the same states, the same interruption mechanism, the same visibility and synchronization rules. There are three differences: a virtual thread is always a daemon, its priority is always NORM_PRIORITY, and isVirtual() returns true.
| Property or method | Behavior on a virtual thread | More details |
|---|---|---|
| Daemon | Always isDaemon() == true; setDaemon(false) throws IllegalArgumentException. If you don't wait with join() or close(), the JVM exits without finishing the task | Where the JDK creates daemon threads |
| Priority | Always 5; setPriority() checks the range but doesn't change the value | Priority of virtual threads |
getState() | The same six Thread.State values; a thread waiting on a socket is WAITING, not RUNNABLE | States of virtual threads |
interrupt() | Works as usual; network I/O in a virtual thread is interruptible | Interruption: special cases |
sleep(), yield(), join() | The thread releases its carrier; yield() hands the carrier to another virtual thread | sleep(), yield(), join() |
synchronized | Same semantics; on Java 21–23 blocking inside pins the carrier | synchronized and virtual threads |
Synchronizers, Lock | Waiting goes through LockSupport.park() — the thread is unmounted | Synchronizers and virtual threads |
CompletableFuture | Pass a virtual-thread executor as the second argument of supplyAsync() | CompletableFuture and virtual threads |
volatile, happens-before | The Java Memory Model doesn't change: data races are just as possible as with platform threads | volatile and the memory model |
The first row explains a common mistake in tutorial code: Thread.startVirtualThread(task) at the end of main without join() usually prints nothing — the JVM typically exits before the thread gets to run. With newVirtualThreadPerTaskExecutor() in try-with-resources this can't happen, because close() waits for the tasks.
Debugging: Thread Dumps with Virtual Threads
The familiar jstack and Thread.getAllStackTraces() don't show virtual threads — a dump lists only the carriers. To get a dump that includes every virtual thread, use jcmd, either in plain text or in JSON that's easy to process programmatically.
jcmd <pid> Thread.dump_to_file -format=text threads.txt
jcmd <pid> Thread.dump_to_file -format=json threads.json The reason for this restriction is practical: with a million virtual threads, a classic dump with stacks and monitors for every thread would take gigabytes and pause the application for a long time. The JSON format groups threads by the executor that created them (the text format lists them one after another), so "where are those 10,000 threads stuck" is visible at a glance. The IntelliJ IDEA debugger does show virtual threads and stops on breakpoints in them just as in regular threads.
Structured Concurrency and ScopedValue
Structured concurrency is an approach in which subtasks started inside a block of code must finish before the block exits: if one subtask fails, the others are cancelled and the error propagates to the caller. In Java it's implemented by the StructuredTaskScope class, which at the time of writing is still a preview feature: it first appeared in Java 21 (JEP 453), and Java 25 ships the fifth preview (JEP 505) with a substantially reworked API.
The problem it solves is familiar from ExecutorService: you start two requests with submit(), the first fails, and the second keeps running even though nobody needs its result — you have to cancel it by hand. StructuredTaskScope does that automatically and pairs well with virtual threads: by default each subtask gets its own virtual thread. There's deliberately no code example here: a preview API only compiles with --enable-preview on the matching JDK and has changed from release to release, so check the documentation for your version before using it.
ScopedValue replaces ThreadLocal for passing immutable context down the call chain: the value is bound for the duration of a block, is automatically visible to StructuredTaskScope subtasks, and isn't copied into every thread. In Java 21 it was a preview (JEP 446); it became a final API in Java 25 (JEP 506). On Java 21 without preview flags you're left with ThreadLocal and the caveats from What Not to Do.
The history of virtual threads themselves is shorter: preview in Java 19 (JEP 425) and Java 20 (JEP 436), final in Java 21 (JEP 444), and no more pinning in synchronized in Java 24 (JEP 491). So the minimum sensible version for a project using virtual threads is Java 21, and for code with lots of synchronized in its libraries — Java 24 or later.
Frequently Asked Questions
Will my code get faster if I switch to virtual threads?
A single request won't: a virtual thread runs code at the same speed, and the response time of the database or remote service doesn't change. What grows is throughput — how many requests the service can handle at once — and only if requests mostly wait on I/O and are capped by the pool size. If the bottleneck is the CPU, the database or the connection pool, switching gains nothing. The reasoning is in When Virtual Threads Don't Help.
Do virtual threads replace CompletableFuture and reactive libraries?
For the main goal of asynchronous code — not blocking expensive OS threads while waiting — largely yes: with virtual threads you can write ordinary blocking code and get comparable scalability, while stack traces and debugging stay readable. CompletableFuture is still handy for composing results (thenCombine, allOf), and reactive libraries for data streams with backpressure. You can run CompletableFuture tasks on virtual threads by passing newVirtualThreadPerTaskExecutor() as the second argument of supplyAsync().
How many virtual threads can I create?
There's no fixed limit: a virtual thread is a heap object, so the ceiling is set by the heap size (-Xmx) and stack depth. A waiting thread with a shallow stack takes on the order of a kilobyte or a few, so a million sleeping threads fit in an ordinary heap. If the heap runs out, you get OutOfMemoryError: Java heap space rather than the native-thread creation error you'd see with platform threads.
How do I enable virtual threads in Spring Boot?
From Spring Boot 3.2 on Java 21, the property spring.threads.virtual.enabled=true is enough: the embedded Tomcat starts handling each request on its own virtual thread, and Spring's async tasks move to virtual threads too. Before turning it on, check two things: that the database connection pool is bounded (it's now the thing protecting the database), and, on Java 21–23, that drivers and your own code don't hold synchronized around network calls — otherwise you'll run into pinning.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
All module tasks →
Comments