Sub topic 13
Pitfalls and Best Practices
Assume you know Java lambdas, ExecutorService, and the basic CompletableFuture methods. This chapter focuses on problems that often appear after a future-based design seems to work.
Do not block the common pool
Methods such as supplyAsync use the common ForkJoinPool when you do not provide an executor. This pool is shared by many parts of the application.
Blocking work, such as network calls, file access, or join, can occupy its worker threads. If enough tasks block, other asynchronous tasks may wait indefinitely for an available worker.
Use a separate executor for blocking operations:
ExecutorService ioPool = Executors.newFixedThreadPool(8);
CompletableFuture<String> response =
CompletableFuture.supplyAsync(this::readFromNetwork, ioPool);
try {
System.out.println(response.join());
} finally {
ioPool.shutdown();
}Size the executor according to the work. A CPU-heavy task usually needs about as many threads as available processors. Blocking I/O may need more, but measure the application rather than choosing an arbitrary large number.
Keep the pipeline asynchronous
Calling join or get in the middle of a pipeline defeats composition:
String user = fetchUser().join();
return fetchOrders(user).join();This design blocks the calling thread and makes failures harder to organize. Prefer thenCompose:
return fetchUser()
.thenCompose(this::fetchOrders);Use join at a deliberate boundary, such as a command-line program or an adapter method that must return a normal value. Keep the internal stages non-blocking.
Understand cancellation
CompletableFuture.cancel completes the future exceptionally with a cancellation exception. It does not reliably interrupt the task that is already running.
CompletableFuture<String> task =
CompletableFuture.supplyAsync(this::longOperation);
task.cancel(false);The future may now report cancellation while longOperation continues in the background. If the operation uses a resource, it must have its own cancellation or interruption policy. Do not use cancellation as a substitute for resource management.
Handle failures at the right point
An exception usually completes the current future exceptionally. A later stage will be skipped until an error-handling stage handles the failure.
exceptionallyconverts a failure into a fallback value.handlereceives either the result or the exception and can handle both cases.whenCompleteobserves the result or failure but normally passes it onward unchanged.
When you call join, an underlying exception is commonly wrapped in CompletionException. get instead declares checked exceptions and commonly reports the cause through ExecutionException.
CompletableFuture<Integer> value =
CompletableFuture.supplyAsync(() -> Integer.parseInt("bad"))
.exceptionally(ex -> {
System.out.println("Cause: " + ex.getCause());
return 0;
});
System.out.println(value.join());Do not catch an exception and silently return a value that looks valid. A fallback should be clearly safe for the caller.
A timeout or fallback changes the meaning of the result. Record enough context to distinguish a real response from a default value.Use timeouts deliberately
orTimeout completes the future exceptionally after the limit. completeOnTimeout completes it normally with a supplied value.
CompletableFuture<String> result =
fetchData()
.orTimeout(500, TimeUnit.MILLISECONDS)
.exceptionally(ex -> "unavailable");A timeout completes the future, but it may not stop the underlying work. The remote request or task might still consume resources. Pair timeouts with client-level cancellation when the library supports it.
Choose the correct method variant
A non-Async continuation may run on the thread that completes the previous stage. An Async continuation uses an executor, or the common pool when no executor is supplied.
| Method | Typical behavior |
|---|---|
| `thenApply` | Transform a value, possibly on the completing thread |
| `thenApplyAsync` | Transform a value through an executor |
| `thenCompose` | Start a dependent future without nesting |
| `thenComposeAsync` | Start the dependent stage through an executor |
Use an explicit executor when the continuation has blocking, expensive, or thread-sensitive work.
Best-practice checklist
- Keep a reference to futures whose completion you must observe.
- Prefer one composed pipeline over many blocking calls.
- Use
allOfwhen every task matters, and inspect each future afterward. - Use
anyOfonly when the first completion is sufficient. - Shut down custom executors.
- Make side effects, retries, and fallbacks explicit.
- Test both successful and exceptional completion.
Exercise
A future performs a blocking database call and then uses thenApplyAsync without an executor. What should you change?
Show answer
Run the database call and any other blocking stage on a dedicated, properly managed executor instead of relying on the common pool.