JAVA-240 · Lesson 7 of 12 · 22 min

Futures and CompletableFuture

▶ Video coming soon A video version of this lesson is on the way.

Monday, February 28, 2028, the first session after the reading week. Over the break Hamza sketched what OrderDesk must do for each web order: look up the customer's account, look up each part's price with the supplier, check the shop's stock, and, if the order includes a repair, find a free slot on Tamsin's rack. Some of those steps depend on each other and some do not. With plain futures from lesson 6, every step that needs an earlier result has to call get and wait, tying up a thread. CompletableFuture lets him describe the whole chain of steps instead, and lets Java run each step as soon as what it needs is ready.

What a plain Future cannot do

A Future is a placeholder for a result, but the only way to use the result is to call get, which blocks the calling thread until the result exists. You cannot tell a plain Future to do something when it finishes, you cannot combine two of them without waiting on both, and you cannot complete one yourself. Waiting is fine in main, but inside a pool it wastes a worker: a thread blocked in get is a thread not doing any other work.

Waiting forever is the other danger. A supplier that hangs will make get hang too. The timed version of get is the simplest protection: it waits up to a limit and then throws TimeoutException, and the caller can decide to cancel the task and use a fallback.

Java Example · Main.java
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
            Future<Integer> slowSupplier = pool.submit(() -> {
                Thread.sleep(5_000);
                return 899;
            });

            try {
                System.out.println("price: " + slowSupplier.get(200, TimeUnit.MILLISECONDS));
            } catch (TimeoutException e) {
                System.out.println("no answer in 200 ms, using the last known price");
                slowSupplier.cancel(true);
            } catch (ExecutionException e) {
                System.out.println("lookup failed: " + e.getCause());
            }
            System.out.println("future stopped by cancel? " + slowSupplier.isCancelled());
        }
    }
}
Output
no answer in 200 ms, using the last known price
future stopped by cancel? true

What this code does

The supplier task would take five seconds, but main waits for at most 200 milliseconds and then gives up with TimeoutException. It cancels the task with cancel(true), which interrupts the sleeping worker so the pool can close at once. The program reports that it used a fallback and that the future is cancelled.

CompletableFuture

CompletableFuture, in java.util.concurrent since Java 8, is a Future you can build on. It represents a stage of work that will complete, normally with a value or exceptionally with an exception, and it lets you attach further stages that run when it completes. You describe what should happen, and the library runs each stage when its inputs are ready, without any thread sitting in get.

The usual way to start is supplyAsync, which runs a Supplier, a task with no input that returns a value, on an executor and returns a CompletableFuture for its result. If you do not pass an executor, it uses the shared common ForkJoinPool, which is sized for CPU-bound work. For tasks that wait on networks, pass your own executor; you will see why in the next lesson.

Java Example · Main.java
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            CompletableFuture<Integer> centsEach = CompletableFuture.supplyAsync(() -> 1499, pool);

            CompletableFuture<String> line = centsEach
                    .thenApply(cents -> cents * 2)
                    .thenApply(cents -> String.format("2 x PAD-ROAD = %d.%02d", cents / 100, cents % 100));

            System.out.println(line.join());
        }
    }
}
Output
2 x PAD-ROAD = 29.98

What this code does

supplyAsync starts the price lookup on the pool, and two thenApply stages transform its result: first doubling it for two pads, then formatting it as a line of text. Each stage runs when the stage before it completes. join waits for the final stage and returns its value; it is like get but throws an unchecked exception if something failed.

The method names follow a pattern that is worth learning once. thenApply transforms a result into another result. thenAccept consumes a result and returns nothing, and thenRun runs an action that does not need the result. Each has an Async version, such as thenApplyAsync, that runs the stage as a new task on an executor instead of on whichever thread completed the previous stage.

The most used CompletableFuture methods
MethodTakesGivesUse it to
thenApply(f)The resultA new resultTransform a value, such as cents to a formatted line
thenAccept(c)The resultNothingUse a value, such as add it to a log
thenRun(r)NothingNothingDo something after, such as mark a step done
thenCompose(f)The resultAnother CompletableFuture, flattenedStart a second asynchronous step that needs the first result
thenCombine(other, f)Two resultsA new resultJoin two independent lookups
allOf(...)Several futuresA future that completes when all haveWait for a batch
exceptionally(f)The exceptionA replacement resultRecover from a failure
handle(f)The result or the exceptionA new resultDeal with success and failure in one place

Chaining dependent steps: thenCompose

Some steps start another asynchronous step. Looking up an order's customer gives an account number, and the account number is needed to look up the customer's discount, which is itself a slow call. With thenApply the function would return a CompletableFuture, and you would end up with a future of a future. thenCompose flattens that: its function returns a CompletableFuture, and thenCompose gives back a single future for the final result. Think of thenApply as map and thenCompose as flatMap, if you met those words with streams.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.*;

public class Main {
    static final Map<String, String> accounts = Map.of("ord-1041", "acct-77", "ord-1042", "acct-12");
    static final Map<String, Integer> discountPercent = Map.of("acct-77", 10, "acct-12", 0);

    static CompletableFuture<String> findAccount(String order, Executor ex) {
        return CompletableFuture.supplyAsync(() -> accounts.get(order), ex);
    }

    static CompletableFuture<Integer> findDiscount(String account, Executor ex) {
        return CompletableFuture.supplyAsync(() -> discountPercent.get(account), ex);
    }

    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            for (String order : List.of("ord-1041", "ord-1042")) {
                CompletableFuture<Integer> discount = findAccount(order, pool)
                        .thenCompose(account -> findDiscount(account, pool));
                System.out.println(order + " discount: " + discount.join() + " in 100");
            }
        }
    }
}
Output
ord-1041 discount: 10 in 100
ord-1042 discount: 0 in 100

What this code does

findAccount and findDiscount each return a CompletableFuture, and the discount lookup needs the account number. thenCompose chains them so that the discount lookup starts as soon as the account is known, and the result is one CompletableFuture of an Integer rather than a future inside a future. The program prints each order's discount once its two lookups have finished.

Combining independent steps

Other steps are independent and can run at the same time. The price of a part and the shop's stock of it come from different places, and neither needs the other. thenCombine runs when both of two futures have completed and passes both results to a function. For a whole batch, CompletableFuture.allOf returns a future that completes when every future in an array has, after which each one's join returns at once.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.*;

public class Main {
    static int supplierCents(String code) {
        sleep(150);
        return Map.of("TUBE-700x25", 899, "CHAIN-11", 3999, "BELL", 1250).get(code);
    }

    static int shelfCount(String code) {
        sleep(100);
        return Map.of("TUBE-700x25", 14, "CHAIN-11", 0, "BELL", 3).get(code);
    }

    static void sleep(int ms) {
        try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    }

    public static void main(String[] args) {
        List<String> codes = List.of("TUBE-700x25", "CHAIN-11", "BELL");
        try (ExecutorService pool = Executors.newFixedThreadPool(6)) {
            List<CompletableFuture<String>> lines = new ArrayList<>();
            for (String code : codes) {
                CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> supplierCents(code), pool);
                CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> shelfCount(code), pool);
                lines.add(price.thenCombine(stock,
                        (cents, n) -> code + ": " + cents + " cents, " + (n > 0 ? n + " on the shelf" : "order from supplier")));
            }
            CompletableFuture.allOf(lines.toArray(new CompletableFuture[0])).join();
            for (CompletableFuture<String> line : lines) System.out.println(line.join());
        }
    }
}
Output
TUBE-700x25: 899 cents, 14 on the shelf
CHAIN-11: 3999 cents, order from supplier
BELL: 1250 cents, 3 on the shelf

What this code does

For each of three parts, the supplier price and the shelf count are looked up at the same time, and thenCombine joins the two answers into one line when both are ready. allOf waits for all three lines, so the six lookups overlap and the whole batch takes about as long as the slowest single lookup. The lines are printed from the list in order, so the output does not depend on which lookup finished first.

A dependency graph of CompletableFuture stages for one order. Two boxes at the left, supplier price and shelf count, start at the same time and both feed into a box labelled thenCombine: make the line. Three such lines feed into a box labelled allOf, which feeds into a final box labelled print the order. A separate chain at the bottom shows find account, then thenCompose, find discount.
Stages run as soon as their inputs are ready

anyOf is the opposite of allOf: it completes as soon as any one of the futures does, with that future's result. It suits asking two equivalent sources and taking whichever answers first, for instance two mirrors of the supplier's catalogue.

When a stage fails

If a stage throws, its future completes exceptionally, and every stage that depends on it is skipped and completes exceptionally too, carrying the same cause. The failure travels down the chain until a stage that handles exceptions catches it. exceptionally supplies a replacement value when something failed. handle receives both the result and the exception, one of which is null, and returns a value either way. whenComplete lets you look at the outcome, for logging, without changing it. If nothing handles the failure, join throws a CompletionException whose cause is the original exception.

Java Example · Main.java
import java.util.concurrent.*;

public class Main {
    static int price(String code) {
        if (code.startsWith("DISC-")) throw new IllegalArgumentException(code + " is discontinued");
        return 2499;
    }

    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            for (String code : new String[] {"SADDLE-COMFORT", "DISC-DYNAMO"}) {
                String line = CompletableFuture.supplyAsync(() -> price(code), pool)
                        .thenApply(cents -> code + " costs " + cents + " cents")
                        .exceptionally(e -> code + " skipped: " + e.getCause().getMessage())
                        .join();
                System.out.println(line);
            }

            CompletableFuture<Integer> unhandled = CompletableFuture.supplyAsync(() -> price("DISC-HORN"), pool);
            try {
                unhandled.join();
            } catch (CompletionException e) {
                System.out.println("join threw CompletionException caused by " + e.getCause().getClass().getSimpleName());
            }
        }
    }
}
Output
SADDLE-COMFORT costs 2499 cents
DISC-DYNAMO skipped: DISC-DYNAMO is discontinued
join threw CompletionException caused by IllegalArgumentException

What this code does

The first part is priced normally. The second throws inside supplyAsync, so its thenApply stage is skipped and exceptionally turns the failure into a skipped line, using getCause to reach the original message. The third failure is not handled, so join throws a CompletionException that wraps the IllegalArgumentException.

The exception passed to exceptionally and handle is usually a CompletionException wrapping the real one, which is why the example calls getCause. Code that handles errors should therefore unwrap carefully, or simply report getCause when it is present.

Timeouts and completing by hand

Since Java 9, a CompletableFuture can give itself a deadline. orTimeout(duration, unit) completes it exceptionally with a TimeoutException if it has not finished in time. completeOnTimeout(value, duration, unit) completes it with a fallback value instead, which is often exactly what a shop wants: if the supplier does not answer within two seconds, show the last known price. You can also complete a CompletableFuture yourself with complete(value) or completeExceptionally(e), which is how libraries turn callbacks from other systems into futures.

Java Example · Main.java
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            int lastKnownCents = 3899;

            CompletableFuture<Integer> fast = CompletableFuture
                    .supplyAsync(() -> 3999, pool)
                    .completeOnTimeout(lastKnownCents, 2, TimeUnit.SECONDS);

            CompletableFuture<Integer> stuck = CompletableFuture
                    .supplyAsync(() -> {
                        try { Thread.sleep(3_000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                        return 3999;
                    }, pool)
                    .completeOnTimeout(lastKnownCents, 200, TimeUnit.MILLISECONDS);

            System.out.println("fast supplier: " + fast.join());
            System.out.println("stuck supplier: " + stuck.join() + " (last known price)");
        }
    }
}
Output
fast supplier: 3999
stuck supplier: 3899 (last known price)

What this code does

The first lookup answers at once, well inside its two-second limit, so it gives the supplier's current price. The second is stuck, so after 200 milliseconds completeOnTimeout finishes its future with the last known price instead. The stuck task itself keeps sleeping until it ends, which is why the pool takes about three seconds to close: a timeout on the future does not stop the work behind it.

That last point catches many people. Completing a CompletableFuture, by timeout or by hand, does not interrupt the code that was supposed to produce it; even cancel(true) on a CompletableFuture does not interrupt the running task. If the work itself must stop, the task has to check for cancellation itself, or you can run it as a plain Future in an executor, where cancel(true) does interrupt.

Where stages run

A stage added with thenApply runs on whichever thread completes the previous stage, or on the calling thread if the previous stage has already finished. That is efficient, but it means a slow function in thenApply can delay the thread that completed the previous stage. When a stage itself does slow or blocking work, use the Async variant and pass an executor, so that the work is scheduled properly. And never block inside a stage with get or join on another future unless you are sure it is finished; that ties up a thread and, in a small pool, can stop everything.

Try it yourself

Price and stock together

Start two CompletableFutures on a pool: one supplies the price of a pump, 3450 cents, and the other the number on the shelf, 2. Combine them with thenCombine into the text PUMP-FLOOR: 3450 cents, 2 in stock and print it.

The program should print PUMP-FLOOR: 3450 cents, 2 in stock.

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 3450, pool);
            CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> 2, pool);
            String line = "PUMP-FLOOR: ?";
            System.out.println(line);
        }
    }
}

Try it yourself

A fallback for a failed lookup

The lookup of part "GRIP-FOAM" throws IllegalStateException("not in the parts list"). Add an exceptionally stage that turns the failure into -1, then print price: -1 (lookup failed) when the value is negative.

The program should print price: -1 (lookup failed).

import java.util.concurrent.*;

public class Main {
    static int lookUp(String code) {
        throw new IllegalStateException("not in the parts list");
    }

    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
            CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> lookUp("GRIP-FOAM"), pool);
            int cents = 0;
            System.out.println(cents < 0 ? "price: " + cents + " (lookup failed)" : "price: " + cents);
        }
    }
}

Common mistakes

  • MistakeCalling get or join inside a stage to wait for another future.

    InsteadUse thenCompose or thenCombine so the library waits for you.

  • MistakeUsing thenApply when the function returns a CompletableFuture.

    InsteadUse thenCompose, which flattens the nested future.

  • MistakeRunning slow, blocking lookups on the common ForkJoinPool.

    InsteadPass your own executor to supplyAsync and the Async methods for I/O-bound work.

  • MistakeExpecting a timeout or cancel on a CompletableFuture to stop the work behind it.

    InsteadIt only completes the future; the task must check for cancellation itself.

  • MistakeForgetting that failures skip later stages.

    InsteadAdd exceptionally or handle where you want to recover, and unwrap CompletionException with getCause.

Summary and key terms

  • A plain Future can only be waited on with get, ideally with a time limit, and cancelled.
  • CompletableFuture is a stage that completes with a value or an exception and lets you attach further stages. supplyAsync starts work on an executor, or on the common ForkJoinPool if none is given; pass your own executor for I/O-bound work. thenApply transforms a result, thenAccept consumes it and thenRun runs afterwards; Async variants schedule the stage on an executor. thenCompose chains a dependent asynchronous step and flattens the result, while thenCombine joins two independent results and allOf and anyOf wait for a batch or for the first.
  • A failure skips dependent stages until exceptionally, handle or whenComplete deals with it, and an unhandled failure makes join throw CompletionException. orTimeout and completeOnTimeout set deadlines, and complete finishes a future by hand, but none of these stops the work behind the future.
CompletableFuture
A future that can be completed and that lets further stages run when it completes.
Stage
One step of a CompletableFuture pipeline that runs when its input is ready.
supplyAsync
A method that runs a Supplier asynchronously and returns a CompletableFuture for its result.
thenApply
Adds a stage that transforms the result into a new result.
thenCompose
Adds a stage that starts another asynchronous step and flattens the nested future.
thenCombine
Adds a stage that runs when two futures complete and combines their results.
allOf
Returns a future that completes when all of the given futures have completed.
exceptionally
Adds a stage that supplies a replacement result when an earlier stage failed.
CompletionException
The unchecked exception join throws, wrapping the original failure.
Common ForkJoinPool
A shared pool sized for CPU-bound work, used by default for asynchronous stages.
completeOnTimeout
Completes a future with a fallback value if it has not finished in time.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which method should you use when a stage's function returns a CompletableFuture?

    Show answer

    thenCompose.

  2. Two lookups are independent. Which method joins their results?

    Show answer

    thenCombine.

  3. A stage throws. What happens to the thenApply stage after it?

    Show answer

    It is skipped and completes exceptionally with the same cause.

  4. What does join throw if the future failed and nothing handled it?

    Show answer

    CompletionException, with the original exception as its cause.

  5. Does completeOnTimeout stop the slow task?

    Show answer

    No; it completes the future with the fallback, but the task keeps running.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz