3

If I have Collection<CompletableFuture<MyResult>>, I expect to convert this into CompletableFuture<Collection<MyResult>>. So after conversion I have only one future and can easyly write bussines logic on MyResult collection using methods from CompletableFuture like thenApply, thenAccept etc. But CompletableFuture#allOf have result type Void so after invoking it I get "no results". E.g. I can not retrieve (as I understand) any results from returned future that correspods to Collection<CompletableFuture<MyResult>>.

I have a doubt that CompletableFuture#allOf just return the Future wich is completed after all in collection. So I can invoke CompletableFuture#allOf(...).isDone and then manually (!) in cycle tranform Collection<CompletableFuture> to CompletableFuture<Collection>, Is my assumption right?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 2
    Your assumption is correct. `allOf` doesn't supply any data but rather it lets you trigger further computations when all futures have completed. You can then use the triggered `CompletionStage` to reassemble the results into a collection or do whatever else is appropriate. See the answers to http://stackoverflow.com/q/30025428/3920048 for some examples of how to make a list of futures into a future of list. – Misha Sep 13 '15 at 07:18
  • This is one of the things why I still find [Guava's `Futures.allAsList()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/Futures.html#allAsList(com.google.common.util.concurrent.ListenableFuture...)) method incredibly useful. – fps Sep 14 '15 at 18:16
  • @Misha - that should be an answer in imho. – John McClean Sep 19 '15 at 20:45

2 Answers2

0

Yes, the allOf method does not supply data, but does signal that all futures have been completed. This eliminates the need of using the more cumbersome countdown latch approach. The expectation is that you would then convert the completed futures back into a usable Collection to apply your business logic. See this question for implementation details. A great discussion of this topic is available at this blog post.

Community
  • 1
  • 1
Austin
  • 8,018
  • 2
  • 31
  • 37
0

if you need CompletableFuture<Collection<MyResult>> as result you can get it by using allAsList method in https://github.com/spotify/completable-futures (spotify-completlablefutures library). CompletableFutures.allAsList(List<CompletableFuture<MyResult>>) will give you CompletableFuture<List<MyResult>>.

Vishal Gupta
  • 1
  • 1
  • 2