Virtual Threads
Project Loom's lightweight threads in Java 21 — how they're scheduled on carrier threads, continuations and stack copying, pinning, when they help, structured concurrency, scoped values, and migration advice.
Virtual threads (final in Java 21) are threads implemented by the JVM rather than the operating system. They're so cheap — a few hundred bytes to start, created in microseconds — that you can run millions of them. Their purpose: let simple, blocking, thread-per-request code scale like asynchronous code, without callbacks or reactive frameworks.
The problem they solve
A server handling a request typically spends most of its time waiting: on a database, another service, a file. With platform threads (1:1 wrappers around OS threads, ~1 MB stack each, expensive context switches), you can afford a few thousand. If each request holds a thread for 100 ms of mostly waiting, throughput caps out at about threads / latency — 2,000 threads / 0.1 s = 20,000 req/s, regardless of how idle the CPU is (Little's law).
The traditional fix was asynchronous code — callbacks, CompletableFuture chains, reactive streams (WebFlux, RxJava) — which frees the thread while waiting but makes code harder to write, debug and profile (useless stack traces, "function colouring").
Virtual threads give you the scalability of async with the simplicity of blocking code.
How they work
- A virtual thread runs mounted on a carrier thread — an ordinary platform thread from a
ForkJoinPoolwith about as many threads as CPU cores. - When the virtual thread performs a blocking operation (socket read,
sleep,BlockingQueue.take, lock wait), the JDK unmounts it: its stack frames are saved to the heap as a continuation, and the carrier is free to run another virtual thread. - When the I/O is ready, the virtual thread is rescheduled and mounted again (possibly on a different carrier), its frames copied back, and it continues as if nothing happened.
- The JDK's networking,
java.util.concurrentand file APIs were rewritten to cooperate with this.
It's M:N scheduling (many virtual threads on few OS threads), like Go's goroutines — but compatible with the existing Thread API, ThreadLocal, debuggers and profilers.
Using them
// One virtual thread per task: the main idiom
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> results = urls.stream()
.map(url -> executor.submit(() -> httpGet(url))) // blocking call: fine!
.toList();
for (var f : results) System.out.println(f.get());
} // close() waits for all tasks
// Directly
Thread vt = Thread.ofVirtual().name("worker-", 0).start(() -> handle(request));
Thread.startVirtualThread(() -> work());
// Frameworks
// Spring Boot 3.2+: spring.threads.virtual.enabled=true
// Tomcat/Jetty/Helidon/Quarkus offer virtual-thread request handling// 10,000 concurrent sleeping tasks: trivial with virtual threads
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> ex.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
} // finishes in about 1 secondRules of thumb
| Do | Don't |
|---|---|
| Create a new virtual thread per task | Pool virtual threads — they're cheap; pooling defeats the purpose |
| Use them for I/O-bound, high-concurrency work | Expect speed-ups for CPU-bound work (still limited by cores) |
Limit access to scarce resources with a Semaphore | Rely on pool size to throttle (e.g. DB connections) |
Keep ThreadLocal use small | Cache expensive objects in ThreadLocals (a million copies) |
Structured concurrency
Unstructured concurrency (fire off futures and hope) leaks threads and loses errors. Structured concurrency (preview, StructuredTaskScope) treats a group of concurrent subtasks as one unit with a clear lifetime: they start in a scope and must finish before the scope exits; if one fails, the others are cancelled.
// Preview API (shape as of Java 25)
Response handle(String userId) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) { // default: fail if any subtask fails
Subtask<User> user = scope.fork(() -> findUser(userId));
Subtask<List<Order>> orders = scope.fork(() -> fetchOrders(userId));
scope.join(); // wait; cancels siblings on failure
return new Response(user.get(), orders.get());
}
}Benefits: no leaked threads, automatic cancellation, errors propagate, and thread dumps show the parent-child task tree.
Scoped values
ThreadLocal is mutable, inherited by copying, and lives as long as the thread — awkward with millions of short-lived threads. Scoped values (final in Java 25) are immutable, bound for a bounded scope, and efficiently shared with child tasks:
static final ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();
ScopedValue.where(CURRENT_USER, authenticatedUser).run(() -> {
handleRequest(); // anywhere below: CURRENT_USER.get()
}); // binding ends here automaticallyVirtual threads vs reactive vs async/await
| Virtual threads | Reactive (WebFlux, RxJava) | async/await (JS, C#, Kotlin coroutines) | |
|---|---|---|---|
| Code style | Plain blocking code | Operator chains | Sequential-looking with keywords |
| Stack traces / debugging | Normal | Poor | Decent |
| Function colouring | None | Everything returns Mono/Flux | async infects callers |
| Backpressure built in | No (use semaphores, bounded queues) | Yes | No |
| Ecosystem fit | Works with JDBC, existing libraries | Needs reactive drivers | Needs async libraries |
For most server applications, virtual threads now offer the best trade-off; reactive streams remain useful for streaming data with backpressure.
- Virtual threads are JVM-managed, cheap threads multiplexed onto a few carrier threads.
- Blocking unmounts the virtual thread (stack saved to the heap), freeing the carrier.
- Use one virtual thread per task; never pool them; throttle with semaphores.
- They help I/O-bound concurrency, not CPU-bound work.
- Watch for pinning (native calls; synchronized before Java 24).
- Structured concurrency and scoped values complete the model.
QHow do virtual threads differ from platform threads?medium
Platform threads map 1:1 to OS threads, have large fixed stacks and expensive creation and context switches, so you can only have thousands. Virtual threads are scheduled by the JVM onto a small pool of carrier threads; their stacks live on the heap and grow as needed; blocking operations unmount them instead of blocking an OS thread. You can have millions, which makes thread-per-request blocking code scale for I/O-bound workloads.
QWhen would virtual threads not help?medium
For CPU-bound work (throughput is bounded by cores), when code is pinned by native calls or (before Java 24) synchronized blocks around blocking I/O, or when the real bottleneck is a limited downstream resource such as a database connection pool — more threads just queue up there.