下面是我的代码:
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()
在future
接口中声明为
V get() throws InterruptedException, ExecutionException;
这两个异常都是检查异常,这意味着它们需要在代码中处理。正如您在代码中看到的那样,IDE中的自动代码生成器询问是否为您创建try-catch块。
try {
CompletableFuture.allOf(fanoutRequestList).get()
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
join()
方法不引发检查异常。
public T join()
CompletableFuture<List<String>> cf = CompletableFuture
.supplyAsync(this::process)
.exceptionally(this::getFallbackListOfStrings) // Here you can catch e.g. {@code join}'s CompletionException
.thenAccept(this::processFurther);