您如何访问已传递给CompletableFuture allOf的已完成期货?

时间:2015-12-10 20:25:44

标签: java java-8 completable-future

我试图掌握Java 8 CompletableFuture。我怎样才能将这些人加入到“allOf”之后再归还给他们。下面的代码不起作用,但让你知道我尝试过的。

在javascript ES6中我会做

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

到目前为止我在Java方面的努力

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));

}

1 个答案:

答案 0 :(得分:17)

CompletableFuture#allOf方法不公开传递给它的已完成CompletableFuture个实例的集合。

  

返回一个新的CompletableFuture,它在所有的时候完成   给定CompletableFuture完成。如果给出任何一个   CompletableFuture完全异常,然后返回   CompletableFuture也是这样做的,CompletionException持有CompletableFuture   这个例外是其原因。 否则,结果(如果有的话)   给定CompletableFuture s不会反映在返回的内容中   CompletableFuture,但可以通过检查获得   单独即可。如果未提供CompletableFuture,则返回a   null已使用值allOf完成。

请注意,Person还会考虑已完成的异常完成的期货。所以你不会总是有一个CompletableFuture可以使用。你可能实际上有一个异常/ throwable。

如果您知道自己正在使用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方法(暂时忽略它&#39; sa 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); } ,你可以做到

{{1}}
相关问题