【发布时间】:2018-01-11 10:03:39
【问题描述】:
CompletableFuture<T> 类的get() 和join() 方法有什么区别?
下面是我的代码:
List<String> process() {
List<String> messages = Arrays.asList("Msg1", "Msg2", "Msg3", "Msg4", "Msg5", "Msg6", "Msg7", "Msg8", "Msg9",
"Msg10", "Msg11", "Msg12");
MessageService messageService = new MessageService();
ExecutorService executor = Executors.newFixedThreadPool(4);
List<String> mapResult = new ArrayList<>();
CompletableFuture<?>[] fanoutRequestList = new CompletableFuture[messages.size()];
int count = 0;
for (String msg : messages) {
CompletableFuture<?> future = CompletableFuture
.supplyAsync(() -> messageService.sendNotification(msg), executor).exceptionally(ex -> "Error")
.thenAccept(mapResult::add);
fanoutRequestList[count++] = future;
}
try {
CompletableFuture.allOf(fanoutRequestList).get();
//CompletableFuture.allOf(fanoutRequestList).join();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapResult.stream().filter(s -> !s.equalsIgnoreCase("Error")).collect(Collectors.toList());
}
这两种方法我都试过了,但我看不出结果有什么不同。
【问题讨论】:
-
get()要求您捕获已检查的异常。当您从get()更改为join()时,您应该注意到不同之处,因为您会立即收到一个编译器错误,指出try块中既没有InterruptedException也没有ExecutionException。 -
@holi-java:
join()不能被打断。 -
@Holger 是的,先生。我发现我不能打断任务。
-
好吧
get存在,因为CompletableFuture实现了要求它的Future接口。join()很可能已经被引入,以避免在组合期货时需要在 lambda 表达式中捕获已检查的异常。在所有其他用例中,请随意使用您喜欢的任何内容。 -
在线程上同时使用 join 或 get 作为块真的有意义吗?难道我们不能通过使用其他组合方法来创建异步函数链来使这个异步。当然,它取决于功能。但是在例如的情况下Spring 中由控制器方法调用的服务方法返回可完成的未来,根本不调用 get 或加入服务方法更有意义。是吗?
标签: java java-8 completable-future