Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is CompletableFuture.allOf declared as CompletableFuture<Void>?

Why is CompletableFuture.allOf declared as CompletableFuture<Void> and not returning collection of results or something else? I think that was good idea to make CompletableFuture.anyOf return CompletableFuture<Object>, but I see these two methods connected and so I'm confused about what they return.

like image 878
Everv0id Avatar asked Dec 04 '15 08:12

Everv0id


1 Answers

anyOf has to somehow tell you what was the result of the specific CompletableFuture whose completion triggered anyOf. That's not necessary in case of allOf because you know which futures completed -- all of them.

allOf (just as anyOf) doesn't require that all futures bear the same type. So if it were to return a future of collection, it would have to be a collection of Object which is probably not what you want anyway.

If you really want to have allOf return a future of collection, it's fairly straightforward to write your own:

public static CompletableFuture<List<Object>> myAllOf(CompletableFuture<?>... futures) {
     return CompletableFuture.allOf(futures)
            .thenApply(x -> Arrays.stream(futures)
                    .map(f -> (Object) f.join())
                    .collect(toList())
            );
}

If you have a type-safe version of this problem and need to convert a collection of futures of a certain type to a future of collection of that same type, see this question for several examples: List<Future> to Future<List> sequence

like image 53
Misha Avatar answered Oct 10 '22 15:10

Misha