您如何访问已传递给CompletableFuture allOf的已完成期货? [英] How do you access completed futures passed to CompletableFuture allOf?

查看:119
本文介绍了您如何访问已传递给CompletableFuture allOf的已完成期货?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get a grip of Java 8 CompletableFuture. How can I join these to person and return them after "allOf". The code under is not working but gives you an idea of what I have tried.

在javascript ES6中,我会这样做

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

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

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

}


推荐答案

< a href =https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#allOf-java.util.concurrent.CompletableFuture...- =noreferrer > CompletableFuture#allOf 方法不会公开传递给它的已完成 CompletableFuture 实例的集合。


返回所有
时完成的新 CompletableFuture 给定 CompletableFuture 完成。如果给定的
CompletableFuture 中的任何一个异常完成,那么返回的
CompletableFuture 也会因此,使用 CompletionException 持有
此异常作为其原因。 否则,给定 CompletableFuture
结果(如果有)不会反映在返回的
CompletableFuture中,但可以通过单独检查
来获得
。如果没有提供 CompletableFuture ,则返回
CompletableFuture ,其值为 null

Returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. If any of the given CompletableFutures complete exceptionally, then the returned CompletableFuture also does so, with a CompletionException holding this exception as its cause. Otherwise, the results, if any, of the given CompletableFutures are not reflected in the returned CompletableFuture, but may be obtained by inspecting them individually. If no CompletableFutures are provided, returns a CompletableFuture completed with the value null.

注意 allOf 也考虑已完成的特殊期货。所以你不会总是有 Person 来使用。你可能实际上有一个异常/ throwable。

Note that allOf also considers futures that were completed exceptionally as completed. So you won't always have a Person to work with. You might actually have an exception/throwable.

如果你知道 CompletableFuture 的数量你正在使用,直接使用它们

If you know the amount of CompletableFutures you're working with, use them directly

CompletableFuture.allOf(p1, p2).thenAccept(it -> {
    Person person1 = p1.join();
    Person person2 = p2.join();
});

如果你不知道你有多少(你正在使用数组或列表) ,只需捕获传递到的数组 allOf

If you don't know how many you have (you're working with an array or list), just capture the array you pass to 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 对象,你可以做


If you wanted your combinePersons method (ignoring it's a @Test for now) to return a Person[] containing all the Person objects from the completed futures, you could do

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

这篇关于您如何访问已传递给CompletableFuture allOf的已完成期货?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆