Course contentsShow
← Java
Lesson 2817 of 2,87051. CompletableFutureFree lesson

Basic thenCompose Syntax and Usage

Write your first thenCompose call to chain two async operations where the second depends on the first's result.

Basic thenCompose Syntax and Usage

You'll learn: How to write your first thenCompose call to chain two async operations where the second depends on the first's result.

The Core Mechanic

thenCompose is like a handoff in a relay race where the second runner needs something from the first runner before they can start their own race. You use it when your transformation function doesn't just return a simple value—it returns another CompletableFuture.

Think of it this way: if thenApply unwraps a gift and puts a bow on it, thenCompose unwraps a gift that contains instructions to find another gift.

Basic Syntax

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);

CompletableFuture<String> result = future1.thenCompose(number -> 
    CompletableFuture.supplyAsync(() -> "Result: " + (number * 2))
);

What's happening:

  1. future1 produces 5
  2. thenCompose receives 5 and passes it to your lambda
  3. Your lambda returns a new CompletableFuture that does another async operation
  4. thenCompose flattens this, so result is CompletableFuture<String>, not CompletableFuture<CompletableFuture<String>>

Real-World Pattern

CompletableFuture<Integer> userId = CompletableFuture.supplyAsync(() -> 42);

CompletableFuture<String> userName = userId.thenCompose(id ->
    CompletableFuture.supplyAsync(() -> "User_" + id)  // Simulates DB lookup
);

System.out.println(userName.join());  // "User_42"

The second operation depends on the first's result and is itself asynchronous.

Key Takeaway:
Use thenCompose when your transformation returns another CompletableFuture—it flattens nested futures and chains dependent async operations into a single pipeline.