2017-08-03 12 views
13

मिल क्या CompletableFuture.get() और CompletableFuture.join() के बीच का अंतरcompletablefuture में शामिल होने बनाम

नीचे मेरी कोड है:

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' block' में फेंक दिया गया है। – Holger

+1

@ होली-जावा: 'शामिल हों() 'बाधित नहीं हो सकता है। – Holger

+0

@ होल्गर हां, महोदय। मैंने पाया कि मैं कार्य को बाधित नहीं कर सकता। –

उत्तर

7

फर्क सिर्फ इतना है कि कैसे तरीकों अपवाद फेंक है। get()

V get() throws InterruptedException, ExecutionException; 

अपवाद दोनों अपवाद जाँच की है कि वे अपने कोड में नियंत्रित किया जा करने की जरूरत है इसका मतलब है के रूप में Future इंटरफ़ेस में घोषित किया जाता है। जैसा कि आप अपने कोड में देख सकते हैं, आपके आईडीई में एक स्वचालित कोड जनरेटर ने पूछा कि क्या आपकी ओर से प्रयास-पकड़ ब्लॉक बनाना है।

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

join() विधि अपवाद जाँच फेंक नहीं है।

public T join() 

इसके बजाय यह फेंकता अनियंत्रित CompletionException। तो अगर आप एक कोशिश पकड़ ब्लॉक की जरूरत नहीं है और इसके बजाय आप पूरी तरह से exceptionally() विधि जब 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); 

का उपयोग कर उपयोग कर सकते हैं आप दोनों get() और join() कार्यान्वयन here

संबंधित मुद्दे