Sub topic 3
Choosing an Executor for CompletableFuture
Assume you know Java lambdas, ExecutorService, generics, and basic exception handling. An executor controls which threads run asynchronous tasks.
Choosing an executor
Methods such as supplyAsync use the common ForkJoinPool when no executor is supplied. This is convenient for short, non-blocking work. Use a custom executor for blocking I/O, slow operations, or workloads that need separate capacity.
ExecutorService ioPool = Executors.newFixedThreadPool(4);
CompletableFuture<String> result =
CompletableFuture.supplyAsync(() -> loadData(), ioPool);
ioPool.shutdown();A custom pool prevents blocking tasks from consuming threads needed by unrelated common-pool work. Always shut down an executor that your code owns.
Understanding the Async method variants
A method without Async, such as thenApply, usually runs the continuation in the thread that completes the previous stage. An Async method uses an executor. You can use the common pool or pass your own executor.
| Method | Typical execution |
|---|---|
| `thenApply` | Completing thread |
| `thenApplyAsync` | Common pool or supplied executor |
Use thenApplyAsync(function, executor) when the continuation itself is expensive or blocking. Do not assume that every continuation runs on a dedicated thread.
Completing futures manually
A CompletableFuture can represent a result delivered by another API:
CompletableFuture<String> promise = new CompletableFuture<>();
promise.complete("ready");
promise.completeExceptionally(new IllegalStateException("failed"));Only the first completion wins. This pattern is useful when adapting callbacks, but the callback must ensure that success and failure cannot accidentally produce competing results.
Timeouts with `orTimeout` and `completeOnTimeout`
orTimeout completes exceptionally with TimeoutException. completeOnTimeout supplies a fallback value. These methods do not generally interrupt the underlying task.
CompletableFuture<String> f = CompletableFuture
.supplyAsync(() -> "result")
.completeOnTimeout("fallback", 100, TimeUnit.MILLISECONDS);Pitfalls and best practices
- Do not block common-pool threads with long I/O or
joincalls. - Keep executor ownership clear and shut down custom pools.
- Remember that
joinwraps failures inCompletionException. - Do not expect
cancelto interrupt running work. - Give each asynchronous boundary an intentional executor.
Exercise
Which method should you choose for a blocking continuation that must use a dedicated pool?
Show answer
Use an Async variant with the custom executor, such as thenApplyAsync(function, executor).