Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    CompletableFuture: Asynchronous Pipelines

    A CompletableFuture<T> is a Future you can chain: attach what should happen next, without blocking a thread while waiting.

    Chapter 10 of 124 min read

    The Plain Picture#

    Ordering a meal kit: "When the vegetables and the spices both arrive, combine them into a recipe box, then label it. If the spice supplier fails, use the house spice mix. If nothing arrives in 10 minutes, cancel." You describe the plan up front; the steps run as things arrive, without you standing and waiting at each one.

    The Real Names#

    • A CompletableFuture<T> is a Future you can chain: attach what should happen next, without blocking a thread while waiting.

    • Start: supplyAsync(supplier, executor) (returns a value), runAsync(runnable, executor).

    • Chain: thenApply(f) (transform the result — like map), thenCompose(f) (when f itself returns a future — like flatMap, Modern Java Ch 5), thenAccept(consumer), thenCombine(other, f) (wait for two), allOf(...) / anyOf(...).

    • Errors: exceptionally(f) (fallback value), handle((result, ex) -> ...), whenComplete(...).

    • Timeouts (Java 9+): orTimeout(t, unit), completeOnTimeout(value, t, unit).

    • Finish: join() (waits; throws unchecked CompletionException) or get() (checked exceptions).

    Under the Hood#

    Two 300 ms calls in parallel, then combined:

    Java
    CompletableFuture<String> notes = CompletableFuture.supplyAsync(() -> {
        sleep(300);
        return "notes";
    }, pool);
    
    CompletableFuture<String> history = CompletableFuture.supplyAsync(() -> {
        sleep(300);
        return "history";
    }, pool);
    
    String quiz = notes
        .thenCombine(history, (n, h) -> "quiz from " + n + " + " + h)
        .thenApply(String::toUpperCase)
        .join();
    // QUIZ FROM NOTES + HISTORY in 307 ms          ← not 600: both calls waited at the same time

    Fallback on failure:

    Java
    CompletableFuture.supplyAsync(() -> {
        throw new IllegalStateException("AI API down");
    }, pool)
        .exceptionally(ex -> "fallback quiz (" + ex.getCause().getMessage() + ")")
        .join();
    // fallback quiz (AI API down)

    Timeouts:

    Java
    CompletableFuture.supplyAsync(() -> {
        sleep(2000);
        return "slow";
    }, pool)
        .orTimeout(200, TimeUnit.MILLISECONDS)
        .join();
    // timeout: TimeoutException          (wrapped in a CompletionException)

    Always pass your own executor to the ...Async methods. Without one, they use the shared ForkJoinPool.commonPool() — sized for CPU work (cores − 1 threads) and shared with parallel streams (Modern Java Ch 7). Blocking I/O in it starves everything else in the application.

    Every call to an external service needs a timeout. A hung AI API without one ties up a thread forever; enough of them and the server stops responding. This "fan out, combine, fall back, time out" shape is the heart of backend service code (Microservices and Service Communication (coming soon)).

    Check yourself

    4 questions
    1

    thenApply vs thenCompose?

    Show answer

    thenApply transforms the result with a plain function; thenCompose chains a function that itself returns a CompletableFuture (flattening it).

    2

    Why did the combined quiz take ~300 ms, not ~600 ms?

    Show answer

    Both calls ran concurrently on the pool, and thenCombine waited for both.

    3

    Why pass a custom executor to supplyAsync?

    Show answer

    The default common pool is small and shared (including by parallel streams); blocking tasks there starve other work.

    4

    How do you give a slow call a deadline?

    Show answer

    orTimeout(t, unit) (fail) or completeOnTimeout(fallback, t, unit) (default value).