CompletableFuture in Java: Asynchronous Programming Made Practical
CompletableFuture is Java's main tool for asynchronous programming. It is a Future you can complete yourself, and a CompletionStage you can chain with callbacks, so you can describe a whole flow of async work without blocking threads.
This tutorial covers creating futures, combining many of them, completing them manually from callback-based code, and adding timeouts.
1. What Is CompletableFuture?
It is a class in java.util.concurrent, added in Java 8, that implements both Future<T> and CompletionStage<T>.
A CompletableFuture is completed either by an asynchronous task started with supplyAsync() or runAsync(), or explicitly by your code calling complete() or completeExceptionally(). Only the first completion counts.
2. CompletableFuture Hierarchy
Swipe sideways to see the whole diagram.
Future(interface): Provides blocking access:get(), pluscancel()and state checks.CompletionStage(interface): Provides the chaining methods that build non-blocking pipelines.
3. Method Details
| Method | Description |
|---|---|
supplyAsync(supplier, executor) | Runs the supplier asynchronously and completes with its result. |
runAsync(runnable, executor) | Runs an action asynchronously; completes with null. |
allOf(cfs…) | Completes when all given futures complete. |
anyOf(cfs…) | Completes when any one of them completes, with that result. |
complete(v), completeExceptionally(ex) | Complete the future manually, if it is not already complete. |
join(), getNow(fallback) | Wait without checked exceptions, or read immediately with a fallback. |
orTimeout(t, unit) | Java 9+: completes exceptionally with TimeoutException if not done in time. |
completeOnTimeout(v, t, unit) | Java 9+: completes with a default value if not done in time. |
4. Example: Finding the Cheapest Offer
A price-comparison feature asks three bookshops for a price in parallel. One shop is too slow, so it gets a placeholder after 400 ms.
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CheapestBookPrice {
record Offer(String shop, double price) {}
static Offer ask(String shop, double price, long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new Offer(shop, price);
}
public static void main(String[] args) {
try (ExecutorService io = Executors.newFixedThreadPool(3)) {
List<CompletableFuture<Offer>> offers = List.of(
CompletableFuture.supplyAsync(() -> ask("PageTurner", 34.90, 100), io),
CompletableFuture.supplyAsync(() -> ask("InkHouse", 31.50, 200), io),
CompletableFuture.supplyAsync(() -> ask("SlowBooks", 29.99, 3_000), io)
// Java 9+: give up after 400 ms and use a placeholder instead
.completeOnTimeout(new Offer("SlowBooks", Double.MAX_VALUE), 400, TimeUnit.MILLISECONDS));
// allOf completes when every offer is in (or has timed out)
CompletableFuture.allOf(offers.toArray(new CompletableFuture<?>[0])).join();
Offer best = null;
for (CompletableFuture<Offer> f : offers) {
Offer o = f.join(); // already complete, does not block
System.out.println(o.shop() + ": "
+ (o.price() == Double.MAX_VALUE ? "no answer in time" : o.price()));
if (best == null || o.price() < best.price()) {
best = o;
}
}
System.out.println("Cheapest: " + best.shop() + " at " + best.price());
}
}
}
PageTurner: 34.9 InkHouse: 31.5 SlowBooks: no answer in time Cheapest: InkHouse at 31.5
How the code works
- Each
supplyAsync(…, io)call runs on the dedicatedioexecutor rather than the shared common pool. completeOnTimeout()completes the slow shop's future with a placeholder after 400 ms; the slow task itself keeps running in the background.allOf()returns aCompletableFuture<Void>that completes when all three are done, andjoin()waits for it.- After that every
join()returns immediately, and a simple loop picks the lowest price.
5. Example: Wrapping a Callback-Based API
Many older libraries report results through callbacks. Creating a CompletableFuture with new and completing it from those callbacks turns them into a modern, composable API.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class CallbackBridge {
// A legacy API that reports results through callbacks on its own thread
static void verifyAddress(String postcode, Consumer<String> onSuccess, Consumer<Exception> onError) {
new Thread(() -> {
if (postcode.matches("\\d{5}")) {
onSuccess.accept(postcode + " is deliverable");
} else if (!postcode.equals("HANG")) {
onError.accept(new IllegalArgumentException("invalid postcode " + postcode));
}
// "HANG" simulates a call that never answers
}).start();
}
// Wrap the callback API in a CompletableFuture that we complete ourselves
static CompletableFuture<String> verify(String postcode) {
CompletableFuture<String> result = new CompletableFuture<>();
verifyAddress(postcode, result::complete, result::completeExceptionally);
return result.orTimeout(300, TimeUnit.MILLISECONDS); // Java 9+: fail if no answer
}
public static void main(String[] args) {
for (String postcode : new String[] {"10115", "X1", "HANG"}) {
try {
System.out.println("OK " + verify(postcode).join());
} catch (CompletionException e) {
System.out.println("ERROR " + postcode + ": " + e.getCause().getClass().getSimpleName());
}
}
}
}
OK 10115 is deliverable ERROR X1: IllegalArgumentException ERROR HANG: TimeoutException
How the code works
verify()creates an incompleteCompletableFutureand passesresult::completeandresult::completeExceptionallyas the callbacks.orTimeout(300, MILLISECONDS)fails the future if no callback arrives in time.join()returns the value, or throws an uncheckedCompletionExceptionwhose cause is the real error:IllegalArgumentExceptionfor the bad postcode,TimeoutExceptionfor the call that never answers.
6. Common Mistakes and Best Practices
- Blocking I/O on the common pool. Async methods without an executor use
ForkJoinPool.commonPool(); pass your own executor for blocking calls. - Calling
get()orjoin()everywhere. Chain withthenApply()and friends, and block only at the edge of the application. - Expecting
cancel(true)to interrupt. On a CompletableFuture it completes the future with aCancellationExceptionbut does not interrupt the task computing it. - Forgetting error handling. Add
exceptionally()orhandle(); otherwise failures surface only when someone joins. - Unbounded waits. Use
orTimeout()orcompleteOnTimeout()for anything that talks to another system.
7. Summary
CompletableFutureimplementsFutureandCompletionStage.- Start work with
supplyAsync()/runAsync(), preferably on your own executor. - Combine results with
allOf()andanyOf(); complete manually withcomplete(). - Java 9 added
orTimeout()andcompleteOnTimeout(). join()wraps failures inCompletionException; checkgetCause().
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between Future and CompletableFuture?
A plain Future only lets you wait for, inspect or cancel a result. CompletableFuture can also be completed manually and supports non-blocking chaining, combining and error handling through CompletionStage.
Q2. What is the difference between join() and get()?
Both wait for the result. get() throws the checked ExecutionException and InterruptedException; join() throws the unchecked CompletionException, which makes it easier to use inside lambdas and streams.
Q3. Which thread pool does supplyAsync() use by default?
Without an executor argument, async methods run on ForkJoinPool.commonPool(). Pass an explicit executor, such as a virtual-thread executor, for blocking work.
Q4. What is the difference between orTimeout() and completeOnTimeout()?
orTimeout() completes the future exceptionally with TimeoutException. completeOnTimeout() completes it normally with a default value. Both were added in Java 9 and neither stops the underlying task.
Q5. Does cancel(true) interrupt a CompletableFuture task?
No. For CompletableFuture, the mayInterruptIfRunning flag has no effect, because interrupts are not used to control processing. The future completes with a CancellationException, but the computation itself is not interrupted.