0

I'm looking for the best way, in Java, to asynchronously run some tasks calculating some values and when they're all gathered, run some further calculation on them.

I thought I was going down the right path with this

    var f1 = CompletableFuture.supplyAsync(() -> Service.findPlayers(filter, maxCount, LeaderboardType.Unranked));
    var f2 = CompletableFuture.supplyAsync(() -> Service.findPlayers(filter, maxCount, LeaderboardType._1x1_RM));
    var f3 = CompletableFuture.supplyAsync(() -> Service.findPlayers(filter, maxCount, LeaderboardType.TG_RM));

    var x = CompletableFuture.allOf(f1, f2, f3);

until I realized that unfortunately allOf() doesn't return a list with the results of f1, f2 and f3 but void instead? Is there any alternative? Otherwise I'd have to store the results in some sort of "global variable" and then access them from the when() call, which completely defeats the whole purpose of using supplyAync vs runAsync, I guess.

halfer
  • 19,824
  • 17
  • 99
  • 186
devoured elysium
  • 101,373
  • 131
  • 340
  • 557

1 Answers1

0

You do CompletableFuture::allOf, just like you do it now, but also join it :

CompletableFuture.allOf(f1, f2, f3).join();

and then you do:

Stream.of(f1, f2, f3)
      .map(CompletableFuture::join)
      .....

There is no joining in the above operation, though, as the features are already completed.

EDIT

If you do not want to block:

 var f1 = ...
 var f2 = ...
 var f3 = ...

 CompletableFuture.allOf(f1, f2, f3)
                  .thenAccept(x -> {
                       f1.join();
                       f2.join();
                       f3.join();
                   })
Eugene
  • 117,005
  • 15
  • 201
  • 306