gpt4 book ai didi

java - CompletableFuture.thenAccept 确实可以阻塞

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:58 32 4
gpt4 key购买 nike

与某些博客中所述(例如 I can't emphasize this enough: thenAccept()/thenRun() methods do not block )不同,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);

我们能确定下面的不会阻塞吗?据我了解,如果 supplyAsync 立即运行,那么 thenAccept 可能会阻塞,不是吗?

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

最佳答案

你是对的,如果 future 已经完成,thenAccept() 将阻塞。还要注意,当不是这种情况时,会导致完成它的线程在完成时阻塞。

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

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

另见 Which executor is used when composing Java CompletableFutures?

关于java - CompletableFuture.thenAccept 确实可以阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43933920/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com