简体   繁体   中英

CompletableFuture.allOf cancel other futures when one throws exception

Java 8's CompletableFuture.allOf(CompletableFuture<?>...cfs) will return a CompletableFuture that is completed when all the given futures complete, or throws a CompletionException if one of the futures completes with an exception.

If one of my futures completes with an exception, will CompletableFuture.allOf wait for the remaining futures to complete before throwing the CompletionException or will it cancel the remaining futures?

If it waits for all futures to complete, it there any way to make it return immediately when any future throws an exception and cancel the remaining futures?

If one of my futures completes with an exception, will CompletableFuture.allOf wait for the remaining futures to complete before throwing the CompletionException

Yes, it will still wait for all the futures to complete.

You could use this helper method to create a CompletableFuture which completes exceptionally once any of the futures does so.

public static CompletableFuture allOfTerminateOnFailure(CompletableFuture<?>... futures) {
    CompletableFuture<?> failure = new CompletableFuture();
    for (CompletableFuture<?> f: futures) {
        f.exceptionally(ex -> {
            failure.completeExceptionally(ex);
            return null;
        });
    }
    return CompletableFuture.anyOf(failure, CompletableFuture.allOf(futures));
}

If you also want to cancel all other futures if one of them completes exceptionally, you could do it like this before returning from this method:

failure.exceptionally(ex -> {
    Arrays.stream(futures).forEach(f -> f.cancel(true));
    return null;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM