Skip to lesson

thenCompose versus thenApply

Real services are often async themselves: findUser(id) already returns a CompletableFuture<User>. To chain such a method you need thenCompose, not thenApply, or you end up with a future inside a future.

Nested CompletableFuture<CompletableFuture<T>>

A nested future is a CompletableFuture<CompletableFuture<T>>: a box inside a box. You get one when the function you pass to thenApply itself returns a CompletableFuture.

Example 1 · thenApply with an async method gives a box in a box

NestedFutureDemo.javaJava
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
public class NestedFutureDemo {    static CompletableFuture<User> findUser(int id) {        return CompletableFuture.supplyAsync(() -> new User(id, "Riya"));    }
    static CompletableFuture<List<String>> fetchOrders(User user) {        return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse"));    }
    public static void main(String[] args) {        CompletableFuture<CompletableFuture<List<String>>> nested =                findUser(7).thenApply(user -> fetchOrders(user));
        Object outerValue = nested.join();        System.out.println("join() gave a " + outerValue.getClass().getSimpleName());        System.out.println("join().join() gave " + nested.join().join());    }}
Output
join() gave a CompletableFuture
join().join() gave [Keyboard, Mouse]

What this code does

  • fetchOrders returns a future, and thenApply wraps it in another future. The type spells it out: CompletableFuture<CompletableFuture<List<String>>>.
  • The first join() gives the inner future, not the orders. Only a second join() reaches the list, and any further thenApply would have to deal with the inner future too.

thenApply wraps whatever the function returns. If the function returns a List, you get a future of a List. If it returns a future of a List, you get a future of a future of a List. To reach the value you would need join().join(), and the next thenApply would receive a future instead of the orders. Writing CompletableFuture<List<String>> orders = findUser(7).thenApply(u -> fetchOrders(u)); fails with incompatible types: inference variable U has incompatible bounds.

Fix the error

Pick the method that compiles

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

fetchOrders returns a future, and the result must be a flat future of the list.

import java.util.List;
import java.util.concurrent.CompletableFuture;
public class NestedFix {
static CompletableFuture<Integer> findUser(int id) { return CompletableFuture.supplyAsync(() -> id); }
static CompletableFuture<List<String>> fetchOrders(int user) {
return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse"));
}
public static void main(String[] args) {
CompletableFuture<List<String>> orders = findUser(7).thenApply(u -> fetchOrders(u));
System.out.println(orders.join());
}
}

Error

NestedFix.java:11: error: incompatible types: inference variable U has incompatible bounds
        CompletableFuture<List<String>> orders = findUser(7).thenApply(u -> fetchOrders(u));
    equality constraints: List<String>
    lower bounds: CompletableFuture<List<String>>

thenCompose flattens like flatMap

thenCompose is a CompletableFuture method for a function that itself returns a future. It chains the two calls and returns one flat CompletableFuture, the way flatMap flattens nested containers.

thenCompose(fn) takes a function that returns a CompletableFuture<U> and gives back a flat CompletableFuture<U>. It is the flatMap of CompletableFuture, just like Optional.flatMap and Stream.flatMap.

Java
// map wraps the result, flatMap does not wrap it a second timeOptional<Optional<Address>> a = user.map(User::address);         // address() returns OptionalOptional<Address> b = user.flatMap(User::address);
CompletableFuture<CompletableFuture<List<String>>> c = findUser(7).thenApply(u -> fetchOrders(u));CompletableFuture<List<String>> d = findUser(7).thenCompose(u -> fetchOrders(u));

The rule is short: if the function returns a plain value, use thenApply; if it returns a future, use thenCompose. The future from thenCompose completes when the inner future completes, with the inner future's value.

Left: thenApply with a function that returns a future gives a nested future, a CompletableFuture inside a CompletableFuture holding the List, so join() returns the inner future. Right: thenCompose gives one flat CompletableFuture holding the List, so join() returns the list.

Example 2 · thenCompose gives a flat future

ThenComposeDemo.javaJava
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
public class ThenComposeDemo {    static CompletableFuture<User> findUser(int id) {        return CompletableFuture.supplyAsync(() -> new User(id, "Riya"));    }
    static CompletableFuture<List<String>> fetchOrders(User user) {        return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse"));    }
    public static void main(String[] args) {        CompletableFuture<List<String>> orders = findUser(7).thenCompose(user -> fetchOrders(user));
        CompletableFuture<Integer> count = orders.thenApply(list -> list.size());        System.out.println("Orders: " + orders.join());        System.out.println("Count: " + count.join());    }}
Output
Orders: [Keyboard, Mouse]
Count: 2

What this code does

  • Same two methods, one word changed. thenCompose returns CompletableFuture<List<String>>, so one join() gives the list.
  • Because the future is flat, the next step thenApply(list -> list.size()) receives the real list and can call size() on it.

Dependent calls: find user, then fetch orders

A dependent call is a call that needs the result of an earlier call as its input. You cannot fetch Riya's orders before you know Riya's user id, so the two calls must run one after the other.

Example 3 · Three dependent calls: token, user, orders

DependentCallsDemo.javaJava
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
record Order(String item, int price) {}
public class DependentCallsDemo {    static CompletableFuture<Integer> userIdForToken(String token) {        return CompletableFuture.supplyAsync(() -> {            System.out.println("Looking up session token " + token);            return 7;        });    }
    static CompletableFuture<User> findUser(int id) {        return CompletableFuture.supplyAsync(() -> {            System.out.println("Found user Riya (id " + id + ")");            return new User(id, "Riya");        });    }
    static CompletableFuture<List<Order>> fetchOrders(User user) {        return CompletableFuture.supplyAsync(() -> {            System.out.println("Fetching orders of " + user.name());            return List.of(new Order("Keyboard", 320), new Order("Mouse", 120),                    new Order("Headset", 200));        });    }
    public static void main(String[] args) {        CompletableFuture<String> summary = userIdForToken("abc123")                .thenCompose(id -> findUser(id))                .thenCompose(user -> fetchOrders(user))                .thenApply(orders -> "Riya has " + orders.size() + " orders, total Rs "                        + orders.stream().mapToInt(Order::price).sum());
        System.out.println(summary.join());    }}
Output
Looking up session token abc123
Found user Riya (id 7)
Fetching orders of Riya
Riya has 3 orders, total Rs 640

What this code does

  • Each service needs the previous answer: the id needs the token, the user needs the id, the orders need the user. thenCompose starts each call only when its input is ready, so the log lines always come in this order.
  • The last step builds a plain String, so it is a thenApply. The summary is the only value main waits for.

thenCompose says exactly that: "when the user arrives, start the order call with it". No thread sits blocked in between; the second call simply starts when the first one finishes. When calls do not depend on each other, running them one after the other wastes time. The next lesson shows how to run independent calls side by side.

Reading long chains

A long chain is easy to read when you know the type after each step. Write one call per line and, while learning, add the type as a comment.

Example 4 · A long chain, with the type after each step

LongChainDemo.javaJava
import java.util.concurrent.CompletableFuture;
record Passenger(String pnr, String name, String train) {}
public class LongChainDemo {    static CompletableFuture<Passenger> findPassenger(String pnr) {        return CompletableFuture.supplyAsync(() -> new Passenger(pnr, "meera iyer", "12627"));    }
    static CompletableFuture<String> seatFor(String train, String pnr) {        return CompletableFuture.supplyAsync(() -> "B2-41");    }
    public static void main(String[] args) {        CompletableFuture<String> sms = CompletableFuture                .supplyAsync(() -> "  4521897630 ")                .thenApply(String::trim)                  // CF<String>     plain value -> thenApply                .thenCompose(pnr -> findPassenger(pnr))   // CF<Passenger>  returns a future -> thenCompose                .thenCompose(p -> seatFor(p.train(), p.pnr())  // CF<String>  needs p and the seat                        .thenApply(seat -> p.name().toUpperCase() + ", train " + p.train() + ", seat " + seat))                .thenApply(text -> "SMS: " + text);
        System.out.println(sms.join());    }}
Output
SMS: MEERA IYER, train 12627, seat B2-41

What this code does

  • Read down the comments: they say what the future holds after a step, and why it is thenApply or thenCompose. The first and the last steps also hold a CompletableFuture<String>.
  • The message needs both the passenger p and the seat. The inner thenApply sits inside the thenCompose lambda, where p is still in scope.

Example 5 · completedFuture when the answer is already known

CachedLookupDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.concurrent.CompletableFuture;
public class CachedLookupDemo {    static Map<Integer, String> cache = new HashMap<>();
    static CompletableFuture<String> nameOf(int roll) {        String hit = cache.get(roll);        if (hit != null) {            return CompletableFuture.completedFuture(hit);       // no thread needed        }        return CompletableFuture.supplyAsync(() -> {            System.out.println("  server call for roll " + roll);            return "Student-" + roll;        });    }
    public static void main(String[] args) {        cache.put(1, "Aarav");
        for (int roll : new int[] {1, 2}) {            String line = CompletableFuture.supplyAsync(() -> roll)                    .thenCompose(r -> nameOf(r))                    .thenApply(name -> "Roll " + roll + ": " + name)                    .join();            System.out.println(line);        }    }}
Output
Roll 1: Aarav
  server call for roll 2
Roll 2: Student-2

What this code does

  • nameOf always returns a future, so it always fits thenCompose. For a cache hit it returns completedFuture(hit), which is already done and costs no thread.
  • Only roll 2 misses the cache, so only roll 2 makes a server call. The caller's chain is the same for both cases.
  • Function returns a plain value (String::trim, total * 118 / 100) → thenApply.
  • Function returns a future (findUser, fetchOrders) → thenCompose.
  • Value already known → CompletableFuture.completedFuture(value).
  • Never join() inside a step: it blocks a pool thread; use thenCompose instead.

Two patterns come up often. When a later step needs a value from an earlier one, nest a thenApply inside the thenCompose lambda so both are in scope. When a method sometimes already has the answer, for example from a cache, it returns CompletableFuture.completedFuture(value), so callers still get a future.

Next step

Check your understanding

11 quick questions