dev*_*747 1 java completable-future
我正在努力实现这样的目标.这是一个表达意图的组成示例.
我想要所有可完成的期货执行并将所有结果合并到一个结果并返回.因此,对于下面的示例,集合allResults应该具有字符串"one","two","three",每个3次.我希望他们都能并行而不是连续运行.
任何指向我可用于实现此目的的可完成未来的API的指针都将非常有用.
public class Main {
public static void main(String[] args) {
int x = 3;
List<String> allResuts;
for (int i = 0; i < x; i++) {
//call getCompletableFutureResult() and combine all the results
}
}
public static CompletableFuture<List<String>> getCompletableFutureResult() {
return CompletableFuture.supplyAsync(() -> getResult());
}
private static List<String> getResult() {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
return list;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Venkata Raju的答案有问题.拉朱使用GET对未来调用,它是一个阻塞调用,并杀死在异步风格编码的主要目的.总是避免做到期货.
有大量的内置方法围绕处理未来的值,如thenApply,thenAccept,thenCompose,thenCombine等.
CompletableFuture.allOf 当你必须处理多个期货时,可以使用方法.
它具有以下签名
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
Run Code Online (Sandbox Code Playgroud)
附注: CompletableFuture.anyOf当您只关心第一个未来完成时可以使用.allOf当您需要完成所有期货时使用.
我会使用CompletableFuture.allOf以下列方式编写您的规范.
public class DorjeeTest {
public static CompletableFuture<List<String>> getCompetableFutureResult() {
return CompletableFuture.supplyAsync(() -> getResult());
}
public static List<String> getResult() {
return Lists.newArrayList("one", "two", "three");
}
public static void testFutures() {
int x = 3;
List<CompletableFuture<List<String>>> futureResultList = Lists.newArrayList();
for (int i = 0; i < x; i++) {
futureResultList.add(getCompetableFutureResult());
}
CompletableFuture[] futureResultArray = futureResultList.toArray(new CompletableFuture[futureResultList.size()]);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray);
CompletableFuture<List<List<String>>> finalResults = combinedFuture
.thenApply(voidd ->
futureResultList.stream()
.map(future -> future.join())
.collect(Collectors.toList()));
finalResults.thenAccept(result -> System.out.println(result));
}
public static void main(String[] args) {
testFutures();
System.out.println("put debug break point on this line...");
}
}
Run Code Online (Sandbox Code Playgroud)