ThenApply Vs ThenApplyAsync Thread Choice
thenApplyAsync pins a stage to an executor; thenApply on an already-completed future runs synchronously on the calling thread, making stage placement explicit.
Code
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadChoice {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor(
r -> new Thread(r, "pool-worker"));
// 1) 未完成的 future + thenApplyAsync(pool):阶段被钉到指定池线程执行
CompletableFuture<String> async = CompletableFuture
.supplyAsync(() -> "payload", pool)
.thenApplyAsync(v -> {
System.out.println("async stage on: " + Thread.currentThread().getName());
return v.toUpperCase();
}, pool);
String value = async.join();
System.out.println(value);
// 2) 已完成的 future + thenApply:结果就绪,当前调用线程立即同步执行
String synced = async.thenApply(v -> {
System.out.println("sync stage on: " + Thread.currentThread().getName());
return v + "!";
}).join();
System.out.println(synced);
pool.shutdown();
}
}What the code does
ThenApply Vs ThenApplyAsync Thread Choice reduces to the class ThreadChoice and the function main.
Applying it
The demo output is labeled (async stage on:, sync stage on:), so every line of output can be traced to the operation that made it.
Statements that matter
ExecutorService pool = Executors.newSingleThreadExecutor(
r -> new Thread(r, "pool-worker"));
return v.toUpperCase();
return v + "!";
Interactive Tools for This Topic
FAQ
- What does ThenApply Vs ThenApplyAsync Thread Choice print when run?
- Invoke the file as-is — the `async stage on:`, `sync stage on:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.