javamultithreadingcompletable-futureforkjoinpool

In which thread do CompletableFuture's completion handlers execute?


I have a question about CompletableFuture method:

public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)

The thing is the JavaDoc says just this:

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function. See the CompletionStage documentation for rules covering exceptional completion.

What about threading? In which thread is this going to be executed? What if the future is completed by a thread pool?


Solution

  • The policies as specified in the CompletableFuture docs could help you understand better:

    • Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method.

    • All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task). To simplify monitoring, debugging, and tracking, all generated asynchronous tasks are instances of the marker interface CompletableFuture.AsynchronousCompletionTask.

    Update: I would also advice on reading this answer by @Mike as an interesting analysis further into the details of the documentation.