Replace Futures.successfulAsList with Java 8 CompletingFuture?

I am looking for canonical code to replace Guava Futures.successfulAsList()

with Java 8 code CompletableFuture

.

I guess CompletableFuture.allOf()

it seems like a replacement Futures.allAsList()

, but I don't see anything like it successfulAsList()

.

+3


source to share


1 answer


CompletableFuture.allOf(…)

actually closer to successfulAsList()

than allAsList()

.

Indeed, it allOf()

only completes after all the specified futures are completed, be it a value or an exception. Then you can check each future to check how it is completed (like in the next thenAccept()

/ thenApply()

).



allAsList()

does not have a close equivalent in CompletableFuture

, as it should fail as soon as any of the entry futures fails. However, you can implement it with a combination allOf()

and bind each input future with a exceptionally()

, which will result in the immediate completion of the future returned allOf()

:

CompletableFuture<String> a = …, b = …, c = …;
CompletableFuture<Void> allWithFailFast = CompletableFuture.allOf(a, b, c);
Stream.of(a, b, c)
    .forEach(f -> f.exceptionally(e -> {
        allWithFailFast.completeExceptionally(e);
        return null;
    }));

      

+3


source







All Articles