00:00

CompletableFuture in Java 8

Last updated: · Standard (Java 8)

CompletableFuture is a Future that you can chain, combine and complete. Introduced in Java 8 as part of JEP 155, it lets you describe asynchronous work as a pipeline of steps instead of blocking a thread while you wait.

This tutorial covers starting async tasks, chaining and combining results, waiting for many tasks, and handling errors.

1. Why Was CompletableFuture Added?

A plain Future from an ExecutorService offers only get(), which blocks. You cannot say "when this finishes, do that", combine two futures, or handle an error without blocking a thread. CompletableFuture adds callbacks for all of these, which makes it practical to run independent remote calls in parallel and merge their results.

2. Key Methods

MethodWhat it does
supplyAsync(supplier[, executor])runs a task that returns a value
thenApply(fn)transforms the result
thenCompose(fn)chains another async step that returns a CompletableFuture
thenCombine(other, fn)combines two independent results
allOf(...) / anyOf(...)waits for all / the first of many futures
exceptionally(fn)replaces a failure with a fallback value
handle(fn)receives either the result or the exception
join()waits and returns the result (unchecked exceptions)

3. Practical Examples

Example 1: Two calls in parallel, combined

The price and the tax rate are fetched at the same time on a two-thread pool, so the total wait is about the longer of the two calls, not their sum.

AsyncPipeline.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncPipeline {
    static int fetchPrice(String item) {
        sleep(200);                                   // pretend this is a remote call
        return item.equals("laptop") ? 55000 : 1200;
    }

    static double fetchTaxRate() {
        sleep(150);
        return 0.18;
    }

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

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        // Two independent calls run at the same time
        CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> fetchPrice("laptop"), pool);
        CompletableFuture<Double> tax = CompletableFuture.supplyAsync(AsyncPipeline::fetchTaxRate, pool);

        // thenCombine waits for both; thenApply transforms the result
        CompletableFuture<String> invoice = price
                .thenCombine(tax, (p, t) -> p * (1 + t))
                .thenApply(total -> String.format("Total with tax: %.2f", total));

        System.out.println(invoice.join());           // join() waits for the result
        pool.shutdown();
    }
}
Output
Total with tax: 64900.00

Example 2: Many tasks and error handling

Each SKU lookup runs asynchronously. exceptionally turns a failed lookup into a readable value, allOf waits for every task, and handle shows the alternative that sees both outcomes.

ErrorsAndAllOf.java
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class ErrorsAndAllOf {
    static String loadStock(String sku) {
        if (sku.startsWith("X")) {
            throw new IllegalStateException("unknown SKU " + sku);
        }
        return sku + "=in stock";
    }

    public static void main(String[] args) {
        List<String> skus = Arrays.asList("A100", "X999", "B200");

        // One future per SKU; exceptionally() turns a failure into a fallback value
        List<CompletableFuture<String>> futures = skus.stream()
                .map(sku -> CompletableFuture.supplyAsync(() -> loadStock(sku))
                        .exceptionally(ex -> sku + "=error (" + ex.getCause().getMessage() + ")"))
                .collect(Collectors.toList());

        // allOf completes when every future has completed
        CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join();

        futures.stream().map(CompletableFuture::join).forEach(System.out::println);

        // handle() sees either the result or the exception
        String status = CompletableFuture.supplyAsync(() -> loadStock("X1"))
                .handle((value, ex) -> ex == null ? value : "handled: " + ex.getCause().getClass().getSimpleName())
                .join();
        System.out.println(status);
    }
}
Output
A100=in stock
X999=error (unknown SKU X999)
B200=in stock
handled: IllegalStateException

The exception passed to these callbacks is a CompletionException that wraps the original one, which is why the example calls getCause().

4. How the Pipeline Runs

Two async tasks combined into one result Two supplyAsync tasks fetch the price and the tax rate in parallel. thenCombine runs when both finish, thenApply formats the invoice, and join returns it to the main thread. 2 x supplyAsync price and tax in parallel thenCombine waits for both thenApply formats the invoice join() main thread reads it
Figure 1: Each step runs when the previous one completes; only the final join() waits.

5. Important Points and Best Practices

  • Without an executor argument, async methods use the shared ForkJoinPool.commonPool(). Pass your own executor for blocking I/O.
  • Always end a chain with error handling (exceptionally or handle), or failures may go unnoticed.
  • Use thenCompose, not thenApply, when the next step itself returns a CompletableFuture.
  • Prefer join() in streams because it throws unchecked exceptions; get() throws checked ones.
  • Shut down executors you create, as the example does.

6. Summary

  • CompletableFuture was added in Java 8 (JEP 155) for composable async code.
  • Start tasks with supplyAsync; chain with thenApply and thenCompose.
  • Combine results with thenCombine and allOf.
  • Handle failures with exceptionally or handle.

Related Tutorials

7. References