2017-08-03 6 views
13

を得る:completablefuture参加対CompletableFuture.get()とCompletableFuture.join()の違い</p> <p>以下は私のコードでは何

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

'取得()は'あなたを必要としていますので、あなたは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()'に変更したときには、 'InterruptedException'も' ExecutionException'も 'try'ブロックにスローされないというコンパイラエラーが発生するので、違いを気付かなければなりません。 – Holger

+1

@ holi-java: 'join()'は中断できません。 – Holger

+0

@Holgerはい、サー。私は仕事を中断することができないことがわかった。 –

答えて

7

例外は例外をスローする方法です。 get()は例外がは、彼らがあなたのコードで処理する必要があることを意味例外をチェックされ、両方の

V get() throws InterruptedException, ExecutionException; 

としてFutureインタフェースで宣言されています。あなたのコードで見ることができるように、IDEの自動コードジェネレータは、あなたのためにtry-catchブロックを作成するかどうか尋ねました。

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

join()方法はチェック例外をスローしません。

public T join() 

代わりに、それは未チェック CompletionExceptionをスローします。あなたは両方のget()join()実装here

関連する問題