gpt4 book ai didi

java - CompletableFuture.supplyAsync() 中 ForkJoinPool 的行为

转载 作者:行者123 更新时间:2023-12-03 14:03:37 29 4
gpt4 key购买 nike

我正在比较 的行为CompletableFuture.supplyAsync() 在我设置自定义 ExecutorService 或我希望我的供应商由默认执行程序(如果未指定)执行的两种情况下,即 ForkJoinPool.commonPool()
让我们看看区别:

public class MainApplication {
public static void main(final String[] args) throws ExecutionException, InterruptedException {

Supplier<String> action1 = () -> {
try {
Thread.sleep(3000);
}finally {
return "Done";
}
};
Function<String, String> action2 = (input) -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
return input + "!!";
}
};

final ExecutorService executorService = Executors.newFixedThreadPool(4);

CompletableFuture.supplyAsync(action1, executorService)
.thenApply (action2)
.thenAccept (res -> System.out.println(res));

System.out.println("This is the end of the execution");

}
}
在这种情况下,我通过 执行人服务 到我的 supplyAsync() 并打印:

This is the end of the execution

Done!!


所以 “完成”在主执行结束后打印。
但如果我改用:
CompletableFuture.supplyAsync(action1)
所以我没有通过我的自定义 executorService 并且 CompletableFuture 类在后台使用 ForkJoinPool.commonPool() 然后根本不打印“完成”:

This is the end of the execution

Process finished with exit code 0


为什么?

最佳答案

在这两种情况下,当您这样做时

CompletableFuture.supplyAsync(action1, executorService)
.thenApply (action2)
.thenAccept (res -> System.out.println(res));

您无需等待任务完成。但是随后您的程序将要退出,并且常见的 fork 加入池的方式有所不同:
ForkJoinPool.commonPool()

和定期执行服务:
final ExecutorService executorService = Executors.newFixedThreadPool(4);

..对尝试调用 System.exit(...) 等效时使用react。

这就是 doc says关于fork join common pool,需要注意的是:

However this pool and any ongoing processing are automatically terminated upon program System.exit(int). Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.



即链接到 ExecutorService docs ,你可能会注意:

The shutdown() method will allow previously submitted tasks to execute before terminating



我认为这可能是您询问的差异。

关于java - CompletableFuture.supplyAsync() 中 ForkJoinPool 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035090/

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