CompletableFuture.thenAccept确实可以阻止

Rol*_*and 5 java multithreading asynchronous java-8 completable-future

不像某些博客中所述(例如我不能强调这一点:thenAccept()/ thenRun()方法不会阻止)CompletableFuture.thenAccept确实可以阻止.请考虑以下代码,取消注释pause方法调用将导致thenAccept阻塞:

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);
Run Code Online (Sandbox Code Playgroud)

我们可以确定以下内容不会阻止吗?这是我的理解,如果supplyAsync立即运行然后thenAccept可以阻止,不是吗?

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

Did*_*r L 8

你是对的,thenAccept()如果未来已经完成,将会阻止.另请注意,如果不是这种情况,则会导致完成它的线程在完成时阻塞.

这就是为什么你thenAcceptAsync()Consumer以非阻塞的方式运行你:

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

另请参阅编写Java CompletableFutures时使用哪个执行程序?