The method CompletableFuture#allOfdoes not provide a collection of completed instances CompletableFuturethat were passed to it.
CompletableFuture, , CompletableFuture. - CompletableFuture , CompletableFuture CompletionException . , , CompletableFuture CompletableFuture, . CompletableFuture, CompletableFuture null.
, allOf , . , Person . , /throwable.
CompletableFuture, ,
CompletableFuture.allOf(p1, p2).thenAccept(it -> {
Person person1 = p1.join();
Person person2 = p2.join();
});
, ( ), , allOf
CompletableFuture<Person>[] persons = new CompletableFuture[] { p1, p2 };
CompletableFuture.allOf(persons).thenAccept(ignore -> {
for (int i = 0; i < persons.length; i++ ) {
Person current = persons[i].join();
}
});
combinePersons ( @Test), Person[], Person ,
@Test
public Person[] combinePersons() throws Exception {
CompletableFuture<Person> p1 = CompletableFuture.supplyAsync(() -> {
return new Person("p1");
});
CompletableFuture<Person> p2 = CompletableFuture.supplyAsync(() -> {
return new Person("p1");
});
// make sure not to change the contents of this array
CompletableFuture<Person>[] persons = new CompletableFuture[] { p1, p2 };
// this will throw an exception if any of the futures complete exceptionally
CompletableFuture.allOf(persons).join();
return Arrays.stream(persons).map(CompletableFuture::join).toArray(Person[]::new);
}