Sub topic 13
Pitfalls and best practices
This chapter assumes you know supplyAsync, thenApply, thenCompose, allOf, handle, and orTimeout from earlier chapters, and that you understand ExecutorService. Most CompletableFuture bugs do not come from misusing one method. They come from threads, exceptions, and cancellation behaving differently than the code's shape suggests.
Pitfall 1: blocking inside the common pool
supplyAsync(supplier) without an executor runs on ForkJoinPool.commonPool(). That pool is sized for CPU-bound work. Its parallelism defaults to the number of processors minus one. Every other user of the pool shares it, including parallel streams and other libraries.
If your tasks call Thread.sleep, JDBC, a blocking HTTP client, or file I/O, they occupy those few threads while doing nothing. Unrelated tasks queue behind them, and latency grows for the whole application.
Calling join() inside a stage running on the pool is a milder form of the same problem. CompletableFuture can add compensating threads in that case, but it does not do so for sleep or I/O calls.
The fix is to pass a dedicated executor sized for the blocking work:
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class BlockingIo {
static String blockingCall(int id) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
return "response-" + id;
}
public static void main(String[] args) {
ExecutorService io = Executors.newFixedThreadPool(8);
try {
List<CompletableFuture<String>> calls = IntStream.range(0, 8)
.mapToObj(i -> CompletableFuture.supplyAsync(() -> blockingCall(i), io))
.collect(Collectors.toList());
CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join();
System.out.println(calls.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
} finally {
io.shutdown();
}
}
}All eight calls overlap, so the program finishes in about 500 ms. On a machine with a small common pool, the same eight calls would run in several waves.
Choosing where a stage runs
Pitfall 2: the JVM exits before the work finishes
Common pool threads are daemon threads. They do not keep the JVM alive. In a small main program that starts a future and returns without waiting, the process can end before the task runs. Call join() at the edge of the program, or keep the application alive some other way.
The opposite problem occurs with your own executors. Executors.newFixedThreadPool creates non-daemon threads. If you forget shutdown(), the JVM never exits. Shut the pool down in a finally block, as the examples in this tutorial do. Do not shut it down while futures that use it are still pending, because later submissions then throw RejectedExecutionException.
Pitfall 3: cancel does not stop running work
CompletableFuture.cancel(boolean) completes the future with a CancellationException. The boolean argument is ignored. It does not interrupt the thread running the task, because the future does not know which thread that is.
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
public class CancelDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
System.out.println("task body finished");
return "result";
});
Thread.sleep(50);
System.out.println("cancel: " + f.cancel(true));
System.out.println("cancelled: " + f.isCancelled());
try {
f.join();
} catch (CancellationException e) {
System.out.println("join threw CancellationException");
}
Thread.sleep(500);
}
}The output shows cancel: true, cancelled: true, and the CancellationException line. About 300 ms later, task body finished still appears, and interrupted never does. The future is cancelled, but the work ran to the end and its result was discarded.
Two consequences follow:
- Cancelling a future does not release the resources its task holds.
- Cancelling an upstream future makes dependent stages fail with a
CompletionExceptionthat wraps theCancellationException. It does not cancel them.
If work must be stoppable, give the task a cooperative signal. Examples are a volatile flag, an AtomicBoolean, or a check of Thread.interrupted() driven by a Future you got from ExecutorService.submit.
Pitfall 4: timeouts have the same limit
orTimeout and completeOnTimeout complete the future early. They do not stop the work behind it. A task that takes 30 seconds still consumes its thread for 30 seconds after orTimeout(1, SECONDS) fires. For network calls, also set the timeout on the client itself (connect and read timeouts) so the thread is actually freed.
orTimeout completes the future with a TimeoutException. A stage that is attached after orTimeout and handles errors will see it, so put your fallback stage after the timeout stage.
Pitfall 5: exceptions that nobody sees
A future that fails with nobody calling join, get, or an error-handling stage fails silently. Fire-and-forget code such as runAsync(() -> sendEmail()) loses the failure completely. Nothing is logged and nothing is thrown.
Attach whenComplete or handle to every future whose result you do not consume. The next example also shows the wrapping rule. A stage that fails because its own function threw, and every dependent stage downstream, sees a CompletionException whose cause is the original exception.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
public class LostErrors {
static Throwable unwrap(Throwable t) {
if ((t instanceof CompletionException || t instanceof ExecutionException)
&& t.getCause() != null) {
return t.getCause();
}
return t;
}
public static void main(String[] args) {
CompletableFuture<Void> logged = CompletableFuture
.runAsync(() -> {
throw new IllegalStateException("boom");
})
.whenComplete((v, ex) -> {
if (ex != null) {
System.err.println("task failed: " + unwrap(ex));
}
});
try {
logged.join();
} catch (CompletionException e) {
System.out.println("root cause: " + e.getCause().getMessage());
}
}
}whenComplete logs the failure and does not change the outcome, so join() still throws and the program prints root cause: boom. Use handle or exceptionally when you want to replace the failure with a value.
Remember the difference between the two ways to retrieve a result:
| Method | Failure arrives as | Checked exception? |
|---|---|---|
| `join()` | `CompletionException` (cancel gives `CancellationException`) | No |
| `get()` | `ExecutionException` with the original as cause | Yes, and `InterruptedException` too |
When you test for a specific exception type in exceptionally or handle, unwrap first. Code such as ex instanceof TimeoutException can be false because ex is a wrapper. If you called completeExceptionally(e) directly, the future that you completed holds e as is, but its dependents see a wrapped one. Writing code that works with both forms is simpler than tracking which one you have.
Pitfall 6: surprises with allOf and anyOf
allOfis not fail-fast. If one input fails immediately and another takes a minute, the combined future completes exceptionally only after the minute has passed. Its result isVoid, so you must collect values withjoin()afterwards, as you did earlier.anyOfcompletes with the first stage to finish, and that can be a failure. Its result type isObject, so you need a cast.- Neither method cancels the losers. Slow tasks keep running after
anyOfhas its answer.
Pitfall 7: callbacks run on whichever thread completes the future
A non-Async method such as thenApply runs its function on the thread that completes the previous stage. If the future is already complete, it runs immediately on the calling thread. That is efficient for small functions. It becomes a problem when the callback is slow, because it stalls the completing thread. That thread could be an I/O event loop or a thread that you passed to complete(...).
For slow callbacks, use the ...Async variant with an explicit executor. Do not rely on a callback running on a particular thread. In particular, ThreadLocal values, such as logging context, security context, or transaction state, are not carried from one stage to the next. Capture the values you need in local variables before building the chain, or wrap the executor to copy the context.
Best practices checklist
- Pass an explicit executor to every
supplyAsync,runAsync, and...Asynccall that does blocking work. Make it bounded, name its threads, and shut it down. - End every chain with a consumer of failures. Put
join()orget()at the outermost layer only, not in the middle of a pipeline. - Keep stage functions short and free of blocking calls. Use
thenComposeinstead ofthenApplyplusjoin()for dependent asynchronous calls. - Return futures from your API methods and let callers decide when to wait. Do not hide a
join()inside a method that returns aCompletableFuture. - Treat
canceland timeouts as signals to the caller, not as ways to stop work. Add a cooperative stop mechanism where it matters. - Unwrap
CompletionExceptionin one helper method, and use it everywhere you inspect failures. - Test failure paths, not only success paths. A test that makes a stage throw and then checks the fallback catches most of the issues in this chapter.
Exercise
A method calls CompletableFuture.supplyAsync(() -> httpClient.fetch(url)) with no executor, and 20 requests are started at once on a 4-core machine. Name the problem and give a fix.
Show answer
The blocking fetch calls run on the common pool, whose parallelism is about 3 on that machine. Only about 3 requests run at a time, and other code that uses the common pool is delayed behind them. Pass a dedicated bounded executor (for example Executors.newFixedThreadPool(20), shut down when done) as the second argument of supplyAsync, and set read and connect timeouts on the HTTP client.
Exercise
You call f.cancel(true) on a future whose task is sleeping inside supplyAsync. What happens to the future, to the task, and to a stage created with f.thenApply(...)?
Show answer
The future completes with a CancellationException, and isCancelled() returns true. The true argument has no effect, so the task is not interrupted and keeps running, and its result is discarded. The dependent thenApply stage does not run its function. It completes exceptionally with a CompletionException that wraps the CancellationException.
Exercise
allOf(a, b) is used, where a fails after 10 ms and b takes 5 seconds. When does the combined future complete, and with what outcome?
Show answer
It completes after about 5 seconds, because allOf waits for every input. The outcome is exceptional, a CompletionException caused by the failure of a. To react to the first failure sooner, attach exceptionally or whenComplete to each input and complete a separate future manually.