CompletableFuture and virtual threads
Senior Frequently asked 7 min
On this page
The question
How do you compose asynchronous calls in Java?
30-second answer
Build a chain of stages on CompletableFuture. supplyAsync starts the first call on a pool thread and returns a future at once. thenCompose chains a call that itself returns a future, thenApply maps a value, thenCombine or allOf joins independent calls, and exceptionally or handle deals with a failure once, at the end. Only join() or get() blocks, and only where the result is needed.
Understand it
Platform or virtual threads for blocking calls?
CompareA pool of 200 platform threads runs 10,000 one-second blocking calls. Each sleep holds an OS thread, so the tasks run in 50 waves: about 50 s.
View as text
The same job runs on two kinds of thread: 10,000 tasks, each blocking for 1 s. On the left, a grid of 50 cells stands for the tasks, 200 per cell. On the right, the threads and what a blocking call does to them. At the bottom, a wall-clock bar on an axis from 0 to 50 s.
Platform threads: A pool of 200 platform threads runs 10,000 one-second blocking calls. Each sleep holds an OS thread, so the tasks run in 50 waves: about 50 s. One cell is running and 49 are queued, with a badge reading 200 run, 9,800 wait. The thread box reads 200 threads, 1 OS thread each, and the sleep leads to blocks, OS thread held. The time bar fills all 50 one-second segments, with a badge reading 50 waves, about 50 s.
Virtual threads: Each of the 10,000 tasks gets its own virtual thread. A sleeping virtual thread unmounts and frees its carrier, so all 10,000 wait at once: about 1 s. All 50 cells are running, with a badge reading 10,000 run at once. The thread box reads carriers, 1 per core, and the sleep leads to unmounts, carrier freed. The time bar fills one segment, about 1 s, with a badge reading 1 wave, about 1 s.
The same job runs on two kinds of thread: 10,000 tasks, each blocking for 1 s. On the left, a grid of 50 cells stands for the tasks, 200 per cell. On the right, the threads and what a blocking call does to them. At the bottom, a wall-clock bar on an axis from 0 to 50 s.
Platform threads: A pool of 200 platform threads runs 10,000 one-second blocking calls. Each sleep holds an OS thread, so the tasks run in 50 waves: about 50 s. One cell is running and 49 are queued, with a badge reading 200 run, 9,800 wait. The thread box reads 200 threads, 1 OS thread each, and the sleep leads to blocks, OS thread held. The time bar fills all 50 one-second segments, with a badge reading 50 waves, about 50 s.
Virtual threads: Each of the 10,000 tasks gets its own virtual thread. A sleeping virtual thread unmounts and frees its carrier, so all 10,000 wait at once: about 1 s. All 50 cells are running, with a badge reading 10,000 run at once. The thread box reads carriers, 1 per core, and the sleep leads to unmounts, carrier freed. The time bar fills one segment, about 1 s, with a badge reading 1 wave, about 1 s.
Takeaway: A blocked platform thread holds an OS thread; a blocked virtual thread lets go of its carrier. For blocking calls, one virtual thread per task beats a fixed pool.
A CompletableFuture chain, stage by stage
Step by stepsupplyAsync runs findUser(42) on a pool thread and returns a future at once. The main thread holds it, not done yet, and goes on.
View as text
The chain is drawn as rows, one per stage: supplyAsync, thenCompose, thenApply and exceptionally, then count.join() on the main thread. A value box beside the rows moves down as each stage completes, and the main thread holds a future marked not done.
supplyAsync runs findUser(42) on a pool thread and returns a future at once. The main thread holds it, not done yet, and goes on. The value box beside supplyAsync reads User 42.
fetchOrders(user) returns its own future. thenCompose flattens it, so the next stage gets the 3 orders, not a future of a future as thenApply would give. The value box reads 3 orders inside a dashed future outline, marked unwrapped.
thenApply maps the value with a plain function: orders.size() turns the 3 orders into 3, still inside a future. The value box reads 3.
If fetchOrders fails instead, thenApply is skipped and the exception jumps to exceptionally, which turns it into the fallback 0. An exception box sits beside thenCompose, the thenApply row is faded and marked skipped, and a dashed arrow jumps to exceptionally, where the value box reads 0.
join() makes the main thread wait until the chain completes. Here it returns 3; after a failure without exceptionally, it would throw a CompletionException. The value box reaches the count.join() row and reads 3, done.
The chain is drawn as rows, one per stage: supplyAsync, thenCompose, thenApply and exceptionally, then count.join() on the main thread. A value box beside the rows moves down as each stage completes, and the main thread holds a future marked not done.
supplyAsync runs findUser(42) on a pool thread and returns a future at once. The main thread holds it, not done yet, and goes on. The value box beside supplyAsync reads User 42.
fetchOrders(user) returns its own future. thenCompose flattens it, so the next stage gets the 3 orders, not a future of a future as thenApply would give. The value box reads 3 orders inside a dashed future outline, marked unwrapped.
thenApply maps the value with a plain function: orders.size() turns the 3 orders into 3, still inside a future. The value box reads 3.
If fetchOrders fails instead, thenApply is skipped and the exception jumps to exceptionally, which turns it into the fallback 0. An exception box sits beside thenCompose, the thenApply row is faded and marked skipped, and a dashed arrow jumps to exceptionally, where the value box reads 0.
join() makes the main thread wait until the chain completes. Here it returns 3; after a failure without exceptionally, it would throw a CompletionException. The value box reaches the count.join() row and reads 3, done.
Takeaway: Each stage runs when the one before completes. thenCompose flattens a stage that returns a future, thenApply maps a value, and a failure skips ahead to exceptionally.
In code
CompletableFuture<Integer> count =
CompletableFuture.supplyAsync(() -> findUser(42)) // pool thread, returns at once
.thenCompose(user -> fetchOrders(user)) // fetchOrders returns a future
.thenApply(orders -> orders.size()) // plain value: 3
.exceptionally(ex -> 0); // any failure above: 0
CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> findUser(7));
CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> 5);
String both = user.thenCombine(stock, (u, s) -> u.id() + ":" + s).join(); // "7:5"
int n = count.join(); // the main thread waits here: 3try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1)); // the virtual thread unmounts here
return null;
});
}
} // close() waits for every task: about 1 s in all
// The same loop on Executors.newFixedThreadPool(200) runs in 50 waves: about 50 sCompletableFuture<Price> price = CompletableFuture.supplyAsync(() -> prices.get(id), pool);
CompletableFuture<Stock> stock = CompletableFuture.supplyAsync(() -> stocks.get(id), pool);
Page page = price.thenCombine(stock, Page::new) // waits for both, runs in parallel
.orTimeout(2, TimeUnit.SECONDS) // Java 9+: fail if either is late
.exceptionally(e -> Page.unavailable()) // one fallback for timeout or failure
.join();Solve it
Virtual threads made the service slower: find out why
A team switched a blocking REST (Representational State Transfer) service to Executors.newVirtualThreadPerTaskExecutor(). Under 10,000 concurrent
requests, latency got worse and the database logs “too many connections”. The pool has 10 connections. Explain and fix it.
- Find where threads wait. A thread dump (
jcmd <pid> Thread.dump_to_file threads.txt) shows thousands of virtual threads blocked on the connection pool, not on the CPU. - Name the real limit. Virtual threads remove the cost of a waiting thread, not the limits downstream. Ten connections still serve ten queries at a time.
- Limit concurrency explicitly. A
Semaphoresized to the pool lets the rest wait cheaply. Do not pool virtual threads to limit them; create one per task. - Rule out pinning. On Java 21 to 23, blocking inside
synchronizedpins the carrier thread. Thejdk.VirtualThreadPinnedevent of JFR (Java Flight Recorder) finds it; Java 24 removed this case. - Check. Under the same load, connections stay at 10 and latency is steady.
private final Semaphore dbPermits = new Semaphore(10); // matches the connection pool size
Order load(long id) throws InterruptedException {
dbPermits.acquire(); // a virtual thread waits here cheaply
try {
return repository.findById(id);
} finally {
dbPermits.release();
}
}
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
ids.forEach(id -> executor.submit(() -> load(id)));
} // close() waits for every taskHow to answer
- Without an executor argument,
supplyAsyncruns onForkJoinPool.commonPool(); pass your own executor for blocking calls. thenComposetakes a function that returns aCompletableFuture;thenApplywould nest it asCompletableFuture<CompletableFuture<T>>.thenCombinemerges the results of two independent futures once both complete;allOfwaits for any number of them.- A failed stage skips every later
thenApplyandthenComposeuntil a stage that handles it, such asexceptionallyorhandle. join()throws an uncheckedCompletionExceptionandget()a checkedExecutionException; both carry the original exception as the cause.
Common mistakes
- Calling
join()after every stage, which turns the chain back into blocking code. - Expecting
exceptionallyto receive the original exception; a failure from an earlier stage arrives wrapped in aCompletionException, so readgetCause(). - Running blocking I/O on the common pool, which is sized to the CPU cores and shared by the whole JVM (Java Virtual Machine).
Follow-up questions
What are virtual threads in Java 21, and when do they help?
A virtual thread is a Thread scheduled by Java, not the OS, and final in Java 21. When it blocks on a socket, a java.util.concurrent lock or sleep, the JVM unmounts it from its carrier platform thread, which then runs another virtual thread. So one thread per request scales to thousands of blocking calls: 10,000 one-second sleeps took about 1 s, against about 50 s on a thread pool of 200.
- Create them with
Executors.newVirtualThreadPerTaskExecutor(),Thread.ofVirtual().start(task)orThread.startVirtualThread(task);isVirtual()returnstrue. - By default the carriers come from a
ForkJoinPoolwith one thread per core, and a resumed virtual thread can continue on another carrier. - They help when tasks spend their time waiting on HTTP calls or database queries, not when they compute.
- Code stays in plain blocking style, with readable stack traces, instead of a chain of callbacks.
See it in the infographic: Platform or virtual threads for blocking calls?
What is the difference between thenApply and thenCompose?
Both run after the future completes and pass its value to a function. thenApply is for a function that returns a plain value, like map on a stream. thenCompose is for a function that returns another CompletableFuture, like flatMap: it waits for that inner future and gives you a flat CompletableFuture<T>. Pass fetchOrders to thenApply and you get a CompletableFuture<CompletableFuture<List<Order>>>.
- Assigning
thenApply(user -> fetchOrders(user))to aCompletableFuture<List<Order>>is a compile error about incompatible bounds. thenCombineis the third option: it merges two futures that do not depend on each other.- The
Asyncvariants, such asthenApplyAsync, run the function on an executor, by default the common pool.
CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> findUser(42));
CompletableFuture<List<Order>> orders = user.thenCompose(u -> fetchOrders(u));
CompletableFuture<CompletableFuture<List<Order>>> nested = user.thenApply(u -> fetchOrders(u));
CompletableFuture<Integer> count = orders.thenApply(List::size); See it in the infographic: A CompletableFuture chain, stage by stage
When do virtual threads not help, and what can pin one to its carrier thread?
When the work computes instead of waiting: 64 CPU-bound tasks took about as long on virtual threads as on a pool sized to the cores. When something else is the limit, such as 10 database connections. And in Java 21 when a virtual thread blocks inside synchronized or a native method: it pins its carrier, which then runs nothing else. Java 24 removed nearly all synchronized pinning (JEP 491).
- In Java 21, replace
synchronizedaround a blocking call with aReentrantLock, which lets the virtual thread unmount. - Since Java 24, native frames and class initialization still pin (JEP 491, a Java Development Kit Enhancement Proposal).
- Cap access to a scarce resource with a
Semaphore, not with a smaller thread pool. - Avoid caching expensive objects in a
ThreadLocal; with one virtual thread per task, each task builds its own copy.
See it in the infographic: Platform or virtual threads for blocking calls?
How do you handle errors in a CompletableFuture chain?
A failure skips the remaining thenApply and thenCompose stages and completes the chain exceptionally. exceptionally(ex -> fallback) recovers with a value, handle((value, ex) -> ...) sees either the value or the exception, and whenComplete observes the outcome without changing it. Put one handler near the end, unwrap a CompletionException with getCause(), and remember that an unhandled failure throws from join().
Should virtual threads be pooled?
No. A virtual thread is cheap to create and meant for one task, so create one per task with Executors.newVirtualThreadPerTaskExecutor(). A pool exists to reuse expensive threads and to cap concurrency. For virtual threads, cap the scarce resource instead, for example a Semaphore with 10 permits around the database call. Pooling them brings back the limit they remove.
Check yourself
Show answers
- thenCompose(user -> fetchOrders(user)): Correct. thenCompose waits for the future the function returns and flattens it into one future.
- thenApply(user -> fetchOrders(user)): Incorrect. thenApply wraps whatever the function returns, giving a future of a future.
- thenAccept(user -> fetchOrders(user)): Incorrect. thenAccept discards the function's result and gives a CompletableFuture<Void>.
Show answers
- About 1 s: Correct. Each sleeping virtual thread unmounts and frees its carrier, so all 10,000 tasks wait at the same time.
- About 50 s: Incorrect. Only the fixed pool limits the job to 200 tasks at a time; here every task has its own thread.
- Longer than 50 s: Incorrect. Creating 10,000 virtual threads is cheap, far below the cost of 50 waves of sleeping.