CompletableFuture
- Java course
- Advanced
- Lesson 63/82
- 5 min
Learn async chains with CompletableFuture.
CompletableFuture
CompletableFuture lets you chain and combine asynchronous operations. supplyAsync runs a task in a pool; thenApply, thenAccept and friends define the next step on the result.
CompletableFuture<Integer> f =
CompletableFuture.supplyAsync(() -> 2 + 3)
.thenApply(n -> n * 2);
System.out.println(f.join()); // 10join() waits for the result; unlike get(), it throws an unchecked exception. This makes it easy to build async flows in functional style. Multiple futures can be combined with allOf.
Combining with allOf
To run several futures in parallel and wait for all of them, use allOf. This is ideal for speeding up independent tasks.
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2);
all.join();
// f1 and f2 are doneAfter this, each future's result is fetched with f1.join(). This increases throughput in scenarios like parallel API requests. anyOf returns the one that finishes first. This is the foundation of modern async Java.
Practice Build a CompletableFuture chain
Write main in an AsyncDemo class; start with CompletableFuture.supplyAsync(() -> 10), add 5 with .thenApply(n -> n + 5) to produce 15, and print the result with System.out.println(f.join()).
Starter code
import java.util.concurrent.*;
// Write main in AsyncDemo
// Start supplyAsync returning 10; add 5 with thenApply; print joinSample solution
import java.util.concurrent.*;
class AsyncDemo {
public static void main(String[] args) {
CompletableFuture<Integer> f =
CompletableFuture.supplyAsync(() -> 10).thenApply(n -> n + 5);
System.out.println(f.join());
}
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match CompletableFuture methods
| Term | Meaning |
|---|---|
supplyAsync |
Runs the task in a pool |
thenApply |
Transforms the result |
thenAccept |
Consumes the result |
join |
Waits for the result |
2 Complete the thenApply call
CompletableFuture.supplyAsync(() -> 2 + 3)
.____(n -> n * 2);
CompletableFuture.supplyAsync(() -> 2 + 3)
.thenApply(n -> n * 2);
Explanation: thenApply transforms the result.
3 What does CompletableFuture.join() return?
- Cancels the future
- Waits and returns the result Correct answer
- Immediately void
- Creates a new future
Explanation: join() waits and returns the result.