The behavior of thenAccept running on different threads in your code depends on how tasks are scheduled and executed in CompletableFuture. Here’s an explanation:
High-Level Explanation
Thread Pool for supplyAsync: CompletableFuture.supplyAsync by default uses the ForkJoinPool.commonPool, unless you specify a custom Executor. This means any asynchronous task (like supplyAsync) is picked up by one of the threads in the common pool.
Thread Propagation through Chaining:
If a stage in the chain (like handle, thenApply, thenAccept) does not explicitly specify an executor, it may execute:
On the thread completing the previous stage if it happens to be free.
On the calling thread if the task is already completed when the next stage is invoked (i.e., the main thread in this case).
Why thenAccept Runs on Different Threads:
When you print within supplyAsync, it likely adds enough delay for the task to fully complete asynchronously before thenAccept is registered. As a result, thenAccept executes on the ForkJoinPool.commonPool.
When you skip printing, the completion happens quickly enough that the main thread can take over execution of subsequent stages like thenApply and thenAccept.
Recorded Output Analysis
Case 1: When supplyAsync Prints
Thread Behavior:
supplyAsync: Runs on ForkJoinPool.commonPool-worker-1.
thenApply and thenAccept: Also run on the same worker thread since the asynchronous computation was still active in the pool when thenAccept was registered.
Reasoning:
Adding the out.println("supplyAsync") adds latency, keeping the computation on the worker thread longer.
Case 2: When supplyAsync Does Not Print
Thread Behavior:
thenApply and thenAccept: Run on the main thread (main/tid:1).
Reasoning:
Without the delay introduced by out.println, the supplyAsync task completes faster. When the chained operations like thenApply and thenAccept are registered, they are picked up by the thread initiating the chain (the main thread), since the completion occurs synchronously.
Takeaways
Thread Dependence: The thread running thenAccept (or other chained stages) depends on:
Whether the task completed asynchronously or synchronously.
How and when subsequent stages are registered.
Consistency with Custom Executor:
If you want predictable thread execution, supply an Executor to CompletableFuture methods:
ForkJoinPool Behavior: The ForkJoinPool.commonPool can sometimes reuse the same thread for subsequent tasks to optimize throughput, but it’s not guaranteed. Timing and task scheduling influence this behavior.
Solution for Controlling Execution Context
To ensure all stages consistently run on a specific thread pool:
val executor = Executors.newFixedThreadPool(4)CompletableFuture.supplyAsync({ out.println("supplyAsync") "Result"}, executor).thenApplyAsync({ it + " Processed"}, executor).thenAcceptAsync({ out.println(it)}, executor)