我在库中公开了一个方法,该方法返回一个 CompletableFuture。该方法的计算发生在单线程执行器上,这是我的瓶颈,因此我不希望任何后续工作发生在同一线程上。
如果我使用返回“supplyAsync”结果的简单方法,我会将我宝贵的线程暴露给调用者,调用者可能会添加同步操作(例如通过 thenAccept),这可能会在该线程上占用一些 CPU 时间。
重现如下:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CfPlayground {
private ExecutorService preciousExecService = Executors.newFixedThreadPool(1);
CfPlayground() {}
private static void log(String msg) {
System.out.println("[" + Thread.currentThread().getName() + "] " + msg);
}
CompletableFuture<String> asyncOp(String param) {
return CompletableFuture.supplyAsync(() -> {
log("In asyncOp");
return "Hello " + param;
}, preciousExecService);
}
void syncOp(String salutation) {
log("In syncOp: " + salutation);
}
void run() {
log("run");
asyncOp("world").thenAccept(this::syncOp);
}
public static void main(String[] args) throws InterruptedException {
CfPlayground compFuture = new CfPlayground();
compFuture.run();
Thread.sleep(500);
compFuture.preciousExecService.shutdown();
}
}
这确实打印:
[main] run
[pool-1-thread-1] In asyncOp
[pool-1-thread-1] In syncOp: Hello world
我发现的一个解决方案是引入另一个执行器,并在返回 CompletableFuture 之前添加一个无操作 thenApplyAsync 与该执行器
CompletableFuture<String> asyncOp(String param) {
return CompletableFuture.supplyAsync(() -> {
log("In asyncOp");
return "Hello " + param;
}, preciousExecService).thenApplyAsync(s -> s, secondExecService);
}
这可行,但感觉不太优雅——有更好的方法吗?
没有任何功能可以将您的完成与相关操作的执行分离。当链接依赖操作的线程已经完成注册并且执行器的线程完成未来时,如果没有给出其他执行器,哪个其他线程应该执行依赖操作?
您将另一个操作与不同的执行者链接起来的方法似乎是您能得到的最好的方法。然而,值得注意的是,如果发生异常完成,异常会在不评估传递给的函数的情况下传播thenApply
。如果调用者链接了类似的操作,则此异常传播可能再次导致线程暴露whenComplete
, handle
, or exceptionally
.
另一方面,您不需要指定辅助执行程序,因为您可以使用async不带 executor 参数的方法,获取默认(通用 Fork/Join)池。
所以链接.whenCompleteAsync((x,y) -> {})
是迄今为止解决您问题的最佳方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)