Sub topic 1
Why Future is not enough
Java 5 introduced java.util.concurrent.Future to represent the result of work running on another thread. It solved one problem, getting a value back from a background task. It left several others open, and those gaps are the reason CompletableFuture exists. This chapter walks through each gap with code, so you can recognize the symptoms in your own programs.
Prerequisites
This chapter assumes you already know:
- Java 8 lambdas and method references.
- How to create an
ExecutorServiceand submit tasks to it. - Generics and the functional interfaces
Supplier,Function, andConsumer. - The difference between checked and unchecked exceptions.
What Future gives you
A Future<V> is a handle to a result that may not exist yet. Its whole interface is five methods (Java 19 and later add a few more, covered below):
| Method | Purpose |
|---|---|
| `get()` | Block until the result is ready, then return it |
| `get(timeout, unit)` | Block, but give up with a `TimeoutException` |
| `isDone()` | Return true if the task finished, failed, or was cancelled |
| `cancel(mayInterrupt)` | Try to cancel the task |
| `isCancelled()` | Return true if the task was cancelled |
You usually get a Future from ExecutorService.submit. The following program runs two independent computations in parallel and adds their results:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureBlocking {
static int slowSquare(int n) throws InterruptedException {
Thread.sleep(500);
return n * n;
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Integer> a = pool.submit(() -> slowSquare(3));
Future<Integer> b = pool.submit(() -> slowSquare(4));
int sum = a.get() + b.get();
System.out.println(sum);
} finally {
pool.shutdown();
}
}
}This prints 25 after about half a second, because the two tasks overlap. For this simple fan-out and join, Future works well. The trouble starts when the work has more structure than "start some tasks, then wait for all of them".
Limit 1: the only way to get a result is to block
get() parks the calling thread until the value arrives. The Future has no way to say "when you finish, run this code". To use the result, some thread must wait for it.
In a program that handles many requests, each blocked thread is a thread that cannot do other work. A server that blocks one thread per outstanding call needs as many threads as it has concurrent calls. Threads are expensive, so this limits scalability.
Polling with isDone() avoids blocking, but it just moves the cost into a loop that burns CPU or adds latency through sleeps.
Limit 2: no way to attach a callback
Many asynchronous designs are event driven. You want to say "when the user lookup completes, log it". With Future there is no method for this. The standard workaround is to submit a second task whose only job is to call get() on the first one:
Future<String> user = pool.submit(() -> lookupUser());
pool.submit(() -> {
String name = user.get(); // occupies a pool thread while waiting
System.out.println(name);
return null;
});The second task spends its life blocked. You have not removed the waiting, only moved it onto another thread.
Limit 3: steps cannot be composed
Real work often has the shape "fetch the user, then fetch that user's orders, then compute a total". Each step needs the previous result. With Future you must write this as sequential blocking code:
Future<Integer> userId = pool.submit(() -> fetchUserId("alice"));
Future<String> order = pool.submit(() -> fetchOrder(userId.get()));
String result = order.get();The call userId.get() runs inside the second task, so a pool thread blocks waiting for the first task. This is more than a performance cost. It can deadlock.
A deadlock you can reproduce
Suppose the pool has a single thread. The outer task occupies that thread and submits an inner task. The inner task cannot start because the only thread is busy, and the outer task cannot finish because it waits for the inner task.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureDeadlock {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<String> outer = pool.submit(() -> {
Future<String> inner = pool.submit(() -> "inner");
return inner.get(); // waits for a thread that is never free
});
try {
System.out.println(outer.get(1, TimeUnit.SECONDS));
} catch (TimeoutException e) {
System.out.println("deadlocked: outer task never finished");
}
} finally {
pool.shutdownNow();
}
}
}The program prints deadlocked: outer task never finished. I gave get a timeout only so the demonstration ends. Without the timeout it would hang forever. A larger pool hides the problem until enough nested tasks arrive at once to use every thread, which is a typical production failure under load.
CompletableFuture.thenCompose, covered in a later chapter, expresses the same dependency without any thread waiting.
Limit 4: combining several futures is manual
Waiting for two futures is easy, as the first example showed. But anything more flexible needs hand-written code:
- "Continue when the first of these three finishes" requires a loop over
isDone()or a helper such asExecutorService.invokeAny. - "Combine these two results with a function" requires calling
get()on both and applying the function yourself, on whichever thread you happen to be on. - "Run something when all of these finish, without blocking" is not possible at all.
Each of these becomes a small piece of custom concurrency code, and each is a place to introduce bugs.
Limit 5: you cannot complete a Future yourself
A Future from submit is tied to the task that produced it. You cannot say "this value arrived from a network callback, so mark the future done". Many APIs are callback based: an HTTP client calls your listener, a message broker delivers a reply. To expose such an API as a Future, you would need to write your own Future implementation, with its own locking and waiting logic.
You also cannot supply a default. If a task is slow, you can stop waiting with get(timeout, unit), but the exception interrupts your flow, and the task keeps running.
Limit 6: errors arrive in a clumsy form
If the task throws, get() throws ExecutionException with the real error as its cause:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureErrors {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<Integer> f = pool.submit(() -> Integer.parseInt("abc"));
try {
f.get();
} catch (ExecutionException e) {
System.out.println("cause: " + e.getCause());
}
} finally {
pool.shutdown();
}
}
}This prints cause: java.lang.NumberFormatException: For input string: "abc".
Three things make this awkward:
- The error surfaces only if someone calls
get(). If nobody does, the failure is silent. get()also throws the checkedInterruptedException, so every call site needs atryblock or athrowsclause.- There is no way to say "if this fails, use a fallback" as part of a pipeline. You write
try/catcharound eachget().
Limit 7: cancellation and inspection are limited
cancel(true) on a FutureTask interrupts the running thread, but the task only stops if it responds to interrupts. isDone() is true for success, failure, and cancellation alike, so after it returns true you still cannot tell which one happened without calling get() and catching exceptions. Java 19 added state(), resultNow(), and exceptionNow() to Future to ease this, but they inspect a finished future and do not add composition.
What CompletableFuture changes
CompletableFuture<T> implements Future<T>, so it works anywhere a Future is expected. On top of that it implements CompletionStage<T>, which adds the missing operations. The table maps each limit to the feature that addresses it.
| Limit of Future | CompletableFuture feature |
|---|---|
| Only blocking retrieval | `thenApply`, `thenAccept`, and other callbacks |
| No composition of dependent steps | `thenCompose` |
| Manual combination of results | `thenCombine`, `allOf`, `anyOf` |
| Cannot be completed by you | `complete`, `completeExceptionally` |
| Clumsy errors | `exceptionally`, `handle`, `whenComplete` |
| No built-in timeouts | `orTimeout`, `completeOnTimeout` (Java 9 and later) |
Here is the earlier two-task example rewritten so that no thread blocks until the very end:
import java.util.concurrent.CompletableFuture;
public class FirstLook {
static int slowSquare(int n) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return n * n;
}
public static void main(String[] args) {
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> slowSquare(3));
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> slowSquare(4));
int sum = a.thenCombine(b, Integer::sum).join();
System.out.println(sum);
}
}This prints 25. The addition runs as a callback when both inputs are ready, and only the final join() waits. The later chapters explain each method used here.
Summary of the argument
Future is a good fit when you start a few independent tasks and then wait for all of them from one place. It is a poor fit when results feed into further asynchronous work, when you cannot afford to block threads, or when you need to handle errors and timeouts as part of the flow. In those cases you end up writing blocking glue code that wastes threads and risks deadlock. CompletableFuture moves that glue into the library, so you describe what happens after a result arrives instead of waiting for it.
Exercise
A colleague writes a service that submits a task to a fixed pool of 4 threads. Inside that task, it submits a subtask to the same pool and calls get() on it. Under light load everything works, but under heavy load the service stops responding. Explain why, and name the CompletableFuture method designed to avoid this pattern.
Show answer
Each outer task holds a pool thread while it blocks on get() for its subtask. Under heavy load, 4 outer tasks can occupy all 4 threads at once. Their subtasks then sit in the queue with no free thread to run them, so no outer task can finish. This is a thread starvation deadlock. Light load works because a thread is usually free to run each subtask. thenCompose chains the dependent step as a callback, so no thread waits for the first result.
Exercise
The Future interface has no way to run code when a task finishes, other than blocking on get() or polling isDone(). Name two costs of each workaround.
Show answer
Blocking on get() ties up a thread for the whole wait, which limits scalability, and it forces you to handle the checked InterruptedException and ExecutionException at each call site. Polling isDone() either burns CPU in a tight loop or adds latency when you sleep between checks, and you still have to call get() afterwards to read the result or the error.