Scale Concurrent Applications with Java Virtual Threads
Scale Java applications with virtual threads from Project Loom: Thread.ofVirtual, per-task executor, structured concurrency on JDK 25, and scoped values.
Overview
Virtual threads are lightweight threads managed by the JVM instead of the OS. They arrived as a preview in JDK 19, went final in JDK 21 (JEP 444), and let you write plain blocking code that scales to millions of concurrent tasks. The catch used to be everything around them: structured concurrency and scoped values stayed in preview for years, and the synchronized pinning problem scared people off. This recipe is current through JDK 25, the latest LTS: it covers Thread.ofVirtual(), the per-task executor, StructuredTaskScope with the new open() + Joiner API, ScopedValue (now final), and pinning advice that respects what JEP 491 actually changed in JDK 24.
When to Use This
- Server apps that handle many concurrent requests, where each request spends most of its time waiting on I/O (databases, HTTP calls, queues)
- Replacing reactive or callback-heavy code with straightforward blocking code you can actually read
- Apps that hit the ceiling of a platform thread pool before they hit the CPU
- Fan-out work like “call five services, combine the answers” where structured concurrency keeps lifetimes tidy
Virtual threads won’t speed up CPU-bound work: a virtual thread doing math still occupies a carrier thread, same as a platform thread. They don’t remove downstream limits either: if your connection pool has 10 slots, opening 10,000 virtual threads just moves the bottleneck from threads to the pool, so you still need to bound concurrency with a Semaphore or size the pool correctly.
Prerequisites
- JDK 21+ — virtual threads are final since JDK 21 (JEP 444)
- JDK 25 to compile the structured-concurrency examples as written.
StructuredTaskScopeis still a preview API (JEP 505), so it needs--enable-preview. On JDK 21–24 the same feature exists under a different API — see the variant below. - JDK 24+ for the pinning fix:
synchronizedno longer pins virtual threads (JEP 491) ScopedValueis final in JDK 25; on JDK 21–24 it’s preview and also needs--enable-preview
Solution
1. Basic Virtual Thread
public class BasicVirtualThread {
public static void main(String[] args) throws InterruptedException {
// Create and start a virtual thread — no executor needed
Thread vt = Thread.ofVirtual().name("my-virtual-thread").start(() -> {
System.out.println("Running in: " + Thread.currentThread());
System.out.println("Is virtual: " + Thread.currentThread().isVirtual());
});
vt.join();
System.out.println("Virtual thread completed");
}
}
2. Virtual Thread per Task Executor
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class VirtualThreadExecutor {
public static void main(String[] args) throws InterruptedException {
// One virtual thread per task — don't pool them
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return i * 2;
});
});
// try-with-resources blocks until every task finishes
}
System.out.println("All 10,000 virtual threads completed");
}
}
3. Blocking I/O with Virtual Threads
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.ArrayList;
public class VirtualThreadIO {
private static final HttpClient client = HttpClient.newHttpClient();
public static String fetch(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
}
public static void main(String[] args) throws Exception {
List<String> urls = List.of(
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/3",
"https://httpbin.org/delay/1"
);
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<java.util.concurrent.Future<String>> futures = new ArrayList<>();
for (String url : urls) {
futures.add(executor.submit(() -> fetch(url)));
}
// Each fetch runs on its own virtual thread
// Total ~3s (max delay), not 8s (sum of delays)
long start = System.currentTimeMillis();
for (java.util.concurrent.Future<String> f : futures) {
System.out.println("Fetched " + f.get().length() + " bytes");
}
System.out.println("Total time: " + (System.currentTimeMillis() - start) + "ms");
}
}
}
4. Structured Concurrency with StructuredTaskScope (JDK 25)
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class StructuredConcurrency {
record User(String name, String email) {}
record Order(String id, double total) {}
record UserOrder(User user, Order order) {}
static User fetchUser(String userId) throws InterruptedException {
Thread.sleep(100);
return new User("Alice", "alice@example.com");
}
static Order fetchOrder(String orderId) throws InterruptedException {
Thread.sleep(150);
return new Order("ord-123", 99.99);
}
public static void main(String[] args) throws Exception {
// open() gives the default policy: wait for all subtasks,
// cancel everything and throw if any one fails.
try (var scope = StructuredTaskScope.open()) {
Subtask<User> userTask = scope.fork(() -> fetchUser("u1"));
Subtask<Order> orderTask = scope.fork(() -> fetchOrder("o1"));
scope.join(); // waits for all; throws FailedException on failure
UserOrder result = new UserOrder(userTask.get(), orderTask.get());
System.out.println("Result: " + result);
} catch (StructuredTaskScope.FailedException e) {
System.err.println("A subtask failed: " + e.getCause());
}
}
}
5. First Result Wins with a Joiner
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
public class FirstResultPattern {
static String fetchFromReplica(String replicaUrl) throws InterruptedException {
Thread.sleep((long) (Math.random() * 500));
return "Data from " + replicaUrl;
}
public static void main(String[] args) throws Exception {
// anySuccessfulResultOrThrow: first success wins, the rest are cancelled
var joiner = Joiner.<String>anySuccessfulResultOrThrow();
try (var scope = StructuredTaskScope.open(joiner)) {
scope.fork(() -> fetchFromReplica("replica-1"));
scope.fork(() -> fetchFromReplica("replica-2"));
scope.fork(() -> fetchFromReplica("replica-3"));
// join() returns the first successful result directly
String result = scope.join();
System.out.println("First response: " + result);
}
}
}
6. Scoped Values Instead of ThreadLocal
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ScopedValueExample {
// ScopedValue lives in java.lang — no import needed. Final in JDK 25.
static final ScopedValue<String> USER_ID = ScopedValue.newInstance();
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static void handleRequest() {
System.out.println("User: " + USER_ID.get() + ", Request: " + REQUEST_ID.get());
// Virtual threads inherit scoped value bindings
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
System.out.println("In child thread — User: " + USER_ID.get()
+ ", Request: " + REQUEST_ID.get());
}).get();
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
// Bind values for the duration of the call — they can't be reassigned
ScopedValue.where(USER_ID, "user-42")
.where(REQUEST_ID, "req-abc-123")
.run(() -> handleRequest());
}
}
7. Mixing Platform and Virtual Threads
import java.util.concurrent.*;
public class MixedThreads {
static void cpuIntensiveTask(int id) {
long result = 0;
for (long i = 0; i < 100_000_000L; i++) {
result += i;
}
System.out.println("CPU task " + id + " result: " + result);
}
static void ioTask(int id) throws InterruptedException {
Thread.sleep(500);
System.out.println("IO task " + id + " done");
}
public static void main(String[] args) throws InterruptedException {
// CPU-bound work stays on a fixed platform pool
try (ExecutorService cpuPool = Executors.newFixedThreadPool(4);
// I/O-bound work gets a virtual thread per task
ExecutorService ioPool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 4; i++) {
final int id = i;
cpuPool.submit(() -> cpuIntensiveTask(id));
ioPool.submit(() -> ioTask(id));
}
cpuPool.shutdown();
ioPool.shutdown();
cpuPool.awaitTermination(10, TimeUnit.SECONDS);
ioPool.awaitTermination(10, TimeUnit.SECONDS);
}
System.out.println("All tasks completed");
}
}
8. Locking: synchronized vs ReentrantLock (JDK 24+)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class LockingExample {
private static final ReentrantLock lock = new ReentrantLock();
private static int counter = 0;
public static void main(String[] args) throws InterruptedException {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
});
}
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
System.out.println("Counter: " + counter);
}
}
Two honest notes on pinning. On JDK 24 and later, synchronized blocks do not pin virtual threads anymore. JEP 491 reworked the monitor implementation so a virtual thread blocked inside synchronized can still unmount from its carrier. On JDK 21–23 it did pin, which is where the old “always use ReentrantLock” advice comes from. Today ReentrantLock is still worth reaching for when you need what it adds (tryLock, fairness, conditions, lockInterruptibly), not because synchronized is forbidden. What still pins on every version: calls into native methods and foreign functions (FFM API).
How It Works
A virtual thread is a java.lang.Thread whose stack lives on the heap as a continuation object, not on a fixed ~1MB OS stack. The JVM time-shares a huge number of virtual threads over a small pool of carrier threads (ordinary platform threads in a ForkJoinPool, one per CPU core by default). When a virtual thread hits a blocking operation the JDK knows about (socket I/O, Thread.sleep, most java.util.concurrent blocking), the JVM parks its continuation and frees the carrier to run another virtual thread. When the I/O completes, the continuation gets scheduled back onto a carrier, not necessarily the same one.
That’s the whole trick: your code blocks, but the carrier underneath doesn’t. A server that capped out at ~200 concurrent requests on a 200-thread pool can now run one virtual thread per request with no pooling logic at all.
| Platform thread | Virtual thread | |
|---|---|---|
| Stack | ~1MB committed up front | a few hundred bytes, grows in heap |
| Scheduled by | OS scheduler | JVM onto carrier threads |
| Realistic count | thousands | millions |
| Cost to create | expensive, worth pooling | cheap, one per task |
| Best for | CPU-bound work | I/O-bound blocking work |
A few things worth knowing before you bet production on it:
StructuredTaskScopeis still preview. In JDK 25 you open a scope withStructuredTaskScope.open()and pick a policy throughJoiner: the default waits for all and propagates failure,allSuccessfulOrThrow()hands you aStream<Subtask<T>>of results, andanySuccessfulResultOrThrow()gives you the first success and cancels the rest.join()throwsFailedException(aRuntimeExceptionwrapping the first cause), so callers see one failure, not N.ScopedValueis final in JDK 25 (JEP 506), and it does whatThreadLocaldoes but with a bounded lifetime: the binding exists only inside therun()/call()where you set it, and child threads forked inside the scope inherit it automatically. With millions of threads,ThreadLocal’s mutable, unbounded map is a real memory leak risk;ScopedValuesidesteps it.- Pinning is mostly solved.
synchronizedpinned on JDK 21–23; JEP 491 removed that in JDK 24. What still pins on every version is calls into native methods and foreign functions (FFM API). And a virtual thread that never blocks never yields, which is fine, because that’s just a CPU-bound task. - The bottleneck moves. Virtual threads make thread count cheap, but the database still has 10 connections and the downstream API still rate-limits you. Bound fan-out with a
Semaphore, size connection pools deliberately, and keep rate limits explicit. CompletableFuturestill has a place. If you need to compose stages, race calls, or attach timeouts declaratively, composing async pipelines with CompletableFuture is the better tool. Virtual threads win when blocking code is simply clearer.
Variants
Custom Thread Builder
Thread.Builder builder = Thread.ofVirtual()
.name("worker-", 0) // prefix + auto-increment
.uncaughtExceptionHandler((t, e) -> {
System.err.println("Uncaught in " + t.getName() + ": " + e);
});
Thread t = builder.start(() -> {
System.out.println("Running in " + Thread.currentThread().getName());
});
t.join();
Thread.ofPlatform() gives you the same builder API for platform threads, so naming and exception handling stay consistent across both kinds.
Semaphore for Bounded Concurrency
import java.util.concurrent.*;
public class BoundedVirtualThreads {
public static void main(String[] args) throws InterruptedException {
// Downstream rate limit: max 10 in-flight calls
Semaphore semaphore = new Semaphore(10);
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100; i++) {
final int id = i;
executor.submit(() -> {
semaphore.acquire();
try {
Thread.sleep(100);
System.out.println("Task " + id + " done");
} finally {
semaphore.release();
}
});
}
}
}
}
StructuredTaskScope on JDK 21–24
If you’re stuck on JDK 21–24, the same pattern uses the old constructor-based API, which is preview there too:
// JDK 21–24 API — constructors + throwIfFailed(), removed in JDK 25
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var userTask = scope.fork(() -> fetchUser("u1"));
var orderTask = scope.fork(() -> fetchOrder("o1"));
scope.join();
scope.throwIfFailed(); // rethrow the first failure
var result = new UserOrder(userTask.get(), orderTask.get());
}
Nested Scopes
// A child scope failure cancels the child — not the outer scope
try (var outer = StructuredTaskScope.open()) {
var dataTask = outer.fork(() -> fetchData());
try (var inner = StructuredTaskScope.open()) {
var enrichTask = inner.fork(() -> enrichData());
inner.join();
}
outer.join();
System.out.println("All done: " + dataTask.get());
}
Spring Boot
Spring Boot 3.2+ flips Tomcat to a virtual-thread executor with one property:
spring.threads.virtual.enabled=true
With that on, every incoming request runs on its own virtual thread, no code changes needed. Your servlet code, @Transactional boundaries, and blocking repository calls all keep working; they just stop fighting over a fixed request pool.
Verify the Setup Actually Works
Run one of the examples end to end. The structured-concurrency classes need the preview flag on JDK 25:
javac --release 25 --enable-preview StructuredConcurrency.java
java --enable-preview StructuredConcurrency
# Result: UserOrder[user=User[name=Alice, ...], order=Order[...]]
# Plain virtual threads need no flags on JDK 21+
javac VirtualThreadExecutor.java && java VirtualThreadExecutor
# All 10,000 virtual threads completed
To prove the threads are really virtual while an app is running, dump them:
jcmd <pid> Thread.dump_to_file -format=json threads.json
Every virtual thread in the JSON comes back with "virtual": true and is grouped under its StructuredTaskScope when one owns it, a handy way to spot threads that escaped a scope boundary.
Best Practices
- One virtual thread per task, never pooled. They’re cheap to create and throw away; pooling them adds contention for zero benefit.
- Use
newVirtualThreadPerTaskExecutor()in try-with-resources. On JDK 19+ the close waits for all tasks, so you get structured lifetimes for free. - Keep CPU-bound work on platform threads. A fixed pool sized to your cores is the right tool; virtual threads add nothing there.
- Bound downstream calls explicitly. A
Semaphoreor a correctly sized connection pool prevents your new scalability from DDoSing your own database. - Reach for
StructuredTaskScopefor related subtasks. It guarantees subtasks are awaited and cancelled together, so no thread leaks outliving the request. - Prefer
ScopedValueoverThreadLocal. Immutable, bounded lifetime, inherited by forked children, and it doesn’t leak with millions of threads.
Common Mistakes
- Repeating the JDK 21 pinning advice as if it’s still current. “Never use
synchronized” was right in 2023. Since JDK 24 (JEP 491)synchronizedno longer pins. Update the rule to “native and foreign calls still pin” instead of cargo-cultingReentrantLockeverywhere. - Assuming virtual threads make CPU work faster. They don’t; a busy virtual thread holds a carrier just like a platform thread does. The wins come from blocked I/O, not parallelism.
- Unbounded fan-out. Creating 10,000 virtual threads that all hammer one database doesn’t scale the database; it queues 10,000 waiters on 10 connections.
- Letting
ThreadLocalsurvive into virtual-thread code. Mutable, never-cleaned thread-locals across millions of threads are a memory leak. Migrate request-scoped state toScopedValue. - Forgetting
--enable-preview.StructuredTaskScope(JDK 25, JEP 505) andScopedValueon JDK 21–24 need the flag at compile and run time. Virtual threads themselves don’t. - Catching
InterruptedExceptionand swallowing it. Virtual threads get interrupted when a scope cancels them. Restore the flag withThread.currentThread().interrupt()so the cancellation actually propagates.
See Also
Frequently Asked Questions
What's the difference between virtual threads and platform threads?
Platform threads are thin wrappers over OS threads, about 1MB of committed stack each and scheduled by the OS. Virtual threads are JVM objects: a few hundred bytes of heap, scheduled onto a small pool of carrier threads. When a virtual thread blocks on I/O it unmounts and frees the carrier; a platform thread just sits there holding it. Roughly: thousands of platform threads max, millions of virtual threads feasible.
Do virtual threads work with Spring Boot?
Yes. Spring Boot 3.2+ supports them with spring.threads.virtual.enabled=true in application.properties. Tomcat then handles each request on a virtual thread, and your existing blocking controller/service/repository code works unchanged.
Do virtual threads replace CompletableFuture?
Not entirely. Virtual threads make blocking-style code scale, which removes the need for async plumbing in the common case. CompletableFuture is still the better tool when you genuinely need stage composition, racing, or declarative timeouts — see composing async pipelines with CompletableFuture for that side of the trade-off.
Does synchronized still pin virtual threads?
Not since JDK 24. JEP 491 changed the monitor implementation so a virtual thread can unmount from its carrier even while holding a synchronized monitor. On JDK 21–23 it pinned, so the old advice to always prefer ReentrantLock was correct then. What still pins today: native methods and foreign function calls. Keep ReentrantLock for its extra API (tryLock, fairness), not for pinning.
Is StructuredTaskScope stable yet?
No — it's a preview API in JDK 25 (fifth preview, JEP 505), and the API moved a lot: scopes now open via StructuredTaskScope.open() with a Joiner policy instead of new ShutdownOnFailure()/new ShutdownOnSuccess() constructors. You need --enable-preview to compile and run it, while ScopedValue did finalize in JDK 25 (JEP 506).
How many virtual threads can I create?
Practically, millions; the limit is heap. Each one costs a few hundred bytes of initial state plus whatever its stack grows to, so a million idle virtual threads land in the few-hundred-MB range. The real ceiling is usually your downstream resources (connections, rate limits) long before the JVM struggles.
Related Resources
Compose Asynchronous Pipelines with Java CompletableFuture
Build non-blocking async pipelines in Java using CompletableFuture with thenCompose, thenCombine, allOf, anyOf, exception handling, timeouts, and custom thread pools.
RecipeConcurrent Patterns with Go Goroutines and Channels
Build concurrent systems in Go using goroutines, channels, select statements, worker pools, fan-out/fan-in, pipelines, context cancellation, and rate limiting with tickers.
GuideConcurrency Patterns Guide
Production-ready concurrency patterns: thread pools, async/await, producer-consumer, semaphores, actors, circuit breakers in Python, Java, JS, Go, Elixir.
RecipeBuild Async Pipelines with C# async/await and Task.Run
Build async pipelines in C# using async/await, Task.Run, Task.WhenAll, Task.WhenAny, CancellationTokenSource, Channels, and Parallel.ForEachAsync for concurrent I/O and CPU work.
RecipeBuild Async Systems with Rust Tokio Runtime
Build async systems in Rust using the Tokio runtime with tasks, channels, select, synchronization primitives, graceful shutdown, and structured concurrency patterns.