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()
.
Future vs CompletableFuture. CompletableFuture is an extension to Java's Future API which was introduced in Java 5. A Future is used as a reference to the result of an asynchronous computation.
Java 8 introduced the CompletableFuture class.CompletableFuture is at the same time a building block and a framework, with about 50 different methods for composing, combining, and executing asynchronous computation steps and handling errors.
A CompletableFuture is an extension to Java's Future API which was introduced in Java 8. A Future is used for asynchronous Programming. It provides two methods, isDone() and get(). The methods retrieve the result of the computation when it completes.
CompletableFuture is a Future . It overrides methods of future, meaning that you can wait for the result of the future, with or without a timeout. You can request the status of the future (whether it's done), etc. Waits if necessary for this future to complete, and then returns its result.
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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With