2017-08-03 16 views
13

olsun:completablefuture katılmak vs CompletableFuture.get() ve CompletableFuture.join() arasındaki fark</p> <p>Aşağıda benim kodudur nedir

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

Her iki yöntemleri ile denedim ama hiçbir fark içinde sonuç.

Teşekkürler

+4

'almak()' gerektirir hem get() ve join() uygulanmasını bulabilirsiniz Yani bir try-catch bloğu gerekmez ve

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

disscused List<String> process fonksiyonunu kullanırken yerine tam exceptionally() yöntemini koşum kontrol edilen istisnaları yakalamak için. 'Get() 'ile' join() 'arasında bir değişiklik yaptığınızda fark etmelisiniz, zira derhal bir' 'InterruptedException' 'ya da' ExecutionException '' try' bloğuna atılmadığını söyleyen bir derleyici hatası alacaksınız. – Holger

+1

@ holi-java: 'join()' kesilemez. – Holger

+0

@Holger evet, efendim. Görevi engelleyemedim. –

cevap

7

tek fark, yöntemlerin istisnaları nasıl attığıdır. get()

V get() throws InterruptedException, ExecutionException; 

istisnalar hem onlar kodunuzda ele alınması gerektiği anlamına geliyor ki istisnalar kontrol gibi Future arabiriminde bildirildi. Kodunuzda gördüğünüz gibi IDE'nizdeki otomatik kod üreteci sizin adınıza try-catch bloğu oluşturup oluşturmayacağınızı sordu.

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

join() yöntem istisnalar kontrol atmaz.

public T join() 

Bunun yerine kontrolsüz CompletionException atar. Sen here

İlgili konular