Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 664
Miket Avatar asked Apr 10 '17 18:04

Miket


People also ask

What is the difference between future and CompletableFuture?

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.

Is Completable future blocking?

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.

What is CompletableFuture in java8?

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.

Why is the future Completable?

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.


1 Answers

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;
    }));
like image 141
Didier L Avatar answered Sep 28 '22 07:09

Didier L