2017-08-03 24 views
13

是什么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()); 
} 

我试图与这两种方法,但没有什么区别结果。

谢谢

+4

'得到()'需要你捕获检查的异常。当你从'get()'改变到'join()'时你应该注意到它的区别,因为你会立即得到一个编译器错误,说'try'块中没有抛出'InterruptedException'和'ExecutionException'。 – Holger

+1

@ holi-java:'join()'不能被打断。 – Holger

+0

@霍尔是的,先生。我发现我不能打断任务。 –

回答

7

唯一的区别是方法如何抛出异常。 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() 

相反,它抛出选中 CompletionException。所以你并不需要一个try-catch块,而是使用disscused List<String> process功能

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

时,你可以充分利用exceptionally()方法你可以找到既get()join()实施here