Search code examples
asynchronousnonblockingcompletable-future

CompletableFuture.exceptionally with executor


CompletableFuture.exceptionally() method takes a lambda, but there is no flavor of the method that takes a custom Executor, or even an "...Async" flavor of it.

Which executor does exceptionally lambda run on? Would it be the same executor which ran the original CompletableFuture which threw the exception? Or (I would be surprised if this is the case) is it the commonPool ?


Solution

  • Form JDK bug discussion CompletableFuture.exceptionally may execute on main thread :

    CompletableFuture.exceptionally does not take an Executor argument since it is not designed to execute the exceptionally task asynchronously.

    If the dependent task is not yet completed then the exceptionally task will complete on the same thread that dependent tasks completes on.

    If the dependent task is completed then the exceptionally task will complete on the thread that executed the call to exceptionally.

    This is the same behaviour that will occur for any non-asynchronous execution, such as thenAccept.

    To guarantee that the exceptionally task is executed on a thread within the executor thread pool then it is necessary to use whenCompleteAsync or handleAsync and passing in the executor.