【问题标题】:How do you access completed futures passed to CompletableFuture allOf?您如何访问传递给 CompletableFuture allOf 的已完成期货?
【发布时间】:2015-12-10 20:25:43
【问题描述】:

我正在尝试掌握 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));

}

【问题讨论】:

    标签: java java-8 completable-future


    【解决方案1】:

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

    返回一个新的CompletableFuture,当所有的 给定CompletableFutures 完成。如果任何给定的 CompletableFutures 异常完成,则返回 CompletableFuture 也这样做,CompletionException 持有 这个异常作为它的原因。 否则,结果(如果有) 给定CompletableFutures 不会反映在返回的 CompletableFuture,但可以通过检查获得 单独。如果没有提供CompletableFutures,则返回一个 CompletableFuture 以值 null 完成。

    请注意,allOf 还将异常完成的期货视为已完成。所以你不会总是有一个Person 可以使用。您实际上可能有异常/可抛出。

    如果您知道您正在使用的CompletableFutures 的数量,请直接使用它们

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

    【讨论】:

    • @user874774 哪种方法*?你的combinePersons 方法?你需要在返回的CompletableFuture(或get)上join,尽管这些是阻塞的。
    • @user 您必须使用提到的方法之一阻止并重新处理您传入的数组。
    • @user 你没有。您使用方法来阻止,保证计算是完整的。然后使用数组从每个未来中提取Person 对象。
    • @srborlongan 哦,是的,我忘了它的存在。
    • @SotiriosDelimanolis 我认为在persons[i].join() 中调用 join() 而不是 get() 更好,因为如果您在 thenAccept 块中,所有承诺都会正确完成,因此任何承诺都会异常完成。如果不处理异常,代码比从不缓存更简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2015-05-17
    • 2018-06-02
    • 1970-01-01
    • 2018-08-13
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多