[英]CompletableFuture.thenAccept can indeed block
Unlike stated in some blogs(eg I can't emphasize this enough: thenAccept()/thenRun() methods do not block ) CompletableFuture.thenAccept
can indeed block. 不像某些博客中所述(例如我不能强调这一点:thenAccept()/ thenRun()方法不会阻塞 )
CompletableFuture.thenAccept
确实可以阻止。 Consider the following code, uncommenting the pause
method call will cause thenAccept
to block: 考虑以下代码,取消注释
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);
Can we be sure that the following will not block? 我们可以确定以下内容不会阻止吗? It's my understanding that if the
supplyAsync
runs immediately then the thenAccept
could block, no? 我的理解是,如果
supplyAsync
立即运行,那么thenAccept
可以阻止,不是吗?
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
return "42";
}).thenAccept((dbl -> {
pause(500);
log.debug("Result: " + dbl);
}));
You are right, thenAccept()
will block if the future is already completed. 你是对的,
thenAccept()
如果未来已经完成,则thenAccept()
将阻止。 Also note that when it is not the case, it will cause the thread that completes it to block at the time of completion. 另请注意,如果不是这种情况,则会导致完成它的线程在完成时阻塞。
This is why you have thenAcceptAsync()
, which will run your Consumer
in a non-blocking way: 这就是为什么你有
thenAcceptAsync()
,它将以非阻塞方式运行你的Consumer
:
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
return "42";
}).thenAcceptAsync((dbl -> {
pause(500);
log.debug("Result: " + dbl);
}));
See also Which executor is used when composing Java CompletableFutures? 另请参阅编写Java CompletableFutures时使用哪个执行程序?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.