Stop 12 · Multithreading & JVM InternalsTopics · 6/9

CompletableFuture

Part of the Java Roadmap

In short

A Future makes you wait with get(). CompletableFuture lets you say what should happen next, so a checkout page can fetch the cart, the offers and the delivery date at once and combine them when ready.

CompletableFuture lets you compose asynchronous tasks: run them in the background, chain steps with thenApply and thenCompose, combine results and handle errors without blocking.

The jaadu sits relaxed at a food court table holding two buzzing pagers, one in each hand, while two counters in the background prepare a dosa and a glass of juice.

Think of it like this

The food court buzzer

At a mall food court you order a dosa and a juice at two counters, get two buzzers and go sit down. You don't stand staring at the counter. When both buzz, you collect them and eat together. Each buzzer is a CompletableFuture, and "when both buzz, eat" is thenCombine.

Watch it happen

An order summary built without blocking

supplyAsync
thenApply
thenCombine
exceptionally
join

1/5Start two tasks in the background: load the cart and load the offers.

The big ideas

What you need to know

supplyAsync

Runs a Supplier on a background pool and returns a CompletableFuture. Pass your own executor for I/O work.

thenApply vs thenCompose

thenApply maps the value. thenCompose chains a step that itself returns a CompletableFuture, avoiding nested futures.

Combine results

thenCombine joins two futures. allOf waits for many. anyOf takes the first to finish.

Handle errors

exceptionally gives a fallback value. handle sees both the result and the exception.

See it in code

Walk through the code

java
1import java.util.concurrent.*;2 3public class Checkout {4    public static void main(String[] args) {5        ExecutorService io = Executors.newFixedThreadPool(4);6 7        CompletableFuture<Integer> subtotal =8            CompletableFuture.supplyAsync(() -> loadCart("u42"), io)9                             .thenApply(cart -> cart * 2);10 11        CompletableFuture<Integer> discount =12            CompletableFuture.supplyAsync(() -> loadOffer("u42"), io)13                             .exceptionally(ex -> 0);14 15        int total = subtotal16            .thenCombine(discount, (s, d) -> s - d)17            .join();18 19        System.out.println("Pay ₹" + total);20        io.shutdown();21    }22 23    static int loadCart(String user)  { return 750; }24    static int loadOffer(String user) { throw new RuntimeException("offers down"); }25}

1/4A dedicated pool for I/O calls instead of the shared common pool.

Prints Pay ₹1500: the offers call fails, so the discount falls back to 0.

Save yourself the pain

Common mistakes

Oops

Using thenApply with a function that returns a CompletableFuture.

Do this instead

You get CompletableFuture<CompletableFuture<T>>. Use thenCompose to flatten it.

Oops

Running blocking I/O on the default ForkJoinPool.commonPool().

Do this instead

Pass your own executor as the second argument to supplyAsync so slow calls don't starve other work.

Oops

Calling get() or join() after every step.

Do this instead

Chain the steps and block once at the edge, or not at all in a reactive flow.

Your mission

Travel booking page

~30 min

Quick check

Your next step returns CompletableFuture<User>. Which method should you chain?

Go deeper

  1. 1Run two tasks asynchronously and combine their results with thenCombine.
  2. 2Handle a failure with exceptionally() or handle().
  3. 3Wait for many futures with CompletableFuture.allOf().

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge