Sub topic 1
Why Future Is Not Enough
Prerequisites
This chapter assumes that you know Java 8 lambdas, method references, basic threads, and ExecutorService. You should also be comfortable with generics, functional interfaces such as Supplier and Function, and checked versus unchecked exceptions.
What `Future` provides
A Future<T> represents the possible result of work that runs elsewhere. An executor returns one when you submit a task:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<String> name = pool.submit(() -> "alice");
System.out.println(name.get());
} finally {
pool.shutdown();
}
}
}The task runs in another thread. Calling get() waits until the task finishes and then returns its result. A Future also lets you ask whether the task is done or request cancellation.
This model works well when one caller submits one task and eventually needs one result. It becomes awkward when several asynchronous steps depend on one another.
The limits of `Future`
A Future mainly gives you a handle for checking or retrieving work. It does not provide operations for describing what should happen after completion.
For example, suppose you must fetch a user and then use that user to fetch an order. With plain Future, the second task often has to call get() inside a worker thread:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class BlockedChain {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<String> user = pool.submit(() -> "alice");
Future<String> order = pool.submit(() -> {
String userName = user.get();
return "order-for-" + userName;
});
System.out.println(order.get());
} finally {
pool.shutdown();
}
}
}This code is valid, but the second worker spends time blocked while waiting for the first task. With a small pool, enough blocked tasks can prevent useful work from running. A dependency that should be described as “continue when this finishes” has instead been implemented as “occupy a thread and wait.”
A Future also lacks convenient standard operations for:
- Transforming a result into another value.
- Starting another asynchronous task from a result.
- Combining independent results.
- Handling a failure at a chosen point in a workflow.
- Running a side effect when work completes.
You can build these features yourself with more submitted tasks, calls to get(), shared state, and error checks. The code grows quickly, and the relationships between tasks become difficult to read.
The `CompletableFuture` model
CompletableFuture<T> implements Future<T> but adds a pipeline of completion stages. A completion stage describes an action that becomes eligible when an earlier stage succeeds or fails.
Instead of submitting a second task that blocks on the first, you attach the next operation to the first future. Methods such as thenApply, thenCompose, and thenCombine express different relationships between stages. The resulting code describes the workflow rather than the mechanics of waiting.
The word “completable” adds another capability: code can complete a future explicitly. This is useful when adapting callback-based APIs, testing asynchronous code, or connecting an external event to a future.
When `Future` is still appropriate
Use a plain Future when the workflow is simple:
- Submit one independent task.
- Perform other work.
- Retrieve the result once.
- Cancel the task if it is no longer needed.
Choose CompletableFuture when the result participates in a workflow with transformations, dependencies, parallel branches, timeouts, or recovery. It gives those relationships names in the program and provides a standard way to connect them.
Exercise
Why can submitting a task that calls another future's get() waste executor threads?
Show answer
The task occupies a worker while waiting. If many tasks wait and the pool is small, no free workers may remain to perform the tasks that produce the awaited results.