Virtual threads (Java 21)
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A busy web server handles thousands of requests, and each one mostly waits for a database or network. Normal threads are heavy, so only a few thousand fit. Java 21 offers a way out.
Platform threads versus virtual threads
A virtual thread is a very lightweight thread managed by the JVM, not the operating system, so a program can run thousands of blocking tasks cheaply.
Every thread so far was a platform thread: a thin wrapper around an operating system thread, with a big fixed stack. They are expensive, so we share a few of them through pools.
Example 1 · A platform thread and a virtual thread side by side
// Java 21public class PlatformVersusVirtualDemo { static void describe() { Thread t = Thread.currentThread(); System.out.println(t.getName() + ": virtual=" + t.isVirtual() + ", daemon=" + t.isDaemon()); }
public static void main(String[] args) throws InterruptedException { Thread platform = Thread.ofPlatform().name("counter-1").start(PlatformVersusVirtualDemo::describe); platform.join();
Thread virtual = Thread.ofVirtual().name("ticket-1").start(PlatformVersusVirtualDemo::describe); virtual.join();
Thread unnamed = Thread.startVirtualThread(() -> {}); unnamed.join(); System.out.println("Unnamed virtual thread name: \"" + unnamed.getName() + "\""); }}counter-1: virtual=false, daemon=false ticket-1: virtual=true, daemon=true Unnamed virtual thread name: ""
What this code does
- Both threads are started with the same builder style (
Thread.ofPlatform()andThread.ofVirtual()), andjoin()works the same way for both. - The virtual thread reports
isVirtual()astrueand is always a daemon. A virtual thread started without a name has an empty name, so name the ones you want to see in logs.
A virtual thread is a Java object. The JVM runs many virtual threads on a small set of platform threads called carrier threads, by default about one per core. When a virtual thread blocks, for example in Thread.sleep, a network read or BlockingQueue.take, the JVM unmounts it: it saves its stack to the heap and frees the carrier to run another virtual thread. When the wait is over, the virtual thread is mounted again, maybe on a different carrier. Creating a virtual thread costs about as much as creating a small object, so you can have one for every task, even a million of them. Virtual threads are always daemon threads, and they have no name unless you give them one.
Thread.ofVirtual() and newVirtualThreadPerTaskExecutor()
Thread.ofVirtual() returns a builder for virtual threads: Thread.ofVirtual().name("seat-", 1).start(task) starts one named seat-1, and the next one built from the same builder is seat-2. Thread.startVirtualThread(task) is the short form without a name.
Example 2 · Named virtual threads from one builder
// Java 21import java.util.ArrayList;import java.util.List;
public class VirtualBuilderDemo { public static void main(String[] args) throws InterruptedException { List<String> booked = new ArrayList<>(); Thread.Builder builder = Thread.ofVirtual().name("seat-", 1); // seat-1, seat-2, ...
List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 3; i++) { threads.add(builder.start(() -> { synchronized (booked) { booked.add(Thread.currentThread().getName() + " booked"); } })); } for (Thread t : threads) { t.join(); } booked.sort(null); booked.forEach(System.out::println); }}seat-1 booked seat-2 booked seat-3 booked
What this code does
name("seat-", 1)gives each thread from this builder the prefix plus a counter that starts at 1, so the names are predictable.- The three threads run at the same time, so the list is sorted before printing to give a fixed order. The short
synchronizedblock does not block inside, so it causes no pinning problem.
Example 3 · 2,000 blocking tasks: fixed pool versus virtual threads
// Java 21import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class VirtualThroughputDemo { static int checkPnr(int pnr) throws InterruptedException { Thread.sleep(100); // waiting for the railway server return 1; }
static void run(String label, ExecutorService pool) throws Exception { List<Callable<Integer>> tasks = new ArrayList<>(); for (int i = 0; i < 2000; i++) { int pnr = i; tasks.add(() -> checkPnr(pnr)); } long start = System.nanoTime(); int done = 0; try (pool) { for (Future<Integer> f : pool.invokeAll(tasks)) { done += f.get(); } } long ms = (System.nanoTime() - start) / 1_000_000; System.out.printf("%-22s %d PNRs checked in %5d ms%n", label, done, ms); }
public static void main(String[] args) throws Exception { run("Fixed pool of 100:", Executors.newFixedThreadPool(100)); run("Virtual per task:", Executors.newVirtualThreadPerTaskExecutor()); }}Fixed pool of 100: 2000 PNRs checked in 2670 ms Virtual per task: 2000 PNRs checked in 153 ms
What this code does
- Each task waits 100 ms. The fixed pool runs 100 at a time, so 2,000 tasks need 20 rounds, a little over 2 seconds. The virtual executor gives every task its own thread, so all 2,000 wait at once and finish in little more than 100 ms. Your times will differ.
- The code is the same blocking style as before:
sleep,invokeAll,get(). Only the executor changed.try (pool)closes each executor at the end of the block, which waits for its tasks.
Executors.newVirtualThreadPerTaskExecutor() is an ExecutorService that starts a new virtual thread for every task. It has no pool and no queue. Use it with try-with-resources, and submit, invokeAll, Future and get() work as before. Do not put virtual threads in a pool: pools exist to reuse expensive threads, and virtual threads are cheap. If you need to limit how many tasks use a slow service at once, limit the access instead (the Synchronizers module shows Semaphore for this).
When they help (blocking I/O) and when they do not (CPU work)
Virtual threads do not make code run faster. They let more tasks wait at the same time without tying up a platform thread each.
Example 4 · CPU-bound work gains nothing
// Java 21import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.function.Supplier;
public class VirtualCpuDemo { static int countPrimes(int from, int to) { int count = 0; for (int n = Math.max(2, from); n < to; n++) { boolean prime = true; for (int d = 2; (long) d * d <= n; d++) { if (n % d == 0) { prime = false; break; } } if (prime) { count++; } } return count; }
static long timeOnce(ExecutorService pool) throws Exception { List<Callable<Integer>> tasks = new ArrayList<>(); for (int i = 0; i < 48; i++) { int from = i * 50_000; tasks.add(() -> countPrimes(from, from + 50_000)); } long start = System.nanoTime(); try (pool) { for (Future<Integer> f : pool.invokeAll(tasks)) { f.get(); } } return (System.nanoTime() - start) / 1_000_000; }
static void bestOfThree(String label, Supplier<ExecutorService> newPool) throws Exception { long best = Long.MAX_VALUE; for (int run = 0; run < 3; run++) { best = Math.min(best, timeOnce(newPool.get())); } System.out.printf("%-20s best of 3 runs: %4d ms%n", label, best); }
public static void main(String[] args) throws Exception { int cores = Runtime.getRuntime().availableProcessors(); timeOnce(Executors.newFixedThreadPool(cores)); // warm-up for the JIT compiler bestOfThree("Fixed pool of " + cores + ":", () -> Executors.newFixedThreadPool(cores)); bestOfThree("Virtual per task:", Executors::newVirtualThreadPerTaskExecutor); }}Fixed pool of 12: best of 3 runs: 117 ms Virtual per task: best of 3 runs: 121 ms
What this code does
- Counting primes never blocks, so a virtual thread never gives up its carrier until it is done. With about one carrier per core, the virtual executor does the same work as a fixed pool sized to the cores, in about the same time.
- Timings of short runs are noisy, so the program warms up first and keeps the best of three runs for each executor. On your machine the numbers will differ, but the two lines stay close to each other.
That raises throughput, the number of tasks finished per second, when tasks spend most of their time blocked: web requests, database queries, calls to a UPI gateway or a railway API.
For CPU-bound work they give no benefit. The real work still runs on the carriers, about one per core. So a CPU-heavy job on virtual threads is no faster than on a fixed pool sized to the cores. They also do not remove other limits. If 10,000 virtual threads call a database that allows 50 connections, 9,950 of them wait for a connection.
Pinning on Java 21
Pinning is when a virtual thread cannot step off its carrier while it blocks, so the carrier stays busy and cannot run other virtual threads.
A virtual thread is pinned when it cannot be unmounted from its carrier while it blocks. On Java 21 this happens when it blocks inside a synchronized block or method, or inside native code.
// Pinned on Java 21: sleeping (or doing I/O) while holding a monitorsynchronized (ledger) { Thread.sleep(100);}
// Not pinned: a ReentrantLock lets the virtual thread unmount while it waitslock.lock();try { Thread.sleep(100);} finally { lock.unlock();}Example 5 · Pinning on Java 21, measured
import java.util.ArrayList;import java.util.List;import java.util.concurrent.locks.ReentrantLock;
public class PinningDemo { static long run(boolean useSynchronized) throws InterruptedException { long start = System.nanoTime(); List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 8; i++) { Object monitor = new Object(); ReentrantLock lock = new ReentrantLock(); threads.add(Thread.ofVirtual().start(() -> { try { if (useSynchronized) { synchronized (monitor) { Thread.sleep(100); // blocks while pinned on Java 21 } } else { lock.lock(); try { Thread.sleep(100); // unmounts while waiting } finally { lock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } })); } for (Thread t : threads) { t.join(); } return (System.nanoTime() - start) / 1_000_000; }
public static void main(String[] args) throws InterruptedException { // Use only 2 carrier threads; must be set before the first virtual thread starts. System.setProperty("jdk.virtualThreadScheduler.parallelism", "2"); System.out.println("Java " + Runtime.version().feature()); System.out.println("synchronized: 8 sleeps took " + run(true) + " ms"); System.out.println("ReentrantLock: 8 sleeps took " + run(false) + " ms"); }}Java 21 synchronized: 8 sleeps took 473 ms ReentrantLock: 8 sleeps took 154 ms
What this code does
- The program limits the JVM to 2 carriers. With
synchronized, each sleeping virtual thread stays pinned to its carrier, so only 2 sleeps happen at a time: 4 rounds of 100 ms. WithReentrantLock, all 8 unmount and sleep together: one round. - Each thread uses its own lock, so this is not lock contention: the slowdown comes only from pinning. On Java 24 or later both lines show about 100 ms, because
synchronizedno longer pins.
A pinned thread keeps its carrier busy for the whole wait, so with only a few carriers, a handful of pinned threads can stall thousands of others.
On Java 21 the usual fix is to protect blocking code with a ReentrantLock instead of synchronized, as below. Short synchronized blocks that never block are fine. Java 24 removed this kind of pinning for synchronized, so on newer releases it matters much less.
-Djdk.tracePinnedThreads=full to print a stack trace whenever a virtual thread blocks while pinned.Structured concurrency, a preview feature
Structured concurrency treats a group of related subtasks as one unit of work: they start together, the code waits for all of them in one place, and if one fails, the others are cancelled. It pairs naturally with virtual threads, one per subtask.
// Java 21 preview: javac --release 21 --enable-preview, java --enable-previewtry (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Subtask<String> user = scope.fork(() -> findUser(id)); // each fork runs in Subtask<Integer> fees = scope.fork(() -> pendingFees(id)); // its own virtual thread scope.join().throwIfFailed(); // wait for both; rethrow the first failure System.out.println(user.get() + " owes Rs " + fees.get());}In Java 21 it is a preview feature: an API that is complete but may still change. It works only when you compile and run with --enable-preview, and its API has changed in later releases, so treat the snippet below as Java 21 only.
Next step
Check your understanding
12 quick questions