Sub topic 10
Understanding the Async Method Variants
Assume you know Java 8 lambdas, method references, generics, and the basics of threads and ExecutorService. A CompletableFuture stage can run its continuation in two main ways:
- A synchronous method, such as
thenApply, runs the continuation in the thread that completes the previous stage. - An asynchronous method, such as
thenApplyAsync, schedules the continuation to run separately.
“ Synchronous” here does not mean that the whole operation blocks while waiting. The caller can still receive a CompletableFuture immediately. It describes how the next stage starts after the previous stage completes.
Synchronous methods
Consider these common pairs:
| Synchronous method | Asynchronous method |
|---|---|
| `thenApply` | `thenApplyAsync` |
| `thenAccept` | `thenAcceptAsync` |
| `thenCompose` | `thenComposeAsync` |
| `thenCombine` | `thenCombineAsync` |
With a synchronous method, the continuation usually runs on the thread that completes the previous future. If the previous future is already complete when you attach the stage, the calling thread might run it immediately.
That behavior avoids scheduling overhead, but it means that a slow continuation can delay the thread completing the earlier stage. For example, a database callback thread should not perform several seconds of report generation just because it uses thenApply.
Asynchronous methods and executors
An Async method without an executor uses Java's common ForkJoinPool. This pool is shared by many parts of an application. An Async method can also receive an explicit Executor, which gives you control over the threads used by that stage.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncVariants {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> base =
CompletableFuture.completedFuture("hello");
CompletableFuture<String> sync = base.thenApply(value -> {
System.out.println("sync: " + Thread.currentThread().getName());
return value.toUpperCase();
});
CompletableFuture<String> async = base.thenApplyAsync(value -> {
System.out.println("async: " + Thread.currentThread().getName());
return value.toUpperCase();
}, executor);
System.out.println(sync.join());
System.out.println(async.join());
} finally {
executor.shutdown();
}
}
}The synchronous continuation can run on the main thread because base is already complete. The asynchronous continuation is submitted to executor. The exact order of thread-related output is not a reliable part of the program's result.
Choosing between the variants
Use a synchronous variant when the continuation is short, non-blocking, and naturally belongs on the completing thread. Simple mapping, validation, and field extraction often fit this choice.
Use an asynchronous variant when the continuation is expensive, blocking, or should be isolated from the previous stage's thread. Pass a custom executor when you need separate capacity for a workload, such as file access or remote calls.
An Async method does not make blocking code safe. If a continuation calls a blocking API, it still occupies a thread while waiting. Avoid putting many blocking operations in the common pool. A custom, bounded executor makes that resource use easier to control.
A common mistake
Adding thenApplyAsync changes only that continuation. It does not automatically move every earlier or later stage to the same executor. Select the appropriate variant at each boundary, and pass the executor explicitly when the default common pool is not suitable.
Exercise
Which method should you choose for a short, non-blocking transformation, and which method is preferable when the transformation performs blocking file I/O?
Show answer
Use thenApply for the short transformation. Use thenApplyAsync with a suitable custom executor for blocking file I/O.