CompletableFuture recoverWith equivalent? i.e. exceptionally but return CompletableFuture

Is this what you are looking for? askPong(“cause error”) .handle( (pong, ex) -> ex == null ? CompletableFuture.completedFuture(pong) : askPong(“Ping”) ).thenCompose(x -> x); Also, do not use the …Async methods unless you intend for the body of the supplied function to be executed asynchronously. So when you do something like .handleAsync((x, t) -> { if … Read more

CompletableFuture / ForkJoinPool Set Class Loader

I ran into something similar and came up with a solution that does not use reflection and seems to work well with JDK9-JDK11. Here is what the javadocs say: The parameters used to construct the common pool may be controlled by setting the following system properties: java.util.concurrent.ForkJoinPool.common.threadFactory – the class name of a ForkJoinPool.ForkJoinWorkerThreadFactory. The … Read more

In which thread do CompletableFuture’s completion handlers execute?

As @nullpointer points out, the documentation tells you what you need to know. However, the relevant text is surprisingly vague, and some of the comments (and answers) posted here seem to rely on assumptions that aren’t supported by the documentation. Thus, I think it’s worthwhile to pick it apart. Specifically, we should read this paragraph … Read more

CompletableFuture is not getting executed. If I use the ExecutorService pool it works as expected but not with the common ForkJoinPool

TL;DR: The ForkJoinPool uses daemon threads, whereas the ExecutorService is using non-daemon threads. The latter keep the JVM alive; the former do not. Also, the main thread is a non-daemon thread and when you block it waiting for the CompletableFuture to complete it remains alive (thus keeping the JVM alive). Daemon vs Non-Daemon Threads A … Read more

Convert from List to CompletableFuture

Use CompletableFuture.allOf(…): static<T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> com) { return CompletableFuture.allOf(com.toArray(new CompletableFuture<?>[0])) .thenApply(v -> com.stream() .map(CompletableFuture::join) .collect(Collectors.toList()) ); } A few comments on your implementation: Your use of .thenComposeAsync, .thenApplyAsync and .thenCombineAsync is likely not doing what you expect. These …Async methods run the function supplied to them in a separate thread. So, in your case, you … Read more