Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CompletableFuture: composition, timeouts, and executors

Compose stages in Java SE 21, recover from failures, coordinate multiple futures, and explicitly choose executors for asynchronous work.

Version: Java SE 21

Syntax

import java.util.concurrent.CompletableFuture;

CompletableFuture.completedFuture(value)
future.thenApply(value -> mappedValue)
future.thenCompose(value -> nextStage)
future.thenCombine(otherStage, (left, right) -> combinedValue)
future.completeExceptionally(cause)
future.exceptionally(cause -> fallbackValue)
CompletableFuture.allOf(future1, future2)
CompletableFuture.anyOf(future1, future2)
future.completeOnTimeout(fallbackValue, timeout, unit)
future.orTimeout(timeout, unit)
CompletableFuture.supplyAsync(() -> value)
CompletableFuture.supplyAsync(() -> value, io)
future.thenApplyAsync(value -> mappedValue)
future.thenApplyAsync(value -> mappedValue, cpu)
future.join()

CompletableFuture is in java.util.concurrent. The static completedFuture(value) creates an already successful future. thenApply maps a successful result to a value in a new stage. Use thenCompose when the function returns a CompletionStage: the new stage follows that stage's outcome instead of holding the stage itself as a value. thenCombine runs its function with two results only when both stages succeed; it does not start either stage.

completeExceptionally(cause) fails the same future and returns true only if that call completed it. exceptionally creates a new stage that passes through a successful result or computes a fallback from the exception. join() blocks if needed and returns the result, throws an unchecked CompletionException for failure, or throws CancellationException if the future was cancelled. Prefer joining at the program boundary rather than blocking workers inside a chain.

The static allOf returns a CompletableFuture<Void> that waits for every input to finish, even if one fails; it fails if any input fails and does not collect values. After success, read the inputs individually. With no inputs it is already completed with null. The static anyOf returns a CompletableFuture<Object> that completes with an input's result or exception when that input's completion is observed. If several inputs are already complete when anyOf is called, the API does not guarantee that it will select the one that completed earliest. It neither waits for a success nor cancels the other inputs. With no inputs it remains incomplete.

If the future is still incomplete when the timeout expires, completeOnTimeout(value, timeout, unit) completes it normally with the fallback value, whereas orTimeout(timeout, unit) fails it with TimeoutException. Both methods date from Java 9, configure and return the same future, leave any already established outcome unchanged, and do not interrupt the computation. The timeout applies to completion of the future, not just to a caller waiting in join().

supplyAsync(supplier, io) runs the supplier via io, and thenApplyAsync(fn, cpu) runs the transformation via cpu after success. Later stages do not inherit these executors. Without an explicit Executor, standard CompletableFuture uses ForkJoinPool.commonPool(), or a new thread per task if the pool cannot support parallelism of at least two. Subclasses can override the default for instance methods. Non-Async methods such as thenCombine promise no particular executor or thread and can run inline when inputs are ready. To specify an executor for the combination, use thenCombineAsync(other, fn, executor).

Examples

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        var composed = CompletableFuture.completedFuture(2)
                .thenApply(n -> n + 1)
                .thenCompose(n -> CompletableFuture.completedFuture(n * 2))
                .thenCombine(CompletableFuture.completedFuture(4), Integer::sum);
        System.out.println("composed=" + composed.join());

        var failed = new CompletableFuture<Integer>();
        failed.completeExceptionally(new IllegalStateException("unavailable"));
        System.out.println("recovered=" + failed.exceptionally(error -> -1).join());

        var ready = CompletableFuture.completedFuture("ready");
        var pending = new CompletableFuture<String>();
        System.out.println("any=" + CompletableFuture.anyOf(ready, pending).join());
        var all = CompletableFuture.allOf(ready, pending);
        pending.complete("done");
        all.join();
        System.out.println("all=" + ready.join() + "," + pending.join());

        var fallback = new CompletableFuture<Integer>();
        var same = fallback.completeOnTimeout(0, 10, TimeUnit.MILLISECONDS);
        System.out.println("fallback=" + same.join() + ", same=" + (same == fallback));
        var deadline = new CompletableFuture<Integer>();
        try {
            deadline.orTimeout(10, TimeUnit.MILLISECONDS).join();
        } catch (CompletionException error) {
            System.out.println("timeout=" + error.getCause().getClass().getSimpleName());
        }

        try (var io = Executors.newSingleThreadExecutor();
             var cpu = Executors.newSingleThreadExecutor()) {
            var loaded = CompletableFuture.supplyAsync(() -> 7, io);
            var offset = CompletableFuture.supplyAsync(() -> 3, io);
            var total = loaded.thenApplyAsync(n -> n * 2, cpu)
                    .thenCombine(offset, Integer::sum);
            System.out.println("async=" + total.join());
        }
    }
}

Result

composed=10
recovered=-1
any=ready
all=ready,done
fallback=0, same=true
timeout=TimeoutException
async=17

Most stages in the first composition use already available results. The timeout futures have no producers, so the result does not depend on a race against a computation. `io` and `cpu` are separate demonstration executors; try-with-resources closes both. Do not assume a particular elapsed time or a thread for `thenCombine`.

Related lessons

  • Java · Lesson 41 · Advanced · Version: 2
  • Java · Lesson 42 · Advanced · Version: 2

Sources