像往常一样使用 ForkJoinPool ExecutorService 是否有益
Is it beneficial to use ForkJoinPool as usual ExecutorService
假设我有这样的代码:
class Foo {
private final ExecutorService executor;
public Foo(ExecutorService executor) {
this.executor = executor;
}
public void doSomething() {
executor.execute(() -> {/* Do important task */});
}
}
如果我不在构造函数中传递 ThreadPoolExecutor
而使用 ForkJoinPool
,我可以获得更好的性能吗?如果是,那么为什么我应该更喜欢在任何情况下使用它而不是 ThreadPoolExecutor
.
更新 1
我的问题是关于 ForkJoinPool
到 ExecutorService
API 的用法,并且不假设使用 ForkJoinPool
特定 API 的递归任务拆分。
是的,如果你有递归 non-blocking 任务,你可以。
Here 是 Cay S. Horstmann 在最近的小丑会议上的精彩解释。
会有效
public static ExecutorService newWorkStealingPool()
Creates a work-stealing thread pool using all available processors as its target parallelism level.
您可以从本文档中找到优势 page:
A ForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.
A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist).
This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.
假设我有这样的代码:
class Foo {
private final ExecutorService executor;
public Foo(ExecutorService executor) {
this.executor = executor;
}
public void doSomething() {
executor.execute(() -> {/* Do important task */});
}
}
如果我不在构造函数中传递 ThreadPoolExecutor
而使用 ForkJoinPool
,我可以获得更好的性能吗?如果是,那么为什么我应该更喜欢在任何情况下使用它而不是 ThreadPoolExecutor
.
更新 1
我的问题是关于 ForkJoinPool
到 ExecutorService
API 的用法,并且不假设使用 ForkJoinPool
特定 API 的递归任务拆分。
是的,如果你有递归 non-blocking 任务,你可以。
Here 是 Cay S. Horstmann 在最近的小丑会议上的精彩解释。
public static ExecutorService newWorkStealingPool()
Creates a work-stealing thread pool using all available processors as its target parallelism level.
您可以从本文档中找到优势 page:
A ForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.
A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist).
This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.