How do you access completed futures passed to CompletableFuture allOf?

I am trying to grab Java 8 CompletableFuture. How can I attach them to a person and return them after "allOf". The code does not work, but gives you an idea of ​​what I tried.

In javascript ES6 I would do

Promise.all([p1, p2]).then(function(persons) {
   console.log(persons[0]); // p1 return value     
   console.log(persons[1]); // p2 return value     
});

My efforts in java so far

public class Person {

        private final String name;

        public Person(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

    }

@Test
public void combinePersons() throws ExecutionException, InterruptedException {
    CompletableFuture<Person> p1 = CompletableFuture.supplyAsync(() -> {
        return new Person("p1");
    });

    CompletableFuture<Person> p2 = CompletableFuture.supplyAsync(() -> {
        return new Person("p1");
    });

    CompletableFuture.allOf(p1, p2).thenAccept(it -> System.out.println(it));

}
+4
source share
1 answer

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

// make sure not to change the contents of this array
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);
}
+9

Source: https://habr.com/ru/post/1619405/