CompletableFuture · Topic 4 of 6
allOf and anyOf
Definition​
allOf waits until every future in a group is done, which is how you run many calls in parallel and then collect them. anyOf finishes as soon as the first one finishes.
Example code​
Run several calls in parallel and gather the results
import java.util.List;
import java.util.concurrent.CompletableFuture;
class Demo {
static CompletableFuture<String> call(String service, int millis) {
return CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(millis); } catch (InterruptedException ignored) { }
return service;
});
}
public static void main(String[] args) {
List<CompletableFuture<String>> calls = List.of(call("users", 150), call("orders", 100), call("prices", 50));
CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join(); // wait for all three
System.out.println(calls.stream().map(CompletableFuture::join).toList());
Object fastest = CompletableFuture.anyOf(call("slow", 300), call("fast", 20)).join(); // first one wins
System.out.println(fastest);
}
}
// Output:
// [users, orders, prices]
// fast
Finished this page? Track your progress (saved only in your browser).