Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 201 ยท Concurrency

CompletableFuture

Learn Java CompletableFuture - supplyAsync, thenApply, thenCompose and thenCombine, allOf and anyOf, exceptionally and handle, and timeouts with orTimeout.

A plain Future from an executor has one way to get its result: get(), which blocks. If step two needs step one's result and step three needs both, you end up with a thread that just sits and waits. CompletableFuture fixes that. Instead of waiting for a result, you describe what should happen when it arrives: transform it, feed it into another async call, combine it with a second result, or recover from an error. Java runs each step as soon as its inputs are ready.

CompletableFuture<T> implements both Future<T> and CompletionStage<T>, the interface with all the chaining methods. This lesson walks through starting async work, the three core chaining methods (thenApply, thenCompose, thenCombine), waiting for many futures with allOf and anyOf, error handling, timeouts, and the mistakes that bite people in production.

Starting asynchronous work

  • CompletableFuture.supplyAsync(supplier) runs a Supplier<T> in the background and gives you a CompletableFuture<T>.
  • CompletableFuture.runAsync(runnable) does the same for work with no result (CompletableFuture<Void>).
  • Both have an overload that takes an Executor. Without one, they use the shared ForkJoinPool.commonPool() (or a new thread per task on a machine where that pool has fewer than two threads).

To read the result, call join() (throws an unchecked CompletionException on failure) or get() (throws the checked ExecutionException, like any Future). Most code that uses CompletableFuture prefers join() because it works inside lambdas.

Java supplyAsync, thenApply, thenAccept

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The main thread printed its line before the "network call" finished: nothing blocked until join(). The thenAccept step ran on io-1, the thread that completed name. That's the rule for the non-Async methods: a dependent step runs on whichever thread completes the previous stage, or immediately on the calling thread if that stage is already complete.

The chaining methods

Every chaining method returns a new CompletableFuture, so you build pipelines step by step. The names follow a pattern based on the functional interface they take (Functional Interfaces):

Method Takes Result Like
thenApply(fn) Function<T, U> CompletableFuture<U> Stream.map
thenAccept(consumer) Consumer<T> CompletableFuture<Void> forEach
thenRun(runnable) Runnable (ignores the value) CompletableFuture<Void>
thenCompose(fn) Function<T, CompletionStage<U>> CompletableFuture<U> Stream.flatMap
thenCombine(other, bifn) another stage + BiFunction<T, U, V> CompletableFuture<V> zip

Each also has an ...Async variant (thenApplyAsync, thenComposeAsync, and so on) that runs the step as a new task on the default pool or an executor you pass, instead of on the completing thread. Use the Async variant when a step is slow, so it doesn't hijack the thread of the previous stage.

thenCompose vs thenApply

If your function itself returns a CompletableFuture, thenApply gives you a nested CompletableFuture<CompletableFuture<U>>. thenCompose flattens it, which is what you want when one async call depends on another's result.

thenCombine: two independent results

thenCombine waits for two futures that run in parallel and merges their results. The next example uses both: fetching an order depends on the user (compose), while the exchange rate is independent and runs at the same time (combine).

Java thenCompose and thenCombine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rate loads at about 300 ms while the user-then-order chain is still running, and the whole thing finishes at about 400 ms instead of the 700 ms a sequential version would take. The time column is rounded to 50 ms, so small scheduling differences don't show, but on a very busy machine the numbers can still drift.

Waiting for many futures: allOf and anyOf

CompletableFuture.allOf(f1, f2, ...) returns a CompletableFuture<Void> that completes when all inputs are done. It carries no values, so the usual pattern is to wait for it, then join() each input (which no longer blocks). anyOf(...) completes with the result of whichever input finishes first, typed as Object.

Java allOf and anyOf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The south shop answers first, so anyOf returns 95; then allOf waits for the slowest one (north, 300 ms) before the minimum is computed. Note the toArray(new CompletableFuture[0]): allOf and anyOf take varargs arrays, which is a little clumsy with lists.

If any input of allOf fails, the combined future fails too, but only after all inputs have finished. anyOf fails if the first input to complete fails, even when others would have succeeded.

Handling errors

When a step throws, the exception skips every following thenApply/thenAccept/thenCompose stage, just like an exception skipping lines in normal code, until it reaches a stage that handles errors:

Method Called when Can change the result?
exceptionally(ex -> value) only on failure yes: returns a fallback value
handle((value, ex) -> result) always; one of the two is null yes: maps both cases to a result
whenComplete((value, ex) -> ...) always no: for logging/cleanup, the original outcome passes through
exceptionallyCompose(ex -> future) only on failure (Java 12) yes: recover with another async call
Java exceptionally, handle and whenComplete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three details from that run are worth remembering:

  • The error inside the pipeline arrives wrapped in a CompletionException; the real exception is getCause(). Write handlers that unwrap it (or check both) instead of testing ex instanceof NumberFormatException directly.
  • join() throws CompletionException, while get() would throw ExecutionException. Either way, the original is the cause.
  • whenComplete didn't swallow the failure: logged is still failed. Only exceptionally, handle and exceptionallyCompose recover.

Timeouts and manual completion

Async calls can hang. Java 9 added two timeout methods:

  • orTimeout(time, unit) fails the future with a TimeoutException if it isn't done in time.
  • completeOnTimeout(value, time, unit) completes it with a default value instead.

You can also create a CompletableFuture yourself and complete it from any thread with complete(value) or completeExceptionally(ex). That's how you adapt callback-based APIs to futures. CompletableFuture.completedFuture(value) and failedFuture(ex) create already-finished futures, which are handy in tests.

Java Timeouts and completing by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Interesting detail: with orTimeout, the exceptionally handler received a raw TimeoutException, not one wrapped in CompletionException, because the timeout completed this very future exceptionally rather than passing an error down from an earlier stage. That's another reason to unwrap defensively. Also note that neither timeout method stops the slow task; it keeps running in the background. CompletableFuture.cancel(true) doesn't interrupt the running task either: it only marks the future as cancelled.

Pitfalls professionals know

  • Forgetting to wait. The common pool uses daemon threads. If main returns before your pipeline finishes, the JVM can exit and the work never completes. Join at the edge of your program (or let a framework do it).
  • Blocking inside async steps on the common pool. The common pool is shared by parallel streams and every supplyAsync without an executor, and it has about one thread per core. Slow, blocking calls (HTTP, JDBC, Thread.sleep) there starve everyone else. Pass your own executor for I/O, or use virtual threads (Virtual Threads).
  • Lost exceptions. A failed future that nobody joins or handles fails silently. End pipelines with exceptionally, handle or whenComplete that logs.
  • join() in the middle of a pipeline. Calling join() inside a thenApply to get another future's value blocks a pool thread; use thenCompose or thenCombine instead.
  • Assuming which thread runs a step. Non-Async steps may run on the completing thread or the caller. Don't rely on thread identity, ThreadLocals or locks held by the caller.

For coordinating threads that don't pass results along (wait until N things happen, let at most N in at once), see the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. getUser() returns CompletableFuture<User> and getOrders(User) returns CompletableFuture<List<Order>>. Which call gives a CompletableFuture<List<Order>>?

    thenCompose flattens a function that returns a future. thenApply would produce CompletableFuture<CompletableFuture<List<Order>>>.
  2. 2. What does this print? CompletableFuture.supplyAsync(() -> 1 / 0).thenApply(x -> x + 1).exceptionally(ex -> -1).thenApply(x -> x * 10).join()

    The division fails, so the first thenApply is skipped; exceptionally recovers with -1, and the last thenApply runs normally on -1, giving -10.
  3. 3. Which method lets you log both successes and failures without changing the outcome of the future?

    whenComplete observes the value or exception and passes the original outcome through. handle and exceptionally replace the result; thenAccept runs only on success.
  4. 4. You call f.orTimeout(1, TimeUnit.SECONDS) on a future whose task hangs. What happens to the task after the timeout?

    Timeouts complete the future with TimeoutException but never stop the underlying work. Design tasks to time out or check for interruption themselves.
  5. 5. Three futures take 100, 200 and 300 ms and run in parallel. About how long does CompletableFuture.allOf(a, b, c).join() take?

    allOf completes when the last input finishes. Running in parallel, that's the slowest one, about 300 ms.

Summary

  • CompletableFuture lets you describe what to do when a result arrives instead of blocking for it.
  • Start with supplyAsync/runAsync, preferably with your own executor for I/O; finish with join() (or get()).
  • thenApply transforms, thenAccept/thenRun consume, thenCompose chains a dependent async call, thenCombine merges two parallel results; ...Async variants run steps as separate tasks.
  • allOf waits for all inputs (then join each), anyOf takes the first to finish.
  • Exceptions skip normal steps until exceptionally, handle or exceptionallyCompose recovers; whenComplete only observes. Errors usually arrive wrapped in CompletionException.
  • orTimeout and completeOnTimeout bound waiting but don't stop the work; complete/completeExceptionally finish a future by hand.

Next: CountDownLatch, CyclicBarrier, Semaphore and Phaser, the tools for making threads wait for each other.