Virtual threads
A virtual thread is a thread managed by the JVM rather than the operating system. Creating one costs about as much as creating an object, and when it blocks on I/O or sleep it releases the OS thread it runs on, so blocking thread-per-request code scales to many thousands of concurrent tasks. This page explains mounting and carriers, measures scale and memory, shows pinning and how to detect it, and covers the ThreadLocal and concurrency-limit traps.
Contents
What a virtual thread is and how it runs
A traditional platform thread is a thin wrapper around an operating system thread. OS threads are expensive: each reserves a large stack, often 1 MB by default, and costs a system call to create, so a server can run only a few thousand of them. A server that handles each request on its own thread therefore runs out of threads long before it runs out of CPU, because most threads spend their time waiting for a database or another service. The usual way out, asynchronous code with callbacks or reactive streams, scales but is hard to write, debug and profile.
A virtual thread is an ordinary java.lang.Thread
- Carriers: virtual threads run on a small pool of platform threads, a
with one carrier per CPU core by default.ForkJoinPool - Mounting: to run, a virtual thread is mounted on a carrier, and its stack frames are on that carrier's stack.
- Unmounting: when it blocks, in
, socket I/O, a lock or aThread.sleep , the JVM copies its frames to a small object on the Java heap and frees the carrier for another virtual thread. When the operation completes, the thread is mounted again, possibly on a different carrier.BlockingQueue - Pinning: in a few situations the frames cannot be moved, and the virtual thread blocks its carrier as well. That is the main limitation, covered below.
The result is that blocking code costs only memory, not OS threads, so the simple thread-per-request style scales to hundreds of thousands of concurrent tasks. The code itself does not change: the same ThreadExecutorService
| JDK | JEP | Change |
|---|---|---|
| 19, 20 | JEP 425, 436 | Preview |
| 21 | JEP 444 | Standard; synchronized |
| 24 | JEP 491 | Monitors reimplemented: synchronized |
| 25 | none | Current long-term support release, used for this page |
The programs below were compiled and run on JDK 25 on a 2-core Linux machine, so the default scheduler has 2 carriers.
Creating virtual threads
There are three common ways. The program uses each one, then starts a platform thread to compare their properties.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CreateVirtual {
public static void main(String[] args) throws Exception {
// 1. Builder: named, started immediately
Thread t1 = Thread.ofVirtual().name("worker-1").start(() ->
System.out.println("builder: " + Thread.currentThread().getName()
+ " virtual=" + Thread.currentThread().isVirtual()));
t1.join();
// 2. Shortcut
Thread t2 = Thread.startVirtualThread(() ->
System.out.println("shortcut: unnamed=" + Thread.currentThread().getName().isEmpty()
+ " daemon=" + Thread.currentThread().isDaemon()));
t2.join();
// 3. Executor: one new virtual thread per task, closed by try-with-resources
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Integer> f = executor.submit(() -> 6 * 7);
System.out.println("executor: result " + f.get());
}
// Platform threads for comparison
Thread p = Thread.ofPlatform().name("platform-1").start(() -> { });
p.join();
System.out.println("platform: virtual=" + p.isVirtual() + " daemon=" + p.isDaemon());
}
}
Output:
builder: worker-1 virtual=true
shortcut: unnamed=true daemon=true
executor: result 42
platform: virtual=false daemon=false
is a builder for setting a name or other options.Thread.ofVirtual() creates an unnamed thread, so its name is empty.Thread.startVirtualThread fits existingExecutors.newVirtualThreadPerTaskExecutor() code. ItsExecutorService , called by try-with-resources, waits for submitted tasks.close()- Virtual threads are always daemon threads, so they do not keep the JVM alive. A platform thread built without options is non-daemon.
Virtual threads are not pooled. They are cheap enough to create one per task, and a pool would only reintroduce the limit they remove.
Blocking at scale
The program submits 10,000 tasks that each block for 200 ms, which stands in for a remote call. It then runs 1,000 of the same tasks on a fixed pool of 100 platform threads. The machine used for this page has 2 CPU cores, so the virtual threads have only 2 carriers.
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class Scale {
static final Set<String> carriers = ConcurrentHashMap.newKeySet();
static void blockingCall() {
try {
Thread.sleep(Duration.ofMillis(200)); // stands in for an HTTP or JDBC call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// toString of a virtual thread names its current carrier: ...@ForkJoinPool-1-worker-3
String s = Thread.currentThread().toString();
carriers.add(s.substring(s.indexOf('@') + 1));
}
static long run(ExecutorService executor, int tasks) {
long start = System.nanoTime();
try (executor) {
IntStream.range(0, tasks).forEach(i -> executor.submit(Scale::blockingCall));
} // close() waits for all tasks
return (System.nanoTime() - start) / 1000000;
}
public static void main(String[] args) {
int cores = Runtime.getRuntime().availableProcessors();
long virtualMs = run(Executors.newVirtualThreadPerTaskExecutor(), 10000);
System.out.println("10,000 tasks on virtual threads finished in under 2 s: "
+ (virtualMs < 2000));
System.out.println("carrier threads used: " + carriers.size() + " (cores: " + cores + ")");
long platformMs = run(Executors.newFixedThreadPool(100), 1000);
System.out.println("1,000 tasks on 100 platform threads took at least 2 s: "
+ (platformMs >= 2000));
}
}
Output:
10,000 tasks on virtual threads finished in under 2 s: true
carrier threads used: 2 (cores: 2)
1,000 tasks on 100 platform threads took at least 2 s: true
- All 10,000 virtual threads were sleeping at the same time, so the run took little more than one 200 ms sleep, even though only 2 OS threads carried them. The carrier count equals the number of cores by default, so it will differ on your machine.
- The platform pool can run only 100 tasks at once, so 1,000 tasks need 10 rounds of 200 ms: at least 2 seconds. Running 10,000 there would take at least 20 seconds, and starting 10,000 platform threads instead would use thousands of OS threads.
Virtual threads help when tasks spend their time waiting. They do not make CPU-bound code faster: with 2 cores, at most 2 tasks compute at any moment, whatever kind of thread runs them.
What a blocked virtual thread costs
The program starts 100,000 virtual threads that all block on the same latch, then checks how many OS threads exist and how much heap the blocked threads use.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Footprint {
static long usedHeap() {
System.gc();
Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
public static void main(String[] args) throws InterruptedException {
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
int platformBefore = mx.getThreadCount();
long heapBefore = usedHeap();
CountDownLatch release = new CountDownLatch(1);
CountDownLatch started = new CountDownLatch(100000);
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
threads.add(Thread.ofVirtual().start(() -> {
started.countDown();
try {
release.await(); // all 100,000 block here
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
started.await();
long heapBlocked = usedHeap();
System.out.println("virtual threads blocked at once: " + threads.size());
int added = mx.getThreadCount() - platformBefore;
System.out.println("platform (OS) threads added: fewer than 10? " + (added < 10));
long perThread = (heapBlocked - heapBefore) / threads.size();
System.out.println("heap per blocked virtual thread: under 2 KB? " + (perThread < 2048));
release.countDown();
for (Thread t : threads) {
t.join();
}
System.out.println("all finished: " + threads.stream().noneMatch(Thread::isAlive));
}
}
Output:
virtual threads blocked at once: 100000
platform (OS) threads added: fewer than 10? true
heap per blocked virtual thread: under 2 KB? true
all finished: true
- All 100,000 threads were blocked at the same moment, yet fewer than 10 OS threads were added: the carriers and a few JVM helper threads. 100,000 platform threads would need 100,000 OS threads and, with 1 MB stacks, up to about 100 GB of reserved address space.
- Each blocked virtual thread used under 2 KB of heap for its saved stack. The figure grows with the depth of the call stack at the moment it blocks, so a thread blocked deep inside a framework uses more.
- The program prints yes-or-no checks rather than exact numbers, because heap measurements vary from run to run.
Pinning: when a virtual thread cannot unmount
Sometimes a blocked virtual thread cannot release its carrier. It is then pinned, and the carrier is blocked too. In Java 21 to 23, the most common cause was blocking inside a synchronized
The program measures this. It runs with a single carrier (-Djdk.virtualThreadScheduler.parallelism=1synchronized
import java.util.ArrayList;
import java.util.List;
public class Pinning {
// Each task sleeps while holding its own monitor lock
static void sleepInsideSynchronized(Object lock) {
synchronized (lock) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws InterruptedException {
// Run with -Djdk.virtualThreadScheduler.parallelism=1: a single carrier thread
long start = System.nanoTime();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Object lock = new Object();
threads.add(Thread.ofVirtual().start(() -> sleepInsideSynchronized(lock)));
}
for (Thread t : threads) {
t.join();
}
long ms = (System.nanoTime() - start) / 1000000;
String outcome = ms < 1500 ? "overlapped (not pinned)" : "ran one after another (pinned)";
System.out.println("Java " + Runtime.version().feature()
+ ": 4 x 500 ms sleeps on 1 carrier " + outcome);
}
}
Output on JDK 25:
Java 25: 4 x 500 ms sleeps on 1 carrier overlapped (not pinned)
The same program compiled and run on JDK 21:
Java 21: 4 x 500 ms sleeps on 1 carrier ran one after another (pinned)
Pinning still happens on current JDKs when a virtual thread blocks inside a native method or a foreign function call, and in a few JDK internals such as class initialization. If you are on Java 21, replace synchronizedReentrantLock-Djdk.tracePinnedThreadsjdk.VirtualThreadPinned
Finding pinning with JFR
The JFR event jdk.VirtualThreadPinnedRecordingStreamsynchronizedqsort
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import jdk.jfr.consumer.RecordingStream;
// Records the JFR event jdk.VirtualThreadPinned while virtual threads block in two ways
public class PinDetect {
static final Object LOCK = new Object();
// Called from C (qsort) and sleeps: a native frame is on the stack, so it pins
static int slowCompare(MemorySegment a, MemorySegment b) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0));
}
@SuppressWarnings("restricted")
static void sortInC() throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle qsort = linker.downcallHandle(linker.defaultLookup().find("qsort")
.orElseThrow(), FunctionDescriptor.ofVoid(ValueLayout.ADDRESS,
ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle cmp = MethodHandles.lookup().findStatic(PinDetect.class, "slowCompare",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
try (Arena arena = Arena.ofConfined()) {
FunctionDescriptor cmpDesc = FunctionDescriptor.of(ValueLayout.JAVA_INT,
ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT),
ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT));
MemorySegment stub = linker.upcallStub(cmp, cmpDesc, arena);
MemorySegment data = arena.allocateFrom(ValueLayout.JAVA_INT, 2, 1);
qsort.invokeExact(data, 2L, 4L, stub);
}
}
public static void main(String[] args) throws Exception {
AtomicInteger pinned = new AtomicInteger();
try (RecordingStream rs = new RecordingStream()) {
rs.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ofMillis(10));
rs.onEvent("jdk.VirtualThreadPinned", e -> pinned.incrementAndGet());
rs.startAsync();
Thread.ofVirtual().start(() -> {
synchronized (LOCK) { // pinned on Java 21 to 23 only
try {
Thread.sleep(30);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).join();
Thread.sleep(1500);
System.out.println("pinned events while sleeping in synchronized: " + pinned.get());
pinned.set(0);
Thread.ofVirtual().start(() -> {
try {
sortInC();
} catch (Throwable t) {
throw new IllegalStateException(t);
}
}).join();
Thread.sleep(1500);
System.out.println("pinned events while sleeping in a C callback: "
+ (pinned.get() > 0 ? "at least 1" : "0"));
}
}
}
Output (JDK 25, run with --enable-native-access=ALL-UNNAMED
pinned events while sleeping in synchronized: 0
pinned events while sleeping in a C callback: at least 1
- Sleeping inside
produced no event on JDK 25. The same test on JDK 21 records 1 event, which is the change JEP 491 made.synchronized - Sleeping inside a callback from C produced at least one event. A native frame sits on the stack between the virtual thread's start and the sleep, and the JVM cannot move native frames to the heap, so the carrier stayed blocked for the 30 ms.
- In production, record with
and look for this event; its stack trace shows the frame that caused the pinning. Seejava -XX:StartFlightRecording ...Java Flight Recorder .
Trap: ThreadLocal caches stop caching
Code written for thread pools often caches an expensive, non-thread-safe object per thread in a ThreadLocalSimpleDateFormat
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalCost {
static final AtomicInteger created = new AtomicInteger();
// A per-thread cache of an object that is not thread-safe and costly to build
static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> {
created.incrementAndGet();
return new SimpleDateFormat("yyyy-MM-dd");
});
static void run(String label, ExecutorService pool) {
created.set(0);
try (pool) {
for (int i = 0; i < 10000; i++) {
pool.submit(() -> FORMAT.get().format(new Date(0)));
}
}
System.out.printf("%-34s formatters created: %,d%n", label, created.get());
}
public static void main(String[] args) {
run("fixed pool of 4 platform threads", Executors.newFixedThreadPool(4));
run("one virtual thread per task", Executors.newVirtualThreadPerTaskExecutor());
}
}
Output:
fixed pool of 4 platform threads formatters created: 4
one virtual thread per task formatters created: 10,000
The pool created 4 formatters, one per thread, and reused them for 10,000 tasks. The virtual threads created 10,000: the cache never hit. Each thread also kept its own entry in its ThreadLocalDateTimeFormatter
Limiting concurrency without a pool
A fixed thread pool used to do two jobs: provide threads and limit how many tasks hit a database at once. With virtual threads the first job disappears, but the second remains. The program runs 1,000 virtual threads against a pretend database that allows 10 connections, enforced with a Semaphore
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class LimitWithSemaphore {
static final Semaphore DB_PERMITS = new Semaphore(10); // the database allows 10
static final AtomicInteger inUse = new AtomicInteger();
static final AtomicInteger peak = new AtomicInteger();
static void query() throws InterruptedException {
DB_PERMITS.acquire(); // waits, cheaply, if all are taken
try {
peak.accumulateAndGet(inUse.incrementAndGet(), Math::max);
Thread.sleep(20);
} finally {
inUse.decrementAndGet();
DB_PERMITS.release();
}
}
public static void main(String[] args) {
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
query();
return null;
});
}
}
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("1,000 virtual threads, peak concurrent queries: " + peak.get());
System.out.println("took at least 100 x 20 ms = 2,000 ms: " + (ms >= 2000));
}
}
Output:
1,000 virtual threads, peak concurrent queries: 10
took at least 100 x 20 ms = 2,000 ms: true
Never more than 10 queries ran at once, and the run took at least 1,000 / 10 × 20 ms = 2,000 ms, which shows the limit really held. The other 990 threads waited in acquire()
Migration checklist
| Situation | What to do |
|---|---|
| Thread-per-request server code | Run each request on a virtual thread; frameworks such as Spring Boot, Helidon and Quarkus offer a setting for this |
| Fixed thread pools sized to limit load on a database | Keep the limit, but enforce it with a Semaphore |
ThreadLocal | Review them: with one thread per task, the cache is created for every task; consider |
synchronized | Switch to ReentrantLock |
| CPU-bound parallel work | Keep platform threads, parallel streams or ForkJoinPool |
For running groups of related virtual threads as one unit, see