Sub topic 13
Composing Asynchronous Work with CompletableFuture
In the earlier chapters you used a Future to get a result back from a task. A Future has one weakness. The only way to use its result is to call get(), and get() makes your thread stop and wait. If you want to do something with the result, such as double it, format it, or save it, you have to wait first and then do the work yourself.
CompletableFuture fixes this. You can tell it what to do with the result once the result is ready, and your thread does not have to wait. This chapter shows how to start work on an executor you choose, chain steps together, combine two results, and handle errors.
What Is a CompletableFuture?
A CompletableFuture is a Future that you can attach more steps to. It lives in the java.util.concurrent package, the same package as ExecutorService.
Some terms used in this chapter:
- Asynchronous means "runs on its own, without making the caller wait." Asynchronous work happens in the background.
- A stage is one step in a chain of asynchronous work. Each method you call on a
CompletableFuturecreates a new stage. - A callback is a piece of code that you hand over now, to be run later when something happens. Here, "something happens" means a result is ready.
Think of an order at a sandwich shop. With a plain Future, you stand at the counter until the sandwich is ready, then you wrap it yourself. With a CompletableFuture, you leave instructions: "When it's ready, wrap it, then put it in a bag." The staff do each step as soon as the step before it finishes.
Starting Work on Your Own Executor
There are two common ways to start a CompletableFuture:
| Method | Task type | Returns a value? |
|---|---|---|
| `supplyAsync(supplier, executor)` | A `Supplier<T>`, like `() -> 21` | Yes |
| `runAsync(runnable, executor)` | A `Runnable`, like `() -> System.out.println("hi")` | No |
Both methods also have a version without the executor argument. Without it, the task runs on a shared pool called the common pool (ForkJoinPool.commonPool()). This chapter always passes an executor, and the callout below explains why.
Your First Chain with thenApply
Here is a full program. It starts a task on a pool of two threads, then attaches two more steps.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> 21, pool)
.thenApply(n -> n * 2)
.thenApply(n -> "Answer: " + n);
System.out.println(result.join());
} finally {
pool.shutdown();
}
}
}Output:
Answer: 42Here is what each line does:
supplyAsync(() -> 21, pool)runs the lambda on a thread frompool. It returns aCompletableFuture<Integer>right away, before the value is ready.thenApply(n -> n * 2)says: "When the value arrives, multiply it by 2." This creates a new stage holding anInteger.thenApply(n -> "Answer: " + n)turns the number into aString. Now the stage type isCompletableFuture<String>.result.join()waits for the last stage and returns its value.pool.shutdown()in thefinallyblock stops the pool, the same as in earlier chapters.
thenApply is a transformation. It takes the result of one stage and produces a new value. It works like the map method you may know from streams.
join Versus get
You can read the final value with either join() or get(). Both wait for the result. They differ in how they report a failure.
| Method | Exception thrown on failure | Checked? |
|---|---|---|
| `get()` | `ExecutionException` (and `InterruptedException`) | Yes, you must catch or declare it |
| `join()` | `CompletionException` | No |
A checked exception is one the compiler forces you to handle with try/catch or throws. join() throws only unchecked exceptions, so it fits neatly inside lambdas and short programs. In both cases, the original error is available through getCause().
Using the Result Without Returning Anything
Sometimes the last step only needs to use the value, for example to print it or save it. Use thenAccept for that. It takes the value and returns nothing, so the stage type becomes CompletableFuture<Void>.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AcceptDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Void> done = CompletableFuture
.supplyAsync(() -> "hello", pool)
.thenApply(String::toUpperCase)
.thenAccept(s -> System.out.println("Got: " + s));
done.join();
} finally {
pool.shutdown();
}
}
}Output:
Got: HELLOThe done.join() call matters. Without it, main could reach pool.shutdown() and finish before the printing step runs. Calling shutdown() still lets tasks that were already submitted finish, but waiting on purpose makes the program's behavior clear.
Combining Two Results with thenCombine
Often you need two independent pieces of data, such as a price and a shipping cost. You can start both at the same time, so they run in parallel, and join them when both are ready. thenCombine does this.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CombineDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 40, pool);
CompletableFuture<Integer> shipping = CompletableFuture.supplyAsync(() -> 5, pool);
CompletableFuture<Integer> total = price.thenCombine(shipping, (p, s) -> p + s);
System.out.println("Total: " + total.join());
} finally {
pool.shutdown();
}
}
}Output:
Total: 45The lambda (p, s) -> p + s runs only after both price and shipping have finished. If each lookup took one second, the total would be ready in about one second, not two, because both lookups run at the same time.
Chaining a Step That Is Itself Asynchronous: thenCompose
Suppose you have a method that already returns a CompletableFuture, such as a method that looks up a user's name from an ID. If you call it inside thenApply, you get a future inside a future: CompletableFuture<CompletableFuture<String>>. That type is awkward to work with.
thenCompose flattens it. Use it when the next step returns a CompletableFuture of its own. It works like flatMap on streams.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ComposeDemo {
static CompletableFuture<String> findName(int id, ExecutorService pool) {
return CompletableFuture.supplyAsync(() -> "User" + id, pool);
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> name = CompletableFuture
.supplyAsync(() -> 7, pool)
.thenCompose(id -> findName(id, pool));
System.out.println(name.join());
} finally {
pool.shutdown();
}
}
}Output:
User7A simple rule: if your lambda returns a plain value, use thenApply. If it returns a CompletableFuture, use thenCompose.
Handling Errors in the Chain
In the chapter on task exceptions, you saw that Future.get() wraps a task's error in an ExecutionException. A CompletableFuture chain can handle an error inside the chain itself.
When a stage throws, every later thenApply or thenAccept stage is skipped. The error moves down the chain until something handles it. Two methods handle errors:
exceptionally(ex -> fallback)runs only on failure and supplies a replacement value.handle((value, ex) -> ...)runs on both success and failure. Exactly one ofvalueandexis non-null.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ErrorDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Integer> safe = CompletableFuture
.supplyAsync(() -> Integer.parseInt("oops"), pool)
.thenApply(n -> n * 2)
.exceptionally(ex -> {
System.out.println("Failed: " + ex.getCause());
return 0;
});
System.out.println("Result: " + safe.join());
CompletableFuture<String> report = CompletableFuture
.supplyAsync(() -> Integer.parseInt("12"), pool)
.handle((value, ex) -> ex == null ? "Parsed " + value : "Error");
System.out.println(report.join());
} finally {
pool.shutdown();
}
}
}Output:
Failed: java.lang.NumberFormatException: For input string: "oops"
Result: 0
Parsed 12In the first chain, parseInt("oops") throws. The thenApply(n -> n * 2) step is skipped, and exceptionally supplies 0. The ex that exceptionally receives here is usually a CompletionException, which wraps the original error. That is why the code calls ex.getCause() to show the real NumberFormatException.
Which Thread Runs Each Step?
Methods like thenApply do not name an executor. The step runs on whichever thread is handy: usually the pool thread that finished the previous stage, or your own thread if the previous stage had already finished when you attached the step. For quick steps like n * 2, this is fine.
If a step is slow or blocks, use the Async version and pass your executor. Every method shown here has one, for example thenApplyAsync(fn, pool) and thenAcceptAsync(action, pool). That puts the step back on a thread you control.
Quick Reference
| You want to... | Use |
|---|---|
| Start a task that returns a value | `supplyAsync(supplier, pool)` |
| Start a task with no result | `runAsync(runnable, pool)` |
| Transform a result | `thenApply` |
| Consume a result | `thenAccept` |
| Chain a step that returns a future | `thenCompose` |
| Merge two independent results | `thenCombine` |
| Replace a failure with a value | `exceptionally` |
| React to success or failure | `handle` |
| Wait for the final value | `join` (unchecked) or `get` (checked) |
Exercises
Exercise
You have CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 5, pool);. Write a chain that adds 10 to the value, then prints "Value: 15", and then waits for it to finish.
Show answer
f.thenApply(n -> n + 10).thenAccept(n -> System.out.println("Value: " + n)).join(); The thenApply step transforms 5 into 15, thenAccept uses the value without returning one, and join waits until the printing is done.
Exercise
A method CompletableFuture<Double> loadRate(String code) already returns a future. You have CompletableFuture<String> code. Should you write code.thenApply(c -> loadRate(c)) or code.thenCompose(c -> loadRate(c)), and why?
Show answer
Use thenCompose. With thenApply the result type would be CompletableFuture<CompletableFuture<Double>>, a future inside a future. thenCompose flattens it to CompletableFuture<Double>.
Exercise
In the chain supplyAsync(() -> 10 / 0, pool).thenApply(n -> n + 1).exceptionally(ex -> -1), what does join() return, and does the thenApply step run?
Show answer
join() returns -1. Dividing by zero throws an ArithmeticException, so the thenApply step is skipped and the error passes down to exceptionally, which supplies -1.
Exercise
Why does this chapter pass an executor to supplyAsync instead of using the version without one?
Show answer
Without an executor, tasks run on the shared common pool, which has only a few threads and is used by the whole program. Blocking tasks can use up all of those threads. Passing your own ExecutorService keeps your tasks separate and under your control, including when you shut the pool down.