skip to content

CompletableFuture Creation

The entry points — completedFuture, supplyAsync, runAsync, and a manually completed future — and the fact that async methods default to the common ForkJoinPool unless you pass an executor. That default is where most CompletableFuture production problems begin.

part ofJavaread it →
on this pageshow

questions

6

What is Java's CompletableFuture, what do Future and CompletionStage each contribute, and what can a plain Future not do?

level: juniorimportance: must knowfreq 72%

answer

  1. reading side, pipeline side, and a third
  2. neither interface can supply a value
  3. block or poll, no callback
  4. Java 19 only added read methods

basics

~20 s

CompletableFuture is a result holder any thread can complete, and it triggers dependent steps when it finishes. Future adds waiting, reading and cancelling; CompletionStage adds those steps. A plain Future has no callbacks, so you poll or block.

solid answer

~50 s

`CompletableFuture<T>`, since Java 1.8, implements `Future<T>` and `CompletionStage<T>`; its Javadoc calls it a `Future` that may be explicitly completed. `Future` (1.5) is the waiting and reading side: `get`, `isDone`, `isCancelled`, `cancel`, and since Java 19 `resultNow`, `exceptionNow` and `state`. `CompletionStage` (1.8) is the pipeline side: `thenApply`, `thenCompose`, `thenCombine`, `handle` and their relatives, each returning a new stage triggered by this one, by both of two stages or by either of two. The part in the name comes from neither interface: `complete` and `completeExceptionally`, like `supplyAsync` and `join`, are the class's own. A plain `Future` offers no way to supply a value or a chosen failure from outside, attach a callback, chain or combine without blocking or polling, or recover from a failure in line; you block in `get()` or poll `isDone()`. That still holds at Java 27, because Java 19's additions only read.

code

java · 17 lines
java
import java.util.concurrent.CompletableFuture;

public class ThreeContributions {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> reply = new CompletableFuture<>(); // nothing is running yet

        // CompletionStage: attach the next step, and no thread waits for it
        CompletableFuture<Integer> length = reply.thenApply(String::length);

        // The class itself: any thread may supply the outcome
        new Thread(() -> reply.complete("hello")).start();

        // Future: block for the value, or ask whether it is finished
        System.out.println(length.get());   // 5
        System.out.println(reply.isDone()); // true
    }
}

go deeper

for a junior

Recall the declaration: it implements Future and CompletionStage. Be able to sort get, thenApply and complete by where each comes from, and say that a plain Future means blocking or polling.

for a middle

Explain that the class holds an outcome and owns no computation, so anyone may complete it and a task submitted elsewhere usually does. Point out that supplying a value comes from the class, not from either interface.

for a senior

Show the API-boundary judgment: returning the class hands callers complete and obtrudeValue, while copy or minimalCompletionStage limits what they can do. Note that get and join still block, so the type alone removes no waiting.

for a principal

Weigh what a team exposes in its signatures. CompletionStage promises less and leaves room to change the implementation, but callers lose get and join until they convert; a shared rule on returned types stops that choice being remade per service.

## What a CompletableFuture is `java.util.concurrent.CompletableFuture<T>`, added in Java 1.8, is declared `public class CompletableFuture<T> implements Future<T>, CompletionStage<T>`. Its Javadoc opens: "A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion." Three terms carry that sentence: - A **future** is an object that stands for a result that may not exist yet. - A **stage** is one step of a possibly asynchronous computation, which acts when another stage completes. - A **dependent** is a stage whose function or action is triggered by the completion of one stage, of both of two, or of either of two. The class holds an outcome and triggers what depends on it. It does not own a thread or a computation: `new CompletableFuture<>()` starts nothing, and the Javadoc says the class "has no direct control over the computation that causes it to be completed". Factories such as `supplyAsync` submit a task to an executor, and that task completes the future. ## What Future contributes `Future`, from Java 1.5, is the waiting and reading side: - `get()` blocks until the outcome exists, `get(long, TimeUnit)` blocks at most for its time limit, and both report a failure as a checked `ExecutionException`. - `isDone()` and `isCancelled()` answer without blocking, which is how you poll. - `cancel(boolean)` asks for cancellation. On this class it is just another form of exceptional completion, and the flag has no effect. - `resultNow()`, `exceptionNow()` and `state()`, added in Java 19, read an outcome without waiting. `resultNow()` throws `IllegalStateException` if the task has not completed or did not complete with a result. Implementing `Future` also means a `CompletableFuture` can be passed to any code that accepts one. ## What CompletionStage contributes `CompletionStage`, from Java 1.8, is the pipeline side. Apart from `toCompletableFuture()`, each method registers a step and returns a new stage, so no thread has to sit waiting for the step before it: - **One input:** `thenApply`, `thenAccept`, `thenRun`, `thenCompose`. - **Two inputs:** `thenCombine`, `thenAcceptBoth`, `runAfterBoth`, `applyToEither`, `acceptEither`, `runAfterEither`. - **Outcome or failure:** `handle`, `whenComplete`, `exceptionally`, and from Java 12 `exceptionallyCompose`. Each also has `...Async` forms, with and without an `Executor`. What each one does belongs with transforming, combining and exception handling. The interface stops there. Its Javadoc says it "does not define methods for initially creating, forcibly completing normally or exceptionally, probing completion status or results, or awaiting completion of a stage". So `get`, `join`, `isDone` and `complete` are not on it, and `toCompletableFuture()` is the bridge back to them. ## What the class adds itself The summary "Future plus CompletionStage" leaves out the part in the name, because neither interface can supply a value or a failure of the caller's choosing. | Comes from | What it gives you | Members | |---|---|---| | `Future` | wait, read, cancel | `get`, `isDone`, `isCancelled`, `cancel`, `resultNow`, `exceptionNow`, `state` | | `CompletionStage` | attach the next step | `thenApply`, `thenCombine`, `handle`, `whenComplete`, `exceptionally`, `toCompletableFuture` | | the class itself | complete from outside, create, read without a checked exception | `complete`, `completeExceptionally`, `orTimeout`, `supplyAsync`, `runAsync`, `completedFuture`, `allOf`, `anyOf`, `join`, `getNow` | `complete(value)` returns `true` only if that call moved the future to a completed state. When several threads attempt it, only one succeeds. ## What a plain Future cannot do `ExecutorService.submit` hands back a `Future`, and a caller holding one learns the outcome by blocking in `get()` or by polling. That leaves these gaps: - **Supply a value or a chosen failure from outside.** The interface has no `complete`; `cancel` is all a holder can force. `FutureTask` has `set` and `setException`, but both are protected. - **Run something when it finishes.** The interface has no way to register a callback. `FutureTask.done()` is a protected hook, so only the code creating the task can override it, and it returns nothing to chain on. - **Chain steps without blocking or polling.** Through the interface, feeding a result into the next asynchronous step means a thread blocks in `get()` or something polls `isDone()`, and then submits that step. The creator of a `FutureTask` can also submit it from `done()`. - **Combine futures you already hold.** Waiting for both means blocking on each in turn or polling; waiting for the first needs polling or one blocked thread per future, because `get()` watches only its own future. `ExecutorService.invokeAll` and `invokeAny` wait on a batch submitted together, and `ExecutorCompletionService` queues futures as they complete, for a caller to `take`. - **Recover in line.** A failure is something a caller reads later; no recovery step can be attached to it. Java 8 added the class and `CompletionStage` beside `Future`, not new methods on it, and Java 19's additions only read. At Java 27 the interface's methods are `cancel`, `exceptionNow`, `get`, `isCancelled`, `isDone`, `resultNow` and `state`, and none supplies a value or registers a callback. JDK 25 declares the same ones. ## What follows in practice - **Returning the class hands callers its completing methods.** They can call `complete` or `obtrudeValue` on your future. `copy()` and `minimalCompletionStage()`, both from Java 9, limit that. - **The type removes no waiting by itself.** `get()` right after `supplyAsync` blocks just as it does on a plain `Future`. The gain comes from attaching the next step instead. - **Cancelling interrupts nothing.** `cancel(true)` completes the future exceptionally and triggers its dependents. A running task is left alone; at JDK 27, a queued `supplyAsync` task whose future is already cancelled never runs its supplier.

  • If an API returns a CompletableFuture, what can its callers do to it, and how do you limit that?
    They can call `complete`, `cancel` or `obtrudeValue` and change the outcome everyone else sees. `copy()`, since Java 9, returns a separate future, so completing the copy leaves yours alone while callers can still attach steps. `minimalCompletionStage()`, also since Java 9, returns a stage its Javadoc says cannot be independently completed, and its `toCompletableFuture()` gives a new future. At JDK 27 a cast followed by `complete` throws `UnsupportedOperationException`, which is implementation rather than contract.
  • Does FutureTask.done() not already give a Future a callback?
    Only to whoever creates the task. `done()` is a protected `FutureTask` method you override in a subclass, it takes no arguments, and it returns nothing to chain on. At JDK 27 it runs on the thread that finishes or cancels the task, which its Javadoc does not promise. Code handed just a `Future`, as `ExecutorService.submit` returns, cannot attach anything.
  • Does creating a CompletableFuture start any work?
    `new CompletableFuture<>()` starts nothing: it is an empty holder until something completes it. `supplyAsync` and `runAsync` start work because they submit a task to an executor, and that task completes the future. The class has no direct control over that computation, which is why `cancel(true)` interrupts nothing.

A plain Future is a repair-shop claim ticket: you can phone to ask whether the job is done, or wait at the counter until it is. A CompletableFuture is a ticket with a list of next errands attached, which get started when the job is done, and anyone holding it can declare the job finished.

  • CompletableFuture runs the task itself on a thread it owns.
  • complete(value) is inherited from the Future interface.
  • CompletionStage is where get() and join() come from.
  • Java 19 gave Future a way to register callbacks through state().
  • FutureTask's protected done() means any holder of a Future can attach a callback.
  • Switching to CompletableFuture makes code non-blocking even if you still call get() on it.

CompletableFuture
Java 1.8
CompletionStage
Java 1.8
Future
Java 1.5
Future.resultNow, exceptionNow and state
Java 19

Assumes Java 27; CompletableFuture and CompletionStage date from 1.8, Future's resultNow, exceptionNow and state from 19, and JDK 25 declares the same public methods.

context

open as a page

What are the main ways to create a CompletableFuture that runs a task asynchronously, and how do supplyAsync and runAsync differ?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Use CompletableFuture.supplyAsync when the task returns a value, and runAsync when it returns nothing. supplyAsync takes a Supplier and gives a CompletableFuture<T>; runAsync takes a Runnable and gives a CompletableFuture<Void>.

open as a page

On which thread pool do supplyAsync and runAsync run by default, and how do you override it?

level: middleimportance: must knowfreq 65%

basics

~20 s

By default they run on the shared ForkJoinPool.commonPool(). Each async method also has an overload that takes an Executor, so you pass your own thread pool as a second argument to control where the task runs.

open as a page

How do you create a CompletableFuture that you complete manually later, and when is that useful?

level: middleimportance: should knowfreq 50%

basics

~10 s

Create an empty future with new CompletableFuture<>(), then call complete(value) when the result arrives, or completeExceptionally(error) on failure. It's useful for bridging callback-based APIs into the CompletableFuture world.

open as a page

If the Supplier passed to CompletableFuture.supplyAsync throws an exception, what happens to the future and to a later get() call?

level: seniorimportance: should knowfreq 55%

basics

~10 s

The exception is captured and the future completes exceptionally—it does not propagate out of supplyAsync. A later get() then throws an ExecutionException whose cause is the thrown exception; join() throws a CompletionException wrapping it.

open as a page

Why might you choose CompletableFuture.supplyAsync over ExecutorService.submit, given both run a task on a thread pool and return a Future?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Both run a task and return a Future, but ExecutorService.submit gives a plain Future you can only block on with get(). supplyAsync returns a CompletableFuture you can chain non-blocking steps onto (thenApply, thenCompose, combine) and add error recovery.

open as a page