Skip to main content

CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win)

Why a CompletableFuture chain can be twice as slow, swallow an error, or time out while the work keeps running. thenApply vs thenCompose, which thread runs your stage, exception wrapping, allOf, and where virtual threads win, all measured on JDK 25.

You chained a few CompletableFuture calls, it compiled, and it returned the right answer. Then one of three things happened: it was twice as slow as it should have been, an error vanished instead of appearing in a log, or a “timeout” fired while the work carried on running in the background. Each of those is documented behaviour that surprises almost everyone the first time. This post starts from the one idea underneath — a future is a box that gets filled once — and walks outward to the places where the box behaves unexpectedly: thenApply vs thenCompose, which thread runs your code, what happens when a stage throws, what a timeout does and does not stop, what allOf waits for, and where virtual threads genuinely win. Every claim was checked by a program run on JDK 25, and each code and output block links to its file in the companion module. The deeper material sits in expandable “Going deeper” boxes, so you can read straight through or open only what you need.
Tested against: JDK 25.0.5.1+2 (Temurin). Java 25 is the current long-term-support release (GA September 2025); Oracle’s roadmap lists Java 29 as the next one, planned for September 2027. JUnit Jupiter 6.1.3, Maven 3.9.11, surefire 3.6.1. Java 27 shipped on 15 September 2026; nothing below depends on it.

Hardware matters in two places. Every timing comes from a 2-vCPU VM, which makes the JVM’s common pool one thread wide. Sections 2 and 7 say exactly where that changes the numbers.

Why does my chain return a CompletableFuture of a CompletableFuture?

A CompletableFuture<T> is a box that will contain a T later. supplyAsync(...) hands a function to another thread and gives you the box straight away; when the function finishes, the box is filled. thenApply(f) says: when this box is filled, run f on what is inside and put the answer in a new box. That works until f is itself an asynchronous call — one that returns a box. thenApply does not look at what f returns; it puts it in the new box. You end up with a box inside a box. Here are two such calls, from ThenApplyVsComposeDemo.java:
static CompletableFuture<User> fetchUser(long id, ExecutorService io) {
    return CompletableFuture.supplyAsync(() -> {
        sleep(100);
        return new User(id, "ankur");
    }, io);
}

static CompletableFuture<Order> fetchLastOrder(User user, ExecutorService io) {
    return CompletableFuture.supplyAsync(() -> {
        sleep(150);
        return new Order(user.id(), "laptop");
    }, io);
}
And what happens when you chain them with thenApply, from the same file:
CompletableFuture<CompletableFuture<Order>> nested =
        fetchUser(1, io).thenApply(user -> fetchLastOrder(user, io));
Object inner = nested.join();
System.out.println("nested.join() is a: " + inner.getClass().getSimpleName());
System.out.println("inner.join() is:    " + ((CompletableFuture<?>) inner).join());
Real output, from output/01-thenapply-vs-thencompose.txt:
== 1. thenApply with a function that itself returns a CompletableFuture
nested.join() is a: CompletableFuture
inner.join() is:    Order[userId=1, item=laptop]
thenApply(user -> fetchLastOrder(user))CompletableFuture<…>CompletableFuture<Order>Ordera future of a futurethenCompose(user -> fetchLastOrder(user))CompletableFuture<Order>Orderone futurethenApply wraps whatever your function returns. thenCompose unwraps one level.
The left box is the type you get from thenApply: the function returned a future, so the result is a future of a future, and you have to call join() twice to reach the Order. The right box is what you wanted. thenCompose is the method that unwraps one level, so the result is a single future of the value. From ThenApplyVsComposeDemo.java:
CompletableFuture<Order> flat =
        fetchUser(1, io).thenCompose(user -> fetchLastOrder(user, io));
System.out.println("flat.join() is:     " + flat.join());
Real output, from output/01-thenapply-vs-thencompose.txt:
== 2. thenCompose flattens it
flat.join() is:     Order[userId=1, item=laptop]
thenCompose also compiles, and returns the right answer, when the two calls do not depend on each other — and then it makes them run one after the other. If the second call does not need the first call’s result, start both before you combine them.
The next three lines are the same two calls timed three ways on a fixed pool of four threads, so nothing queues. The code, from ThenApplyVsComposeDemo.java:
timed("dependent calls: thenCompose (100 ms then 150 ms)",
        () -> fetchUser(1, io).thenCompose(user -> fetchLastOrder(user, io)));

timed("independent calls: start both, then thenCombine",
        () -> {
            CompletableFuture<User> user = fetchUser(1, io);
            CompletableFuture<String> banner = fetchBanner(io);
            return user.thenCombine(banner, (u, b) -> u.name() + " + " + b);
        });

timed("independent calls, wrongly chained with thenCompose",
        () -> fetchUser(1, io)
                .thenCompose(user -> fetchBanner(io).thenApply(b -> user.name() + " + " + b)));
Real output, from output/01-thenapply-vs-thencompose.txt:
== 3. Same three tools, measured (fixed pool of 4, so nothing queues)
dependent calls: thenCompose (100 ms then 150 ms)          -> Order[userId=1, item=laptop]         251 ms
independent calls: start both, then thenCombine            -> ankur + winter-sale                  125 ms
independent calls, wrongly chained with thenCompose        -> ankur + winter-sale                  221 ms
dependent callsthenCompose: 251 msfetchUser 100fetchLastOrder 150independent callsstart both, thenCombine: 125 msfetchUser 100fetchBanner 120independent callswrongly chained: 221 msfetchUser 100fetchBanner 120050100150200250ms
The first lane is a genuine dependency: the order lookup needs the user, so 251 ms (100 plus 150, plus a little overhead) is the floor. The second lane starts both calls up front and finishes with the slower one, 125 ms. The third lane has the same two independent calls as the second, but chained, and pays for both in sequence: 221 ms. Nothing in the types or the result tells you the third version is slower; only the clock does.
Going deeper: thenCompose, thenCombine and their relatives thenCompose is the same idea as flatMap on Optional or Stream: apply a function that returns a container, then flatten one level. If you are comfortable with flatMap, then thenApply is map. For two independent futures, thenCombine takes both results and a two-argument function. Siblings exist for the cases where you do not need a return value (thenAcceptBoth, runAfterBoth) or want whichever of two finishes first (applyToEither). The question to ask before choosing is always the same: does the second call need the first call’s result? If yes, thenCompose; if no, start both and combine.

Which thread runs my code?

You never create a thread when you use CompletableFuture, but your code still runs on one. Which one depends on two choices. First, supplyAsync and every method ending in Async hand the work to an executor: the JVM-wide common pool if you pass none, or yours if you pass one. Second, the plain methods such as thenApply do not pick a thread at all. They run on whichever thread completes the previous stage — or, if that stage has already finished when you call them, on the thread that called them. The demo registers four stages on one slow future. A latch holds the future open until every stage is registered, so “registered while it was still running” is guaranteed. From WhichThreadDemo.java:
CountDownLatch gate = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(4);
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
    await(gate);
    record("1", "supplyAsync body", done);
    return "x";
});
slow.thenApply(v -> { record("2", "thenApply (registered before slow finished)", done); return v; });
slow.thenApplyAsync(v -> { record("3", "thenApplyAsync (no executor)", done); return v; });
slow.thenApplyAsync(v -> { record("4", "thenApplyAsync (executor = mine)", done); return v; }, mine);
gate.countDown(); // every stage is registered; now let slow finish
await(done);
Real output, from output/02-which-thread.txt:
== Stage registered WHILE the previous stage is still running
supplyAsync body                                     ran on ForkJoinPool.commonPool-worker-1
thenApply (registered before slow finished)          ran on ForkJoinPool.commonPool-worker-1
thenApplyAsync (no executor)                         ran on ForkJoinPool.commonPool-worker-1
thenApplyAsync (executor = mine)                     ran on my-pool-1

== Stage registered AFTER the previous stage finished
thenApply (registered after slow finished)           ran on main
thenApply on completedFuture(..)                     ran on main

== Supplying with your own executor
supplyAsync(.., mine) body                           ran on my-pool-2
thenApply after supplyAsync(.., mine)                ran on my-pool-2
thenApply, registered whilethe previous stage is still runningthe completing threadcommonPool-worker-1thenApply, registered afterthe previous stage has finishedthe calling threadmainthenApplyAsync(fn)no executor argumentthe common poolcommonPool-worker-1thenApplyAsync(fn, mine)your executoryour executormy-pool-1Output of WhichThreadDemo. The thread names come straight from the transcript.
Read the diagram top to bottom. A plain thenApply registered early ran on the worker that finished the previous stage. The same call registered after the previous stage was done ran on main, because there was nothing left to wait for. The two Async calls moved the work to a pool: the common pool when no executor was given, my-pool-1 when one was.
A plain thenApply can land on a thread you did not choose, so do not put slow or blocking work in it. It holds whichever thread happened to complete the previous stage. If that is a common-pool worker, it is a worker every other supplyAsync in the JVM shares.
Going deeper: the common pool, and why it is one thread wide here The first two lines of the transcript are the important context: availableProcessors = 2 and common pool parallelism = 1. In the JDK 25 source, the common pool’s default size is the number of processors minus one, with a floor of one. On a 2-vCPU machine that is a single worker. A blocking task — a remote call, a sleep — holds a worker for its whole duration, so a one-worker pool runs blocking tasks strictly one at a time. Section 7 measures exactly that. The usual fix is to give blocking work an executor of its own: a fixed pool sized to what the downstream system can take, or one virtual thread per task. The common pool is sized for CPU work and shared by parallel streams too, which is why the parallel-streams post below spends its time on it.

The thread that waits for the result may run your stage

There is a third possibility the previous transcript carefully avoided: the thread that calls join() can end up running your stage. In WhichThreadDemo, main waits on a latch precisely to keep that from happening. Here is the same arrangement with two different ways of waiting, 200 trials each. From JoinHelpsDemo.java:
CountDownLatch gate = new CountDownLatch(1);
AtomicReference<Thread> ranOn = new AtomicReference<>();
CompletableFuture<String> source = CompletableFuture.supplyAsync(() -> {
    await(gate);
    return "x";
});
CompletableFuture<Void> stage = source.thenAccept(v -> {
    ranOn.set(Thread.currentThread());
    if (Thread.currentThread() == main) {
        sample.compareAndSet(null, new Throwable().getStackTrace()); // keep the first one
    }
});
gate.countDown();
source.join(); // main waits by calling join() on the source: this is where it may run the stage
stage.join();  // then make sure the stage has finished, whichever thread ran it
CountDownLatch gate = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(1);
AtomicReference<Thread> ranOn = new AtomicReference<>();
CompletableFuture<String> source = CompletableFuture.supplyAsync(() -> {
    await(gate);
    return "x";
});
source.thenAccept(v -> {
    ranOn.set(Thread.currentThread());
    done.countDown();
});
gate.countDown();
await(done); // main waits on a latch, never calls into the future
Real output, from output/03-join-helps.txt:
trials per loop: 200
stage ran on main when main waited with join():        37
stage ran on main when main waited on a CountDownLatch: 0

stack of the first stage that ran on main while it was inside join():
    at com.ankurm.completablefuture.JoinHelpsDemo.lambda$main$1(JoinHelpsDemo.java:35)
    at java.base/java.util.concurrent.CompletableFuture$UniAccept.tryFire(CompletableFuture.java:739)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:531)
    at java.base/java.util.concurrent.CompletableFuture.waitingGet(CompletableFuture.java:1930)
    at java.base/java.util.concurrent.CompletableFuture.join(CompletableFuture.java:2138)
    at com.ankurm.completablefuture.JoinHelpsDemo.main(JoinHelpsDemo.java:39)
In this run main ran the stage 37 times out of 200 while it waited with join(), and never when it waited on a latch. The count is a race and varies widely: it ranged from 8 to 104 across the runs I made while writing this. The frames show the mechanism. join() calls waitingGet, which calls postComplete, which fires the dependent stage — so your lambda runs inside the waiting thread’s join() call.
This is documented, not a bug. The Javadoc says actions for non-async dependents may be performed by the thread that completes the future, or by any other caller of a completion method. So never assume a plain thenApply stays off your calling thread. If a stage touches thread-confined state or is slow, use an Async variant with an executor you chose.
Going deeper: waiting without running other people’s stages A CountDownLatch counted down inside the stage, or polling isDone(), waits without entering the future’s completion machinery, which is why the second loop reports zero. In ordinary code you rarely need that: you need to know the stage may run on the joining thread, and write it so that does not matter. The frame numbers in the transcript (CompletableFuture.java:1930 and so on) belong to JDK 25.0.5.1. Other builds will print different line numbers for the same path.

What happens when a stage throws?

If the function inside supplyAsync throws, the box is filled with a failure instead of a value. Every stage chained after it is skipped — its function never runs — and the failure passes down the chain until something handles it. Three methods can: exceptionally turns a failure into a value, handle sees either the value or the failure and returns a value, and whenComplete looks but changes nothing.
supplyAsyncthrows “boom”thenApplyx + 1 (skipped)thenApplyx * 2 (skipped)exceptionallygets CompletionExceptionvalue-1The failure travels down the chain. Skipped stages never run their function.exceptionally sees a CompletionException: a throw inside supplyAsync arrives wrapped,and so does a failure that passed through another stage. Its cause is the exception you threw.
The dashed boxes are the stages that never ran. A test pins that: the functions in two thenApply stages after a failed future are never called. The interesting part is what the handler at the end actually receives. From ExceptionHandlingDemo.java:
static CompletableFuture<Integer> failing() {
    return CompletableFuture.supplyAsync(() -> {
        throw new IllegalStateException("boom");
    });
}

static CompletableFuture<Integer> failedDirectly() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    f.completeExceptionally(new IllegalStateException("boom"));
    return f;
}
failing().exceptionally(ex -> {
    System.out.println("supplyAsync threw, exceptionally on same stage: " + describe(ex));
    return -1;
}).join();
failedDirectly().exceptionally(ex -> {
    System.out.println("completeExceptionally(raw), same stage:         " + describe(ex));
    return -1;
}).join();
failedDirectly().thenApply(x -> x + 1).exceptionally(ex -> {
    System.out.println("completeExceptionally(raw), one stage later:    " + describe(ex));
    return -1;
}).join();
Real output, from output/04-exception-handling.txt:
== 1. What does exceptionally() receive?
supplyAsync threw, exceptionally on same stage: CompletionException <- cause IllegalStateException: boom
completeExceptionally(raw), same stage:         IllegalStateException: boom
completeExceptionally(raw), one stage later:    CompletionException <- cause IllegalStateException: boom
The wrapper trap. The first and third lines show CompletionException with your exception as its cause. The second shows your exception raw, because that future was failed directly with completeExceptionally and the handler sits on that very stage. So ex instanceof IllegalStateException can be false even though an IllegalStateException is exactly what was thrown. When you need to test the cause, unwrap a CompletionException first.
The same wrapping explains what the two blocking calls throw. join() throws an unchecked CompletionException; get() throws a checked ExecutionException. Both carry your exception as the cause. From ExceptionHandlingDemo.java:
try {
    failing().join();
} catch (CompletionException e) {
    System.out.println("join(): " + describe(e));
}
try {
    failing().get();
} catch (ExecutionException e) {
    System.out.println("get():  " + describe(e));
}
CompletableFuture<Integer> f = failing();
try {
    f.join();
} catch (CompletionException ignored) {
    // state() and exceptionNow() are the non-throwing way to look (JDK 19+)
}
System.out.println("state() = " + f.state() + ", exceptionNow() = " + describe(f.exceptionNow()));
== 2. What do join() and get() throw?
join(): CompletionException <- cause IllegalStateException: boom
get():  ExecutionException <- cause IllegalStateException: boom
state() = FAILED, exceptionNow() = IllegalStateException: boom
Finally the difference between the three handlers. exceptionally and handle both recover. whenComplete does not: it observes the failure and passes it on unchanged. From ExceptionHandlingDemo.java:
int viaExceptionally = failing().exceptionally(ex -> -1).join();
int viaHandle = failing().handle((v, ex) -> ex == null ? v : -2).join();
System.out.println("exceptionally(ex -> -1)             -> " + viaExceptionally);
System.out.println("handle((v, ex) -> ex==null?v:-2)    -> " + viaHandle);

CompletableFuture<Integer> observed = failing().whenComplete((v, ex) ->
        System.out.println("whenComplete saw:                      " + describe(ex)));
try {
    observed.join();
} catch (CompletionException e) {
    System.out.println("whenComplete did not recover; join():  " + describe(e));
}
== 3. exceptionally vs handle vs whenComplete
exceptionally(ex -> -1)             -> -1
handle((v, ex) -> ex==null?v:-2)    -> -2
whenComplete saw:                      CompletionException <- cause IllegalStateException: boom
whenComplete did not recover; join():  CompletionException <- cause IllegalStateException: boom
Going deeper: exceptionallyCompose, state() and exceptionNow() exceptionallyCompose (Java 12) is exceptionally for recoveries that are themselves asynchronous: your fallback returns a future, and the method flattens it the way thenCompose does. In the transcript it recovers a failed call with a second async call and returns 99. state() and exceptionNow() (both Java 19) let you inspect a finished future without a try/catch. The transcript shows state() = FAILED and an exceptionNow() that returns your original exception unwrapped.

A timeout does not stop the work

orTimeout(100, MILLISECONDS) (Java 9) completes the future with a TimeoutException if nothing else has completed it by then. completeOnTimeout(value, ...) completes it with a fallback value instead. Both act on the box. Neither tells the task that is filling the box to stop. From TimeoutDemo.java, a task that sleeps 600 ms with a 100 ms timeout on top:
AtomicBoolean finished = new AtomicBoolean();
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
    sleep(600);
    finished.set(true);
    return "late result";
}, pool).orTimeout(100, TimeUnit.MILLISECONDS);
try {
    slow.join();
} catch (CompletionException e) {
    System.out.println("join() after 100 ms:            " + describe(e));
}
System.out.println("task finished right after that? " + finished.get());
sleep(700);
System.out.println("task finished 700 ms later?     " + finished.get());
Real output, from output/05-timeouts-and-cancel.txt:
== 1. orTimeout: the future fails, the task keeps running
join() after 100 ms:            CompletionException <- cause TimeoutException: null
task finished right after that? false
task finished 700 ms later?     true
the futureorTimeout(100 ms)TimeoutException at 100 msthe tasksleep(600), then finished = truestill running…finished = falsetask done at 600 msfinished = trueThe timeout completed the box. Nothing told the task to stop.
The future ended at 100 ms; the task did not notice. Right after the timeout the flag was still false, and 700 ms later it was true: the work ran to completion and its result was thrown away. In production that is a thread, a database connection, or a remote call still being paid for after the caller has moved on.
cancel(true) does not interrupt either. Despite the name of its argument, the Javadoc says mayInterruptIfRunning has no effect on a CompletableFuture, because interrupts are not used to control its processing. The transcript agrees: the future was cancelled, the task never saw an interrupt, and it ran to the end.
== 3. cancel(true) does not interrupt the task either
cancel(true) returned:          true
join():                         CancellationException
task saw an interrupt?          false
task ran to the end anyway?     true
The fix is to keep the Future your executor gave you and cancel that when the timeout fires. The executor’s own Future.cancel(true) does interrupt the running thread. From TimeoutDemo.java:
AtomicBoolean interrupted = new AtomicBoolean();
CompletableFuture<String> result = new CompletableFuture<>();
Future<?> handle = pool.submit(() -> {
    try {
        Thread.sleep(400);
        result.complete("done");
    } catch (InterruptedException e) {
        interrupted.set(true);
    }
});
result.orTimeout(100, TimeUnit.MILLISECONDS).whenComplete((v, ex) -> {
    if (ex instanceof TimeoutException) {
        handle.cancel(true);
    }
});
== 4. The fix: keep the executor's Future and cancel THAT on timeout
join():                         CompletionException <- cause TimeoutException: null
task saw an interrupt?          true
Going deeper: choosing between the two timeout methods Use orTimeout when a slow answer is a failure the caller should see. Use completeOnTimeout when a stale default is acceptable: a cached price, an empty recommendations list. Either way, decide separately what should happen to the underlying work. If it is safe to abandon, say so in a comment; if it is not, wire up the cancellation shown above.

allOf and anyOf: what they actually wait for

allOf(a, b, c) returns a CompletableFuture<Void> that completes when all of them have. It carries no values; you read them from a, b and c afterwards. anyOf(a, b, c) returns a CompletableFuture<Object> that completes when the first one does. From AllOfAnyOfDemo.java:
CompletableFuture<List<String>> all = CompletableFuture.allOf(a, b, c)
        .thenApply(v -> List.of(a.join(), b.join(), c.join()));
System.out.println("collected: " + all.join());
The surprise comes when one input fails. The demo has one task that fails at 50 ms and one that succeeds at 400 ms. Real output, from output/06-allof-anyof.txt:
== 2. allOf with one early failure: it waits for the slow one anyway
allOf failed with: CompletionException <- cause IllegalStateException: failed after 50 ms
after 401 ms (the failure itself happened at 50 ms)
slow task finished by then? true
early taskfails at 50 msslow tasksucceeds at 400 msrunningallOf(early, slow)fails at 401 mswaiting for everyoneallOrFailFast(…)fails at 401 msfails now; slow task is not cancelled
allOf did report the failure, but only after 401 ms, once the slow task had also finished. It completes when every input has completed, and fails afterwards if any of them failed. It does not fail fast, and it cancels nothing.
If you want the first failure immediately, you have to write that yourself — and it still will not cancel the other tasks. The helper below completes as soon as any input fails. In the transcript, the slow task is still running at that moment and finishes 450 ms later.
From AllOfAnyOfDemo.java:
static CompletableFuture<Void> allOrFailFast(List<? extends CompletableFuture<?>> futures) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    futures.forEach(f -> f.whenComplete((v, ex) -> {
        if (ex != null) {
            result.completeExceptionally(ex);
        }
    }));
    CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).thenRun(() -> result.complete(null));
    return result;
}
Real output, from output/06-allof-anyof.txt:
== 3. allOrFailFast: fail at the first failure, but nothing is cancelled
failed with: CompletionException <- cause IllegalStateException: failed after 50 ms
after 50 ms
slow task finished by then?  false
slow task finished 450 ms later? true
anyOf has a similar sharp edge: a failure counts as a completion. If the fastest input fails, anyOf fails, even though a slower one would have succeeded. When you want the first success, this helper from AllOfAnyOfDemo.java does it:
static <T> CompletableFuture<T> firstSuccess(List<CompletableFuture<T>> futures) {
    CompletableFuture<T> result = new CompletableFuture<>();
    AtomicInteger failures = new AtomicInteger();
    for (CompletableFuture<T> f : futures) {
        f.whenComplete((v, ex) -> {
            if (ex == null) {
                result.complete(v);
            } else if (failures.incrementAndGet() == futures.size()) {
                result.completeExceptionally(ex);
            }
        });
    }
    return result;
}
== 4. anyOf returns the first COMPLETION, and a failure counts
anyOf failed with: CompletionException <- cause IllegalStateException: failed after 30 ms

== 5. firstSuccess: skip failures, take the first value
firstSuccess result: slow ok
Going deeper: the shape of the two helpers allOrFailFast attaches a whenComplete to every input that completes the result exceptionally on the first failure, and separately attaches allOf(...).thenRun(...) to complete it normally when everything succeeded. Completing an already-completed future is a no-op, so the two paths do not conflict. firstSuccess counts failures and only fails the result when every input has failed, passing along the last exception it saw. Both are plain code: no new concurrency primitives. The Javadoc for allOf and anyOf says that an input that completes exceptionally makes the returned future complete exceptionally with a CompletionException holding the cause — the same wrapper as in section 4.

When do virtual threads win?

A virtual thread is a thread the JVM schedules itself. A blocked one costs almost nothing, so you can use one per task. Executors.newVirtualThreadPerTaskExecutor() gives you an executor that does exactly that, and you can pass it to supplyAsync like any other executor. The benchmark runs the same set of tasks on four executors. From VirtualThreadsBenchmark.java:
static long run(int tasks, Supplier<Integer> body, Executor executor) {
    long t0 = System.nanoTime();
    List<CompletableFuture<Integer>> futures = IntStream.range(0, tasks)
            .mapToObj(i -> executor == null
                    ? CompletableFuture.supplyAsync(body)
                    : CompletableFuture.supplyAsync(body, executor))
            .toList();
    CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
    return (System.nanoTime() - t0) / 1_000_000;
}
row("default async pool (no executor argument)", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, null));
try (ExecutorService fixed50 = Executors.newFixedThreadPool(50)) {
    row("fixed pool, 50 threads", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, fixed50));
}
try (ExecutorService fixed200 = Executors.newFixedThreadPool(200)) {
    row("fixed pool, 200 threads", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, fixed200));
}
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
    row("virtual thread per task", run(BLOCKING_TASKS, VirtualThreadsBenchmark::blocking, virtual));
}
Real output, from output/07-virtual-threads-timings.txt (one run after a warm-up; indicative, not a JMH result):
== Blocking work: 300 tasks, each sleeping 50 ms (a stand-in for a remote call)
  default async pool (no executor argument)        15095 ms
  fixed pool, 50 threads                             309 ms
  fixed pool, 200 threads                            117 ms
  virtual thread per task                             62 ms

== CPU-bound work: 16 tasks, each 2,000,000 rounds of SHA-256
  sequential, one thread (baseline)                 2237 ms
  default async pool (no executor argument)         2159 ms
  fixed pool, 2 threads (= cores)                   1185 ms
  virtual thread per task                           1116 ms
Blocking work: 300 tasks, each sleeping 50 ms (log scale)default pool (parallelism 1)15,095 msfixed pool, 50 threads309 msfixed pool, 200 threads117 msvirtual thread per task62 msCPU-bound work: 16 tasks, each 2,000,000 SHA-256 rounds (linear scale)sequential, one thread2,237 msdefault pool (parallelism 1)2,159 msfixed pool, 2 threads1,185 msvirtual thread per task1,116 msSame machine, same run: 2 vCPU. Blocking work spreads out when threads are cheap; CPU work does not.
For blocking work the ranking is the argument. The default pool took 15 seconds because, on this 2-vCPU machine, it has one worker: 300 tasks of 50 ms, one after another. A fixed pool of 50 ran six rounds of 50 ms, and a pool of 200 ran two rounds. Virtual threads ran all 300 at once and finished in about the time of one task. On an 8-core machine the default pool would have seven workers and look much better, but the shape stays: a thread that is waiting should not be a scarce resource. For CPU-bound work the ranking collapses. A fixed pool sized to the cores and a virtual-thread executor land close together, because both are limited by two cores of arithmetic. Virtual threads do not create CPU; they stop waiting from costing threads.
Read the default-pool row as a warning, not a benchmark. It is a consequence of this machine having 2 cores. The row that survives any hardware is the comparison between the fixed pools and the virtual-thread executor: for blocking work, the pool size sets the throughput; for virtual threads, nothing does.
Going deeper: using CompletableFuture with virtual threads Nothing about CompletableFuture changes. Pass the virtual-thread executor to supplyAsync(supplier, executor), and to any Async stage that should run there. A test confirms the supplier runs on a virtual thread, and another that 1,000 tasks of 100 ms finish well inside two seconds. The numbers above are wall-clock times from a single run. Treat the ordering as the result and the milliseconds as indicative; for precise figures, use JMH.

What about StructuredTaskScope?

Structured concurrency is designed for the two things allOf does not do: cancel the sibling tasks when one fails, and tie the subtasks’ lifetime to a block of code. It is also, on JDK 25, still a preview API. The file below is deliberately kept out of the build; a script compiles it and the compiler’s own message is committed. From StructuredScopeWithoutPreview.java:
public class StructuredScopeWithoutPreview {
    public static void main(String[] args) throws Exception {
        try (var scope = StructuredTaskScope.open()) {
            scope.join();
        }
    }
}
Real compiler output, from output/08-structured-scope-without-preview.txt:
src/broken/StructuredScopeWithoutPreview.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope;
                           ^
  (use --enable-preview to enable preview APIs)
Preview in Java 25, not final. JEP 505 is titled “Structured Concurrency (Fifth Preview)” and is delivered in JDK 25. The API went through a sixth preview in JDK 26 (JEP 525) and a seventh in JDK 27 (JEP 533). InfoQ reports that JEP 543 makes it final in JDK 28, which Oracle’s roadmap lists for March 2027. On a JDK 25 LTS project you would need --enable-preview at compile time and at run time. Some write-ups describe it as final in Java 25; it is not.
Going deeper: where this leaves allOf Until structured concurrency is final in a release you can ship on, allOf plus a fail-fast helper from section 6 remains the stable option, with the caveat that it cancels nothing. If you do adopt the preview API, the cancel-on-failure behaviour is the thing it adds.

Should you use CompletableFuture at all?

Often not, on JDK 21 and later. If your code is a sequence of blocking calls, plain blocking code on a virtual thread per request is simpler than a chain, and its stack traces are ordinary. Reach for CompletableFuture when you are genuinely composing: fanning out and combining results, racing alternatives, or adding timeouts and fallbacks to calls you do not control. When you do, give it an executor of your own, remember that a timeout or a cancel does not stop the work, and remember that allOf waits for everything.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.