Java CompletableFuture: choosing an executor and handling timeouts
On this page
Use an explicit ExecutorService to choose where asynchronous tasks run, and connect their results with CompletableFuture. The Java 21 example runs the same order on platform and virtual threads and gets the same 23000 KRW receipt. A separate example shows what a timeout changes: join() reports TimeoutException as the cause while the submitted task can still finish. Java 21 CompletableFuture API · Java 21 ExecutorService API
Choosing a method
| Method | When to use it | Example |
|---|---|---|
supplyAsync / runAsync |
Submit asynchronous work with a value or with a Void completion, respectively. |
Look up an order / refresh a cache |
thenApply |
Transform a successful value. | Extract the order ID |
thenCompose |
Start another asynchronous task from a successful value and compose its result. | Issue a receipt from an order summary |
thenCombine |
Combine two stages that have already started once both succeed. | Add the item price and shipping fee |
thenAccept / thenRun |
Run a side effect after success. The first receives the value. | Log the order ID / increment a completion counter |
allOf |
Complete once all stages finish. Any failure completes it exceptionally, and it does not collect individual values. | Wait for both the receipt and the audit log |
whenComplete / exceptionally / handle |
Observe either outcome / recover from failure only / transform either outcome. | Log a failure / use a contractual shipping fallback / return a status |
orTimeout / completeOnTimeout |
If still pending at the deadline, complete the same future with an exception or a fallback, respectively. | Report a deadline error / show a default for an optional field |
Submit the same work to two executors
Use JDK 21. The order and shipping lookups are submitted separately with supplyAsync, so either can proceed independently. The first executor reuses two platform threads. The second creates a virtual thread for each submitted task. Both use try-with-resources. Their close() starts an orderly shutdown and waits for tasks to finish. Java 21 Executors API · Java 21 ExecutorService API
The diagram shows the order pipeline. While thenApply extracts the ID for thenAccept to log, thenCombine waits for the shipping fee and adds it to the item price. thenCompose uses that total to submit the receipt task to the same executor and composes its completion. After allOf(receipt, audit).join() succeeds, receipt.join() reads the completed value. The code then runs a single-task submit/get probe and a timeout example, which the diagram omits.
FutureExample.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FutureExample {
record Order(int id, int price) {}
record Summary(int orderId, int total) {}
public static void main(String[] args) throws Exception {
try (var pool = Executors.newFixedThreadPool(
2, Thread.ofPlatform().name("platform-", 0).factory())) {
demo("platform", pool);
}
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
demo("virtual", executor);
}
}
static void demo(String name, ExecutorService executor) throws Exception {
System.out.println("[" + name + "]");
var order = CompletableFuture.supplyAsync(
() -> {
blockingStep("order");
return new Order(42, 20_000);
}, executor);
var shipping = CompletableFuture.supplyAsync(
() -> {
blockingStep("shipping");
return 3_000;
}, executor);
var summary = order.thenCombine(shipping,
(o, fee) -> new Summary(o.id(), o.price() + fee));
var receipt = summary.thenCompose(s -> CompletableFuture.supplyAsync(
() -> {
blockingStep("receipt");
return "order %d: %d KRW".formatted(s.orderId(), s.total());
}, executor));
var audit = order.thenApply(Order::id)
.thenAccept(id -> System.out.println("audit: " + id));
CompletableFuture.allOf(receipt, audit).join();
System.out.println(receipt.join());
var probe = executor.submit(() -> Thread.currentThread().isVirtual());
System.out.println("submit/get: " + probe.get());
// 완료시키는 작업이 없는 Future로 대기 시간 초과만 재현한다.
String fallback = new CompletableFuture<String>()
.completeOnTimeout("fallback", 30, TimeUnit.MILLISECONDS)
.join();
System.out.println("timeout: " + fallback);
}
static void blockingStep(String task) {
System.out.printf("%s virtual=%s%n",
task, Thread.currentThread().isVirtual());
try {
Thread.sleep(30); // I/O 대기를 흉내 낸다.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CompletionException(e);
}
}
}
Observe a failure, recover, and apply a timeout
whenComplete logs the failure and passes the original outcome through when its callback returns normally. Here the failure reaches exceptionally, which returns 3000. handle attaches to the original failed stage and maps it to unavailable. Use a fallback shipping fee for real billing only when an explicit contract authorizes it.
In the first example, completeOnTimeout completes a pending future normally with fallback after 30 ms. In the second, the submitted task waits on a latch until orTimeout completes its future with TimeoutException. After the latch opens, the task finishes and complete returns false because the future has already timed out. Set HTTP or database deadlines and cancellation in the client or driver that owns the operation. The timeout probe now waits for the task to start before setting the deadline. Java 21 CompletableFuture API
FutureFailureExample.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FutureFailureExample {
public static void main(String[] args) throws Exception {
var failed = CompletableFuture.<Integer>failedFuture(
new IllegalStateException("shipping unavailable"));
int recovered = failed
.whenComplete((value, error) ->
System.out.println("failed: " + (error != null)))
.exceptionally(error -> 3_000)
.join();
System.out.println("recovered: " + recovered);
String status = failed.handle((value, error) ->
error == null ? "ok: " + value : "unavailable").join();
System.out.println(status);
var started = new CountDownLatch(1);
var release = new CountDownLatch(1);
var result = new CompletableFuture<String>();
try (var executor = Executors.newSingleThreadExecutor()) {
var task = executor.submit(() -> {
started.countDown();
release.await();
return result.complete("finished");
});
try {
started.await();
result.orTimeout(30, TimeUnit.MILLISECONDS).join();
} catch (CompletionException e) {
System.out.println(e.getCause().getClass().getSimpleName());
} finally {
release.countDown();
}
System.out.println("task finished, late value accepted: " + task.get());
}
}
}
Run the examples
Save both files in the same directory and run these commands.
javac --release 21 FutureExample.java FutureFailureExample.java
java FutureExample
java FutureFailureExample
This output is from one actual run after compiling with Zulu OpenJDK 21.0.1.
[platform]
order virtual=false
shipping virtual=false
audit: 42
receipt virtual=false
order 42: 23000 KRW
submit/get: false
timeout: fallback
[virtual]
order virtual=true
shipping virtual=true
audit: 42
receipt virtual=true
order 42: 23000 KRW
submit/get: true
timeout: fallback
failed: true
recovered: 3000
unavailable
TimeoutException
task finished, late value accepted: false
Expect order, shipping, and receipt to show virtual=false for the platform run and virtual=true for the virtual run. Both should print the same 23000 KRW receipt. Output from independent tasks and the audit log may appear in a different order. submit returns a Future for one task, and get waits for its value. The probe reports that task’s isVirtual() result.
Continuation threads and waiting
- On a regular
CompletableFuture, an asynchronous method such asthenApplyAsyncwith no executor argument does not inherit the earlier stage’s executor. It usesForkJoinPool.commonPool()by default, with a new thread per task if common-pool parallelism is below two. A subclass can overridedefaultExecutor()for instance async methods. Pass an executor explicitly when the execution location matters. - Non-async continuations such as
thenApplyandthenCombinehave no fixed thread. The thread completing the current future or another caller of a completion method may run them. When a stage has already finished, the registering thread may run its continuation immediately. - Both
join()andget()can wait for a pending result. For an ordinary failure like the one in this example,join()throws an uncheckedCompletionExceptionandget()throws a checkedExecutionException.get()reports interruption while waiting viaInterruptedException.get(timeout, unit)can bound the caller’s wait. Java 21 CompletableFuture API Thread.sleep(30)simulates an I/O wait. The examples contain no performance measurements. Virtual threads can accommodate many waiting tasks. Database connection counts and external service concurrency limits still apply. OpenJDK JEP 444 · Virtual threads and DB connection limits
Discussion