Sub topic 10
Understanding the Async method variants
This chapter assumes you know the basics from earlier chapters: supplyAsync, thenApply, thenCompose, executors, and the common pool. It explains one question: on which thread does each stage of a pipeline run, and how do the Async method names change that?
Three forms of one method
Most stage-building methods on CompletableFuture come in three forms. thenApply is the example here.
| Form | Example | Where the function runs |
|---|---|---|
| Plain | `thenApply(fn)` | In the thread that completes the source future, or in the calling thread if the source is already complete |
| Async | `thenApplyAsync(fn)` | As a new task on the future's default executor (normally `ForkJoinPool.commonPool()`) |
| Async with executor | `thenApplyAsync(fn, executor)` | As a new task on the executor you pass |
The Async suffix does not change what the function computes or what the result is. It changes only where, and in which thread, the function is scheduled.
The methods that have all three forms are thenApply, thenAccept, thenRun, thenCompose, thenCombine, thenAcceptBoth, runAfterBoth, applyToEither, acceptEither, runAfterEither, handle, and whenComplete. exceptionally had no async form until Java 12, which added exceptionallyAsync. join, get, allOf, and anyOf have no variants. They do not run your code on behalf of a stage.
Seeing the threads
The following program registers three stages on the same incomplete future and completes it from a thread named completer. It also shows a stage attached to an already-completed future.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadNames {
static String thread() {
return Thread.currentThread().getName();
}
public static void main(String[] args) throws Exception {
ExecutorService io = Executors.newFixedThreadPool(2, r -> new Thread(r, "io-worker"));
try {
String early = CompletableFuture.completedFuture("x")
.thenApply(v -> "thenApply on completed future ran on " + thread())
.join();
System.out.println(early);
CompletableFuture<String> source = new CompletableFuture<>();
CompletableFuture<String> plain =
source.thenApply(v -> "thenApply ran on " + thread());
CompletableFuture<String> async =
source.thenApplyAsync(v -> "thenApplyAsync ran on " + thread());
CompletableFuture<String> custom =
source.thenApplyAsync(v -> "thenApplyAsync(io) ran on " + thread(), io);
Thread completer = new Thread(() -> source.complete("go"), "completer");
completer.start();
completer.join();
System.out.println(plain.join());
System.out.println(async.join());
System.out.println(custom.join());
} finally {
io.shutdown();
}
}
}Typical output:
thenApply on completed future ran on main
thenApply ran on completer
thenApplyAsync ran on ForkJoinPool.commonPool-worker-1
thenApplyAsync(io) ran on io-workerThe worker number may differ on your machine. The first two lines show the rule for plain methods. If the source is already complete when you attach the stage, the stage runs immediately in the attaching thread (main). If the source is not yet complete, the stage runs inside the complete call of whichever thread finishes the source.
The cost of running in the completing thread
Plain stages are cheap, because no task is submitted and no thread hop happens. They are the right choice for small, fast, non-blocking work such as mapping a field or wrapping a value.
The cost is that a slow callback holds up the thread that completed the future. That thread may be a pool worker you wanted for something else, or the caller of complete. The next program shows this directly.
import java.util.concurrent.CompletableFuture;
public class SlowCallback {
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
CompletableFuture<String> plain = new CompletableFuture<>();
plain.thenAccept(v -> sleep(500));
long start = System.nanoTime();
plain.complete("x");
System.out.println("plain: complete() took about "
+ (System.nanoTime() - start) / 1_000_000 + " ms");
CompletableFuture<String> async = new CompletableFuture<>();
CompletableFuture<Void> done = async.thenAcceptAsync(v -> sleep(500));
start = System.nanoTime();
async.complete("x");
System.out.println("async: complete() took about "
+ (System.nanoTime() - start) / 1_000_000 + " ms");
done.join();
}
}The first complete call takes about 500 ms because the callback runs inside it. The second returns in about a millisecond or less, because the callback was only submitted. The final join keeps the JVM alive until the common pool thread (a daemon thread) finishes.
What the default executor is
thenApplyAsync(fn) without an executor uses the future's defaultExecutor(). For a standard CompletableFuture this is ForkJoinPool.commonPool(), with one exception. If the common pool's parallelism is less than 2, which can happen on a single-core machine or with -Djava.util.concurrent.ForkJoinPool.common.parallelism=1, the class starts a new thread for each async task. This avoids stalling on a pool that is too small.
Three details are worth remembering:
- Dependent stages inherit nothing from their parents. A stage created with
thenApplyAsync(fn, io)runs onio, but a laterthenApplyon its result runs on whichever thread completes that stage, which is aniothread. - Stages that are plain methods inherit the thread of whatever completed their parent. This is why a long chain of plain stages after one async stage usually stays on that single worker.
- In Java 9 and later you can subclass
CompletableFutureand overridedefaultExecutor()andnewIncompleteFuture(). Then everyAsyncmethod without an explicit executor uses your pool, and derived stages keep your subclass.
Hopping between pools
Passing an executor to each Async call lets you shape a pipeline so each step runs on a pool suited to it.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Hop {
static String thread() {
return Thread.currentThread().getName();
}
public static void main(String[] args) {
ExecutorService io = Executors.newFixedThreadPool(2, r -> new Thread(r, "io"));
ExecutorService cpu = Executors.newFixedThreadPool(2, r -> new Thread(r, "cpu"));
try {
String result = CompletableFuture
.supplyAsync(() -> "payload fetched on " + thread(), io)
.thenApplyAsync(s -> s + ", parsed on " + thread(), cpu)
.thenApplyAsync(s -> s + ", stored on " + thread(), io)
.join();
System.out.println(result);
} finally {
io.shutdown();
cpu.shutdown();
}
}
}It prints payload fetched on io, parsed on cpu, stored on io. Each hop costs a task submission, so do not hop for trivial work.
Variants and `thenCompose`
For thenComposeAsync(fn, executor), the executor runs only fn, the function that creates the inner future. It does not run the inner future's work. If fn calls supplyAsync(..., otherPool), that work runs on otherPool regardless. The outer future completes when the inner one does, and the next plain stage then runs in whichever thread completed the inner future.
Timeouts and a hidden thread
orTimeout and completeOnTimeout complete the future from an internal scheduler thread named CompletableFutureDelayScheduler. Any plain stage attached to that future then runs on that single thread when the timeout fires. A slow callback there would delay every other timeout in the JVM.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class TimeoutThread {
public static void main(String[] args) {
CompletableFuture<String> slow = new CompletableFuture<>();
String where = slow
.completeOnTimeout("late", 100, TimeUnit.MILLISECONDS)
.thenApplyAsync(v -> v + " handled on " + Thread.currentThread().getName())
.join();
System.out.println(where);
}
}Here thenApplyAsync moves the callback off the delay scheduler and onto a common pool worker.
Ordering is not guaranteed
If you attach several plain stages to one future, they all run in the completing thread, but the order is not specified. In practice the most recently attached stage often runs first. Never write code that depends on this order. If you need a sequence, chain the stages (a.thenApply(...).thenApply(...)) so each depends on the one before it.
Choosing a variant
Rules of thumb:
- Use plain methods for short, non-blocking transformations.
- Use
Asyncwith an explicit executor for anything that blocks, such as JDBC calls, file reads, orThread.sleep. The common pool is small and shared by parallel streams, so blocking there starves unrelated code. - Use
Asyncafter a future completed by a thread you do not own, such as a timeout scheduler, a network event loop, or a UI thread. This moves your callback off that thread. - Do not use
Asyncout of habit. Each one adds a task submission and a thread hop, and it does not make the work itself faster.
Exercise
A future is completed by a Netty event-loop thread. You attach .thenApply(row -> repository.loadBlocking(row)), where loadBlocking takes 200 ms. What goes wrong, and how do you fix it?
Show answer
The plain thenApply callback runs on the event-loop thread that completes the future, so the 200 ms blocking call stalls that thread and every other connection it serves. Fix it by moving the callback to a thread pool intended for blocking work: .thenApplyAsync(row -> repository.loadBlocking(row), ioExecutor).
Exercise
You call f.thenApply(fn) on a future that is already complete, from a thread named worker-3. On which thread does fn run, and what changes if you call f.thenApplyAsync(fn) instead?
Show answer
With thenApply, fn runs immediately in worker-3, the calling thread, before thenApply returns. With thenApplyAsync, fn is submitted to the default executor (normally the common pool) and runs on one of its threads, so thenApplyAsync returns before fn necessarily runs.