Search code examples
javaasynchronousjava-8guavacompletable-future

Replace Futures.successfulAsList with Java 8 CompletableFuture?


I am Looking for canonical code to replace Guava's Futures.successfulAsList() with Java 8's CompletableFuture code.

I think CompletableFuture.allOf() seems like a replacement for Futures.allAsList(), but I don't see anything quite like successfulAsList().


Solution

  • CompletableFuture.allOf(…) is actually closer to successfulAsList() than allAsList().

    Indeed, allOf() only completes after all the given futures have completed, be it with a value or an exception. You can then inspect each future to check how it completed (e.g. in a following thenAccept()/thenApply()).

    allAsList() does not have a close equivalent in CompletableFuture because it should fail as soon as any of the input futures fails. However, you could implement it with a combination of allOf() and chaining each input future with an exceptionally() that would make the future returned by allOf() immediately fail:

    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;
        }));