【问题标题】:Why does CompletableFuture.runAsync() not always submit to ForkJoinPool.commonPool()?为什么 CompletableFuture.runAsync() 并不总是提交给 ForkJoinPool.commonPool()?
【发布时间】:2020-04-13 00:32:42
【问题描述】:

CompletableFuture.runAsync 文档状态:

返回一个新的 CompletableFuture,它在运行给定操作后由 ForkJoinPool.commonPool() 中运行的任务异步完成。

但是,据我所知,runAsync 仅在ForkJoinPool.getCommonPoolParallelism() > 1 时向ForkJoinPool.commonPool() 提交任务。如果没有,它会为每个提交的任务手动创建一个新的Thread

为什么会这样?

【问题讨论】:

    标签: java multithreading asynchronous completable-future forkjoinpool


    【解决方案1】:

    是的,如果 ForkJoinPool 并行度小于 2,则为每个任务创建新线程here

    所有没有显式 Executor 参数的异步方法都使用 ForkJoinPool.commonPool() 执行(除非它不支持至少两个并行级别,在这种情况下,会创建一个新线程来运行每个任务)。

    【讨论】:

    • 我可以看到,但我想详细说明为什么在并行度不大于1(因此,默认情况下,当您有一个或两个逻辑核心时)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多