2017-05-12 58 views
5

'u engelleyebilir Bazı bloglarda (ör. I can't emphasize this enough: thenAccept()/thenRun() methods do not block) CompletableFuture.thenAccept gerçekten engellenebilir. pause yöntem çağrısı thenAccept engellemek neden olacaktır uncommenting aşağıdaki kodu düşünün:CompletableFuture.thenAccept gerçekten de

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { 
    log.trace("return 42"); 
    return "42"; 
}); 

//pause(1000); //uncommenting this will cause blocking of thenAccept 

future.thenAccept((dbl -> { 
    log.trace("blocking"); 
    pause(500); 
    log.debug("Result: " + dbl); 
})); 

log.trace("end"); 
pause(1000); 

aşağıda belirtilen bloke olmayacağından emin olabilir miyiz? supplyAsync hemen çalışırsa thenAccept'un engellenebileceğini anladım, değil mi?

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> { 
    return "42"; 
}).thenAccept((dbl -> { 
    pause(500); 
    log.debug("Result: " + dbl); 
})); 

cevap

6

Sen geleceksin zaten tamamlanması halinde thenAccept() engeller, haklısın. Ayrıca, durum böyle olmadığında, tamamlandığında iş parçacığının tamamlanmasını engelleyeceğini unutmayın.

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> { 
    return "42"; 
}).thenAcceptAsync((dbl -> { 
    pause(500); 
    log.debug("Result: " + dbl); 
})); 

da Which executor is used when composing Java CompletableFutures?

görün: Bir engellenmeyen bir şekilde Consumer çalışacağı, thenAcceptAsync() neden

budur

İlgili konular