Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
Write non-blocking Java code with CompletableFuture: supplyAsync, thenApply, thenCompose, thenAccept, exceptionally, handle, timeouts, thenCombine, allOf and anyOf, completing futures yourself, cancellation and building clean asynchronous pipelines.
kvi5hnuCode Sprout team member11 min readOn this page
Until now, our concurrent programs split up the work and then waited for the pieces, using Future.get, invokeAll or join. Waiting is cheap with virtual threads. With platform threads, though, every blocked thread is an expensive resource doing nothing. The alternative is an asynchronous style. Instead of waiting for a result, you say what should happen when it arrives. Java's tool for this is CompletableFuture.
From Future to CompletableFuture
With a plain Future, the only way to get the value is get(), which blocks. CompletableFuture<T> implements Future<T> but adds a second mechanism. You register a callback that is invoked, in some thread, with the result once it's available:
CompletableFuture<String> f = ...;
f.thenAccept(s -> process(s)); // returns immediately; runs later
Some APIs return CompletableFutures directly. For example, HttpClient.sendAsync (Volume II) fetches a web page without blocking:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create(urlString)).GET().build();
CompletableFuture<HttpResponse<String>> f =
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
Creating a CompletableFuture with supplyAsync
Most of the time you make your own. Rather than submitting a task to an executor, call the static supplyAsync method:
public CompletableFuture<String> readPage(URI url) {
return CompletableFuture.supplyAsync(() -> {
try (InputStream in = url.toURL().openStream()) { // close the stream
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}, executor);
}
Without the executor argument, the task runs in ForkJoinPool.commonPool(). Usually that's not what you want, because the common pool is shared with parallel streams and other libraries and is sized for CPU-bound work, not blocking I/O. runAsync(Runnable, executor) is the variant for tasks without a result.
Handling result or failure: whenComplete
A CompletableFuture completes either normally with a value or exceptionally with an uncaught exception. whenComplete receives both, and exactly one of them is non-null:
f.whenComplete((s, t) -> {
if (t == null) { process the result s }
else { process the Throwable t }
});
The exception that dependent stages see is usually a CompletionException wrapping the original. Call getCause() to get to it.
Completing a future yourself
The name says it: the future is completable, meaning someone can set its value. In other libraries this is called a promise, and completing it is "fulfilling the promise". Consumers don't care how the value is set. supplyAsync completes it when its task ends, but you can also do it manually. Here, two algorithms race to produce the answer and a third task enforces a deadline:
var f = new CompletableFuture<Integer>();
executor.execute(() -> f.complete(workHard(arg)));
executor.execute(() -> f.complete(workSmart(arg)));
executor.execute(() -> {
try {
Thread.sleep(timeout);
f.completeExceptionally(new TimeoutException());
} catch (InterruptedException e) {
f.completeExceptionally(e);
}
});
It's safe to call complete and completeExceptionally on the same future from many threads. The first completion wins, and later calls return false and have no effect. CompletableFuture.completedFuture(v) and failedFuture(ex) (Java 9) create already-finished futures.
Composing futures: escaping callback hell
Non-blocking code is built from callbacks. If step 2 is also asynchronous, its continuation is another callback, then another. The programmer thinks "step 1, then step 2, then step 3", but the code scatters into nested callbacks. That's callback hell, and it only gets worse with error handling or retries (step 2 might be "the user logs in", which may need repeating).
CompletableFuture solves this by letting you compose asynchronous steps into a pipeline. Suppose readPage(uri) returns CompletableFuture<String> and getImageLinks(String page) returns a List<URI>:
CompletableFuture<String> contents = readPage(uri);
CompletableFuture<List<URI>> imageLinks = contents.thenApply(Parser::getImageLinks);
thenApply doesn't block. It returns another future, and when contents completes, its value is passed to getImageLinks. All the logic sits in one place, in the order you think of it.
Adding an action to one future
In this table, T -> U is shorthand for Function<? super T, ? extends U>, and so on.
| Method | Parameter | Description |
|---|---|---|
thenApply | T -> U | apply a function to the result |
thenAccept | T -> void | like thenApply, with a void result |
thenCompose | T -> CompletableFuture<U> | call the function and continue with the future it returns |
thenRun | Runnable | run the action with a void result |
handle | (T, Throwable) -> U | process result or error, yield a new result |
whenComplete | (T, Throwable) -> void | like handle, but keeps the original result |
exceptionally | Throwable -> T | compute a replacement result from the error |
exceptionallyCompose | Throwable -> CompletableFuture<T> | recover asynchronously (Java 12) |
completeOnTimeout | T, long, TimeUnit | use the given value if the time runs out |
orTimeout | long, TimeUnit | fail with TimeoutException if the time runs out |
thenApply vs thenCompose is the distinction that matters most. The second takes a function that returns a future. If you used thenApply with readPage, you'd get a CompletableFuture<CompletableFuture<String>>. thenCompose flattens it, the same way flatMap does for streams and Optional.
Error handling. If a stage fails, the dependent stages are skipped and the exception propagates down the pipeline until something handles it. exceptionally substitutes a value, handle sees both outcomes, and timeouts are handled the same way:
CompletableFuture<List<URI>> imageLinks = readPage(url)
.exceptionally(ex -> "<html></html>")
.thenApply(this::getImageLinks);
CompletableFuture<List<URI>> imageLinks = readPage(url)
.completeOnTimeout("<html></html>", 30, TimeUnit.SECONDS)
.thenApply(this::getImageLinks);
CompletableFuture<String> page = readPage(url).orTimeout(30, TimeUnit.SECONDS);
Methods with a void result usually end a pipeline.
Combining several futures
These methods run two futures concurrently:
| Method | Parameters | Description |
|---|---|---|
thenCombine | CompletableFuture<U>, (T, U) -> V | wait for both, combine the results |
thenAcceptBoth | CompletableFuture<U>, (T, U) -> void | like thenCombine, void result |
runAfterBoth | CompletableFuture<?>, Runnable | run after both complete |
applyToEither | CompletableFuture<T>, T -> V | use whichever result arrives first |
acceptEither | CompletableFuture<T>, T -> void | like applyToEither, void result |
runAfterEither | CompletableFuture<?>, Runnable | run after either completes |
static allOf | CompletableFuture<?>... | completes (with no value) when all complete, some perhaps exceptionally |
static anyOf | CompletableFuture<?>... | completes when any one completes, with its result or exception |
allOf yields a CompletableFuture<Void>. To get the values, join each original future afterwards, which no longer blocks. anyOf doesn't cancel the others, and its result may be an exception even when other futures succeed.
Async variants and executors
Most of the methods above (all except allOf, anyOf, completeOnTimeout and orTimeout) have two Async variants, such as thenApplyAsync(f) and thenApplyAsync(f, executor). They choose the executor for the dependent action. The non-async version runs the action in whichever thread completes the previous stage, or immediately in the caller if it's already done. The version without an executor uses the common pool, which is not recommended. A good pattern is to start with an Async variant that sets your executor and then use the plain methods, which continue in that executor's threads.
Technically, these methods take a CompletionStage, an interface that describes composition, while Future describes the result. CompletableFuture implements both. Return CompletionStage from APIs if callers shouldn't complete your futures.
The ideal pipeline
A typical example reads a web page, finds its images, loads them and saves them. It starts with a completed future holding the URL, so every step looks the same:
CompletableFuture.completedFuture(url)
.thenComposeAsync(this::readPage, executor)
.thenApply(this::getImageLinks)
.thenCompose(this::getImages)
.thenAccept(this::saveImages);

Each step is one of three kinds:
- an asynchronous function
T -> CompletableFuture<U>, passed tothenCompose, - a synchronous function
T -> U, passed tothenApply, - a final consumer
T -> void, passed tothenAccept.
The initial completedFuture supplies the first argument, and the first step uses thenComposeAsync to set the executor. With HttpClient, the start becomes client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body). The demo runs the same pipeline against a small in-memory "web" so it works offline.
join, get and friends
get()throws checkedExecutionExceptionandInterruptedException.join()throws uncheckedCompletionExceptionorCancellationException, which makes it convenient in lambdas.getNow(valueIfAbsent)doesn't wait. Java 19 addedresultNow(),exceptionNow()andstate()(RUNNING,SUCCESS,FAILED,CANCELLED).CompletableFuture.delayedExecutor(delay, unit, executor)(Java 9) runs a task after a delay,copy()hands out a defensive copy (completing or cancelling the copy doesn't affect the original), andminimalCompletionStage()returns a stage that callers can only chain onto, not complete.
A complete example
The demo runs the image pipeline offline and logs a failure with whenComplete. It recovers with exceptionally, handle and exceptionallyCompose, contrasts join with get, applies both timeouts, completes futures by hand (first completion wins), shows that cancel doesn't stop the task, and combines futures with thenCombine, thenAcceptBoth, runAfterBoth, applyToEither, acceptEither, allOf, anyOf and a delayed executor.
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// a tiny fake "web" so the demo is offline and deterministic
static final Map<String, String> WEB = Map.of(
"https://example.com/", "<html><img src='a.png'> text <IMG SRC=\"b.png\"><img src='c.png'></html>",
"https://example.com/a.png", "AAAA",
"https://example.com/b.png", "BBBBBB",
"https://example.com/c.png", "CC");
static final Pattern IMG = Pattern.compile("<\\s*img\\s+[^>]*src\\s*=\\s*['\"]([^'\"]*)['\"]", Pattern.CASE_INSENSITIVE);
static final ExecutorService executor = Executors.newFixedThreadPool(4);
static CompletableFuture<String> readPage(String uri) {
return CompletableFuture.supplyAsync(() -> {
String contents = WEB.get(uri);
if (contents == null) throw new NoSuchElementException("404 " + uri);
return contents;
}, executor);
}
static List<String> getImageLinks(String page) {
var result = new ArrayList<String>();
Matcher m = IMG.matcher(page);
while (m.find()) result.add("https://example.com/" + m.group(1));
System.out.println(" found links: " + result);
return result;
}
static CompletableFuture<List<String>> getImages(List<String> uris) {
List<CompletableFuture<String>> futures = uris.stream().map(Solution::readPage).toList();
return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
.thenApply(v -> futures.stream().map(CompletableFuture::join).toList());
}
static void saveImages(List<String> images) {
System.out.println(" saving " + images.size() + " images, sizes " + images.stream().map(String::length).toList());
}
public static void main(String[] args) throws Exception {
System.out.println("-- the pipeline: completedFuture -> thenComposeAsync -> thenApply -> thenCompose -> thenAccept --");
CompletableFuture<Void> done = CompletableFuture.completedFuture("https://example.com/")
.thenComposeAsync(Solution::readPage, executor)
.thenApply(Solution::getImageLinks)
.thenCompose(Solution::getImages)
.thenAccept(Solution::saveImages);
done.join();
System.out.println("-- whenComplete sees result or exception --");
readPage("https://example.com/missing").whenComplete((s, t) -> {
if (t == null) System.out.println(" result " + s);
else System.out.println(" failed with " + t.getClass().getSimpleName() + " caused by " + t.getCause().getMessage());
}).exceptionally(t -> null).join();
System.out.println("-- recovering from errors --");
String page = readPage("https://example.com/missing").exceptionally(ex -> "<html></html>").join();
System.out.println(" exceptionally: " + page);
String handled = readPage("https://example.com/missing")
.handle((s, t) -> t == null ? "ok " + s.length() : "recovered from " + t.getCause().getClass().getSimpleName()).join();
System.out.println(" handle: " + handled);
String fallback = readPage("https://example.com/missing")
.exceptionallyCompose(ex -> readPage("https://example.com/c.png")).join();
System.out.println(" exceptionallyCompose (try a mirror): " + fallback);
System.out.println("-- join versus get --");
var failing = CompletableFuture.<String>failedFuture(new IllegalStateException("boom"));
try { failing.join(); } catch (CompletionException e) { System.out.println(" join throws CompletionException(" + e.getCause().getMessage() + ")"); }
try { failing.get(); } catch (ExecutionException e) { System.out.println(" get throws ExecutionException(" + e.getCause().getMessage() + ")"); }
System.out.println(" state: " + failing.state() + ", isCompletedExceptionally: " + failing.isCompletedExceptionally());
System.out.println("-- timeouts --");
var never = new CompletableFuture<String>();
System.out.println(" completeOnTimeout: " + never.completeOnTimeout("<html></html>", 50, TimeUnit.MILLISECONDS).join());
try {
new CompletableFuture<String>().orTimeout(50, TimeUnit.MILLISECONDS).join();
} catch (CompletionException e) {
System.out.println(" orTimeout: " + e.getCause().getClass().getSimpleName());
}
System.out.println("-- completing a future yourself --");
var f = new CompletableFuture<Integer>();
System.out.println(" isDone before: " + f.isDone());
System.out.println(" complete(42): " + f.complete(42) + ", complete(99): " + f.complete(99)
+ ", completeExceptionally: " + f.completeExceptionally(new TimeoutException()));
System.out.println(" value: " + f.join() + ", resultNow: " + f.resultNow());
var race = new CompletableFuture<String>();
var latch = new CountDownLatch(1);
executor.execute(() -> race.complete("smart"));
executor.execute(() -> {
try { latch.await(); race.complete("hard"); } catch (InterruptedException e) { race.completeExceptionally(e); }
});
System.out.println(" first completion wins: " + race.join());
latch.countDown();
System.out.println("-- cancel does not interrupt --");
var started = new CountDownLatch(1);
var release = new CountDownLatch(1);
var taskEnded = new CompletableFuture<String>();
var slow = CompletableFuture.supplyAsync(() -> {
started.countDown();
try { release.await(); } catch (InterruptedException e) { taskEnded.complete("was interrupted"); return ""; }
taskEnded.complete("kept running and finished");
return "result nobody sees";
}, executor);
started.await();
System.out.println(" cancel: " + slow.cancel(true) + ", isCancelled: " + slow.isCancelled());
try { slow.join(); } catch (CancellationException e) { System.out.println(" join throws CancellationException"); }
release.countDown();
System.out.println(" the task " + taskEnded.join());
System.out.println("-- combining futures --");
var price = CompletableFuture.supplyAsync(() -> 120, executor);
var rate = CompletableFuture.supplyAsync(() -> 0.9, executor);
System.out.println(" thenCombine: " + price.thenCombine(rate, (p, r) -> p * r).join());
price.thenAcceptBoth(rate, (p, r) -> System.out.println(" thenAcceptBoth: " + p + " at " + r)).join();
price.runAfterBoth(rate, () -> System.out.println(" runAfterBoth: both done")).join();
var fast = CompletableFuture.completedFuture("cache");
var stuck = new CompletableFuture<String>();
System.out.println(" applyToEither: " + stuck.applyToEither(fast, String::toUpperCase).join());
stuck.acceptEither(fast, s -> System.out.println(" acceptEither: " + s)).join();
var parts = List.of(readPage("https://example.com/a.png"), readPage("https://example.com/b.png"));
CompletableFuture.allOf(parts.toArray(CompletableFuture[]::new)).join();
System.out.println(" allOf then join each: " + parts.stream().map(CompletableFuture::join).toList());
Object any = CompletableFuture.anyOf(stuck, CompletableFuture.completedFuture("first")).join();
System.out.println(" anyOf: " + any);
System.out.println("-- delayed executor --");
var delayed = CompletableFuture.supplyAsync(() -> "after delay",
CompletableFuture.delayedExecutor(30, TimeUnit.MILLISECONDS, executor));
System.out.println(" " + delayed.join());
executor.shutdown();
}
}
-- the pipeline: completedFuture -> thenComposeAsync -> thenApply -> thenCompose -> thenAccept --
found links: [https://example.com/a.png, https://example.com/b.png, https://example.com/c.png]
saving 3 images, sizes [4, 6, 2]
-- whenComplete sees result or exception --
failed with CompletionException caused by 404 https://example.com/missing
-- recovering from errors --
exceptionally: <html></html>
handle: recovered from NoSuchElementException
exceptionallyCompose (try a mirror): CC
-- join versus get --
join throws CompletionException(boom)
get throws ExecutionException(boom)
state: FAILED, isCompletedExceptionally: true
-- timeouts --
completeOnTimeout: <html></html>
orTimeout: TimeoutException
-- completing a future yourself --
isDone before: false
complete(42): true, complete(99): false, completeExceptionally: false
value: 42, resultNow: 42
first completion wins: smart
-- cancel does not interrupt --
cancel: true, isCancelled: true
join throws CancellationException
the task kept running and finished
-- combining futures --
thenCombine: 108.0
thenAcceptBoth: 120 at 0.9
runAfterBoth: both done
applyToEither: CACHE
acceptEither: cache
allOf then join each: [AAAA, BBBBBB]
anyOf: first
-- delayed executor --
after delay
Common questions
What is the difference between thenApply and thenCompose?
thenApply takes a function that returns a plain value. thenCompose takes a function that returns another CompletableFuture, and flattens the result. Use thenCompose when the next step is itself asynchronous, otherwise you end up with a CompletableFuture<CompletableFuture<T>>.
Why should I pass an executor to supplyAsync?
Without one, the task runs in ForkJoinPool.commonPool(), which is shared with parallel streams and sized for CPU work. Blocking I/O there can starve the rest of the program. Pass your own executor, for example a virtual thread executor.
Why does my exception arrive wrapped in a CompletionException?
Dependent stages and join() wrap the original exception so that it can travel through the pipeline as an unchecked exception. Call getCause() to get the original. get() wraps it in ExecutionException instead.
Does cancel(true) stop the running task?
No. A CompletableFuture isn't tied to a thread, so canceling it only completes the future with a CancellationException. The task itself keeps running unless it checks some cancellation flag of its own.
Should I use CompletableFuture or virtual threads?
For new server code that mostly waits on I/O, plain blocking code on virtual threads is easier to write, read and debug. CompletableFuture remains useful for combining independent results, for timeouts with orTimeout, and for working with asynchronous APIs that already return futures.
API reference
java.util.concurrent.CompletableFuture<T>
| Method | Description |
|---|---|
static <U> CompletableFuture<U> supplyAsync(Supplier<U> s, Executor e) | runs s in e (common pool if omitted); completes with its result |
static CompletableFuture<Void> runAsync(Runnable r, Executor e) | runs r asynchronously |
static <U> CompletableFuture<U> completedFuture(U value), failedFuture(Throwable ex) | already-completed futures |
boolean complete(T value), boolean completeExceptionally(Throwable ex) | completes if not yet done; true if this call did it |
boolean cancel(boolean mayInterrupt) | completes with CancellationException; never interrupts |
T join(), T get(), T getNow(T valueIfAbsent), T resultNow() | obtain the result |
boolean isDone(), isCompletedExceptionally(), isCancelled(), Future.State state() | query completion |
thenApply, thenAccept, thenRun, thenCompose, handle, whenComplete, exceptionally, exceptionallyCompose | add a dependent action (plus …Async variants) |
thenCombine, thenAcceptBoth, runAfterBoth, applyToEither, acceptEither, runAfterEither | combine with another stage |
static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs), static CompletableFuture<Object> anyOf(...) | wait for all or any |
completeOnTimeout(T value, long t, TimeUnit u), orTimeout(long t, TimeUnit u) | timeouts (Java 9) |
static Executor delayedExecutor(long delay, TimeUnit unit, Executor e) | executor that submits after a delay |
Summary
CompletableFuturelets you register what happens when a result arrives instead of blocking for it. Create one withsupplyAsync/runAsync, ideally with your own executor, and remember that the supplier can't throw checked exceptions.- A future completes once, either normally or exceptionally.
complete/completeExceptionallycan be called from any thread, and the first one wins.cancelnever interrupts the computation. - Compose pipelines with
thenApplyfor synchronous steps,thenComposefor asynchronous ones andthenAcceptat the end. Recover withexceptionally,handleorexceptionallyCompose, and bound waiting withcompleteOnTimeout/orTimeout. - Combine futures with
thenCombine,applyToEither,allOfandanyOf. UseAsyncvariants to pick executors. - With virtual threads, simple blocking code is often clearer.
CompletableFutureshines for combining, timeouts and already-async APIs.
Practice Questions
What is the difference between thenApply and thenCompose?
thenApply takes a function T -> U and wraps its return value in the next future. thenCompose takes a function T -> CompletableFuture<U> and continues with the future that function returns. Using thenApply with an asynchronous function would give a nested CompletableFuture<CompletableFuture<U>>.
Why does supplyAsync code often wrap IOException in UncheckedIOException?
supplyAsync takes a Supplier, whose get method can't throw checked exceptions. The lambda must catch the checked exception and rethrow it unchecked. The future then completes exceptionally with it, wrapped in a CompletionException for dependent stages.
Two threads call complete on the same CompletableFuture with different values. What happens?
Whichever call happens first sets the value, and its complete returns true. The second call returns false and doesn't change anything. The operation is thread-safe.
You call cancel(true) on a future returned by supplyAsync. Does the task stop?
No. The future completes exceptionally with CancellationException, so join throws, but the running task isn't interrupted and continues to the end. Its result is simply ignored.
How do you obtain all results after CompletableFuture.allOf(f1, f2, f3)?
allOf returns CompletableFuture<Void>. After it completes, for example in allOf(...).thenApply(v -> ...) or after join(), call f1.join(), f2.join() and f3.join(). They don't block at that point because all of them are done.
Previous: Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
Next: Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
Related reading
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Primitive Types: Integers and Floating-Point Numbers Explained
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.