completablefuture加入vs获得 [英] completablefuture join vs get

查看:69
本文介绍了completablefuture加入vs获得的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CompletableFuture.get()CompletableFuture.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());
}

我尝试了两种方法,但结果没有差异.

I have tried with both methods but I see no difference in result.

推荐答案

唯一的区别是方法引发异常的方式. get()Future接口中声明为

the only difference is how methods throw exceptions. get() is declared in Future interface as

V get() throws InterruptedException, ExecutionException;

这两个异常都是 checked 异常,这意味着它们需要在您的代码中进行处理.正如您在代码中看到的那样,IDE中的一个自动代码生成器询问是否代表您创建try-catch块.

The exceptions are both checked exceptions which means they need to be handled in your code. As you can see in your code an automatic code generator in your IDE asked if to creat try-catch block on your behalf.

try {
  CompletableFuture.allOf(fanoutRequestList).get() 
} catch (InterruptedException | ExecutionException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

join()方法不会引发 checked 异常.

public T join()

相反,它抛出 unchecked CompletionException.因此,您不需要try-catch块,而是可以在使用所讨论的List<String> process函数时完全利用exceptionally()方法

Instead it throws unchecked CompletionException. So you do not need a try-catch block and instead you can fully harness exceptionally() method when using the disscused List<String> process function

CompletableFuture<List<String>> cf = CompletableFuture
    .supplyAsync(this::process)
    .exceptionally(this::getFallbackListOfStrings) // Here you can catch e.g. {@code join}'s CompletionException
    .thenAccept(this::processFurther);

您可以找到get()join()实现 查看全文

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