CompletableFuture.exceptionally with executor
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.
Note that as of JDK 12, there is CompletionStage.exceptionallyAsync
(and exceptionallyAsync
which takes an Executor
).