ExecutorService
for running ForkJoinTask
s.
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 ForkJoinTask
s), as well as when many small
tasks are submitted to the pool from external clients. Especially
when setting asyncMode to true in constructors, ForkJoinPool
s may also be appropriate for use with event-style
tasks that are never joined. All worker threads are initialized
with Thread#isDaemon
set true
.
A static commonPool()
is available and appropriate for
most applications. The common pool is used by any ForkJoinTask that
is not explicitly submitted to a specified pool. Using the common
pool normally reduces resource usage (its threads are slowly
reclaimed during periods of non-use, and reinstated upon subsequent
use).
For applications that require separate or custom pools, a ForkJoinPool
may be constructed with a given target parallelism
level; by default, equal to the number of available processors.
The pool attempts to maintain enough active (or available) threads
by dynamically adding, suspending, or resuming internal worker
threads, even if some tasks are stalled waiting to join others.
However, no such adjustments are guaranteed in the face of blocked
I/O or other unmanaged synchronization. The nested ManagedBlocker
interface enables extension of the kinds of
synchronization accommodated. The default policies may be
overridden using a constructor with parameters corresponding to
those documented in class ThreadPoolExecutor
.
In addition to execution and lifecycle control methods, this
class provides status check methods (for example
getStealCount
) that are intended to aid in developing,
tuning, and monitoring fork/join applications. Also, method
toString
returns indications of pool state in a
convenient form for informal monitoring.
As is the case with other ExecutorServices, there are three
main task execution methods summarized in the following table.
These are designed to be used primarily by clients not already
engaged in fork/join computations in the current pool. The main
forms of these methods accept instances of ForkJoinTask
,
but overloaded forms also allow mixed execution of plain Runnable
- or Callable
- based activities as well. However,
tasks that are already executing in a pool should normally instead
use the within-computation forms listed in the table unless using
async event-style tasks that are not usually joined, in which case
there is little difference among choice of methods.
Call from non-fork/join clients | Call from within fork/join computations | |
---|---|---|
Arrange async execution | execute(ForkJoinTask) |
ForkJoinTask#fork |
Await and obtain result | invoke(ForkJoinTask) |
ForkJoinTask#invoke |
Arrange exec and obtain Future | submit(ForkJoinTask) |
ForkJoinTask#fork (ForkJoinTasks are Futures) |
The parameters used to construct the common pool may be controlled by setting the following system properties:
java.util.concurrent.ForkJoinPool.common.parallelism
- the parallelism level, a non-negative integer
java.util.concurrent.ForkJoinPool.common.threadFactory
- the class name of a ForkJoinWorkerThreadFactory
.
The system class loader
is used to load this class.
java.util.concurrent.ForkJoinPool.common.exceptionHandler
- the class name of a UncaughtExceptionHandler
.
The system class loader
is used to load this class.
java.util.concurrent.ForkJoinPool.common.maximumSpares
- the maximum number of allowed extra threads to maintain target
parallelism (default 256).
SecurityManager
is present, then
the common pool uses a factory supplying threads that have no
Permissions
enabled, and are not guaranteed to preserve
the values of java.lang.ThreadLocal
variables across tasks.
Upon any error in establishing these settings, default parameters
are used. It is possible to disable or limit the use of threads in
the common pool by setting the parallelism property to zero, and/or
using a factory that may return null
. However doing so may
cause unjoined tasks to never be executed.
Implementation Note
This implementation restricts the maximum number of
running threads to 32767. Attempts to create pools with greater
than the maximum number result in IllegalArgumentException
. Also, this implementation rejects
submitted tasks (that is, by throwing RejectedExecutionException
) only when the pool is shut down or
internal resources have been exhausted.
Modifier and Type | Class and Description |
---|---|
pack-priv static class | ForkJoinPool.
Default ForkJoinWorkerThreadFactory implementation; creates a new ForkJoinWorkerThread using the system class loader as the thread context class loader. |
public static interface | ForkJoinPool.
Factory for creating new |
public static interface | ForkJoinPool.
Interface for extending managed parallelism for tasks running
in |
pack-priv static class | ForkJoinPool.
Queues supporting work-stealing as well as external task submission. |
Modifier and Type | Field and Description |
---|---|
pack-priv static final long | |
pack-priv static final int | |
pack-priv static final int | |
pack-priv static final ForkJoinPool | common
Common (static) pool. |
pack-priv final long | |
pack-priv final SharedThreadContainer | |
pack-priv volatile long | |
private static final long | |
pack-priv static final int | DEFAULT_COMMON_MAX_SPARES
The default value for common pool maxSpares. |
pack-priv static final long | DEFAULT_KEEPALIVE
Default idle timeout value (in milliseconds) for idle threads to park waiting for new work before terminating. |
public static final ForkJoinPool. | defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread. |
pack-priv static final int | |
pack-priv static final int | |
pack-priv final ForkJoinPool. | |
pack-priv static final int | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv static final int | INITIAL_QUEUE_CAPACITY
Initial capacity of work-stealing queue array. |
pack-priv static final int | |
pack-priv final long | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv static final int | |
pack-priv static final int | |
pack-priv static volatile RuntimePermission | modifyThreadPermission
Permission required for callers of methods that may start or kill threads. |
pack-priv static final long | |
pack-priv int | |
private static final long | |
private static volatile int | poolIds
Sequence number for creating worker names |
private static final long | |
private static final Object | |
pack-priv static final int | |
pack-priv ForkJoinPool. | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv static final long | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv volatile int | |
private static final long | |
pack-priv final Predicate | |
pack-priv static final int | |
pack-priv static final int | |
pack-priv static final int | |
pack-priv volatile long | |
pack-priv static final int | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv volatile CountDownLatch | |
private static final long | |
pack-priv volatile long | |
private static final long | |
pack-priv static final long | TIMEOUT_SLOP
Undershoot tolerance for idle timeouts |
private static final Unsafe | |
pack-priv final Thread. | |
pack-priv static final long | |
pack-priv static final int | |
pack-priv final String |
Access | Constructor and Description |
---|---|
public | ForkJoinPool()
Creates a |
public | ForkJoinPool(int
the parallelism level parallelism)Creates a |
public | ForkJoinPool(int
the parallelism level. For default value,
use parallelism, ForkJoinPool.java. .the factory for creating new threads. For default value,
use factory,defaultForkJoinWorkerThreadFactory .the handler for internal worker threads that
terminate due to unrecoverable errors encountered while executing
tasks. For default value, use handler,null .if true,
establishes local first-in-first-out scheduling mode for forked
tasks that are never joined. This mode may be more appropriate
than default locally stack-based mode in applications in which
worker threads only process event-style asynchronous tasks.
For default value, use asyncMode)false .Creates a |
public | ForkJoinPool(int
the parallelism level. For default value,
use parallelism, ForkJoinPool.java. .the factory for creating new threads. For
default value, use factory,defaultForkJoinWorkerThreadFactory .the handler for internal worker threads that
terminate due to unrecoverable errors encountered while
executing tasks. For default value, use handler,null .if true, establishes local first-in-first-out
scheduling mode for forked tasks that are never joined. This
mode may be more appropriate than default locally stack-based
mode in applications in which worker threads only process
event-style asynchronous tasks. For default value, use asyncMode, int false .the number of threads to keep in the pool
(unless timed out after an elapsed keep-alive). Normally (and
by default) this is the same value as the parallelism level,
but may be set to a larger value to reduce dynamic overhead if
tasks regularly block. Using a smaller value (for example
corePoolSize, int 0 ) has the same effect as the default.the maximum number of threads allowed.
When the maximum is reached, attempts to replace blocked
threads fail. (However, because creation and termination of
different threads may overlap, and may be managed by the given
thread factory, this value may be transiently exceeded.) To
arrange the same value as is used by default for the common
pool, use maximumPoolSize, int 256 plus the parallelism level. (By
default, the common pool allows a maximum of 256 spare
threads.) Using a value (for example Integer.MAX_VALUE ) larger than the implementation's total
thread limit has the same effect as using this limit (which is
the default).the minimum allowed number of core
threads not blocked by a join or minimumRunnable, Predicate<? super ForkJoinPool> ManagedBlocker . To
ensure progress, when too few unblocked threads exist and
unexecuted tasks may exist, new threads are constructed, up to
the given maximumPoolSize. For the default value, use 1 , that ensures liveness. A larger value might improve
throughput in the presence of blocked activities, but might
not, due to increased overhead. A value of zero may be
acceptable when submitted tasks cannot have dependencies
requiring additional threads.if non-null, a predicate invoked upon attempts
to create more than the maximum total allowed threads. By
default, when a thread is about to block on a join or saturate, long ManagedBlocker , but cannot be replaced because the
maximumPoolSize would be exceeded, a RejectedExecutionException is thrown. But if this predicate
returns true , then no exception is thrown, so the pool
continues to operate with fewer than the target number of
runnable threads, which might not ensure progress.the elapsed time since last use before
a thread is terminated (and then later replaced if needed).
For the default value, use keepAliveTime, TimeUnit 60, TimeUnit.SECONDS .the time unit for the unit)keepAliveTime argumentCreates a |
private | ForkJoinPool(byte forCommonPoolOnly)
Constructor for common pool using parameters possibly overridden by system properties |
Modifier and Type | Method and Description |
---|---|
public boolean | Returns: true if quiescent; false if the
timeout elapsed.the maximum time to wait timeout, TimeUnit the time unit of the timeout argument unit)If called by a ForkJoinTask operating in this pool, equivalent
in effect to |
public boolean | Returns: true if this executor terminated and
false if the timeout elapsed before terminationthe maximum time to wait timeout, TimeUnit the time unit of the timeout argument unit)Implements java. Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. |
private int | Returns: current phase, with IDLE set if worker should exitthe worker (may be null if already terminated) w,current phase phase)Tries to inactivate, and if successful, awaits signal or termination. |
pack-priv final long | beginCompensatedBlock()
Invokes tryCompensate to create or re-activate a spare thread to compensate for a thread that performs a blocking operation. |
private boolean | |
private static void | checkPermission()
If there is a security manager, makes sure caller has permission to modify threads. |
public void | close()
Overrides default java. Unless this is the |
private CountDownLatch | |
public static ForkJoinPool | |
pack-priv static ForkJoinPool. | |
private long | |
private boolean | |
private void | |
private boolean | |
pack-priv final void | deregisterWorker(ForkJoinWorkerThread
the worker thread, or null if construction failed wt, Throwable the exception causing failure, or null if none ex)Final callback from terminating worker, as well as upon failure to construct or start a worker. |
protected int | Returns: the number of elements transferredthe collection to transfer elements into c)Removes all available unexecuted submitted and forked tasks from scheduling queues and adds them to the given collection, without altering their execution status. |
pack-priv void | |
public void | |
public void | execute(Runnable
the runnable task task)Implements java. Executes the given command at some time in the future. |
private int | Returns: positive if quiescent, negative if interrupted, else 0max wait time (Long.MAX_VALUE if effectively untimed) nanos, boolean true if return on interrupt interruptible)Helps quiesce from external caller until done, interrupted, or timeout |
pack-priv static ForkJoinPool. | externalQueue(ForkJoinPool p)
Returns queue for an external thread, if one exists that has possibly ever submitted to the given pool (nonzero probe), or null if none. |
pack-priv final ForkJoinPool. | externalSubmissionQueue()
Returns queue for an external submission, bypassing call to submissionQueue if already established and unlocked. |
public < the type of the task's result T> ForkJoinTask | Returns: the taskthe task to submit task)Submits the given task as if submitted from a non- |
public int | Returns: the number of active threadsReturns an estimate of the number of threads that are currently stealing or executing tasks. |
private long | |
private static int | |
private int | |
private int | |
public boolean | Returns: true if this pool uses async modeReturns |
public static int | Returns: the targeted parallelism level of the common poolReturns the targeted parallelism level of the common pool. |
public ForkJoinPool. | Returns: the factory used for constructing new workersReturns the factory used for constructing new workers. |
public int | Returns: the targeted parallelism level of this poolReturns the targeted parallelism level of this pool. |
private int | |
public int | Returns: the number of worker threadsReturns the number of worker threads that have started but not yet terminated. |
public int | Returns: the number of queued submissionsReturns an estimate of the number of tasks submitted to this pool that have not yet begun executing. |
public long | Returns: the number of queued tasksReturns an estimate of the total number of tasks currently held in queues by worker threads (but not including tasks submitted to the pool that have not begun executing). |
public int | Returns: the number of worker threadsReturns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization. |
public long | Returns: the number of stealsReturns an estimate of the total number of completed tasks that were executed by a thread other than their submitter. |
pack-priv static int | getSurplusQueuedTaskCount()
Returns a cheap heuristic guide for task partitioning when programmers, frameworks, tools, or languages have little or no idea about task granularity. |
public Thread. | Returns: the handler, ornull if noneReturns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. |
public boolean | Returns: true if there are any queued submissionsReturns |
pack-priv static void | helpAsyncBlocker(Executor e, ForkJoinPool.
If the given executor is a ForkJoinPool, poll and execute AsynchronousCompletionTasks from worker's queue until none are available or blocker is released. |
pack-priv final int | Returns: task status on exit, or UNCOMPENSATE for compensated blockingroot of computation (only called when a CountedCompleter) task, ForkJoinPool.caller's WorkQueue w,true if w is owned by a ForkJoinWorkerThread internal)Version of helpJoin for CountedCompleters. |
pack-priv final int | Returns: task status on exit, or UNCOMPENSATE for compensated blockingthe task task, ForkJoinPool.caller's WorkQueue w,true if w is owned by a ForkJoinWorkerThread internal)Helps if possible until the given task is done. |
private int | Returns: positive if quiescent, negative if interrupted, else 0max wait time (Long.MAX_VALUE if effectively untimed) nanos, boolean true if return on interrupt interruptible)Runs tasks until all workers are inactive and no tasks are found. |
pack-priv static final int | Returns: positive if quiescent, negative if interrupted, else 0the pool to use, or null if any pool, long max wait time (Long.MAX_VALUE if effectively untimed) nanos, boolean true if return on interrupt interruptible)Helps quiesce from either internal or external caller |
private long | |
private void | |
public < the type of the task's result T> T | Returns: the task's resultthe task task)Performs the given task, returning its result upon completion. |
private <T> List | invokeAll(Collection<? extends Callable<T>> tasks, long deadline)
Common support for timed and untimed invokeAll |
public <T> List | invokeAll(Collection<? extends Callable<T>>
the collection of tasks tasks)Overrides java. Implements java. Executes the given tasks, returning a list of Futures holding their status and results when all complete. |
public <T> List | invokeAll(Collection<? extends Callable<T>>
the collection of tasks tasks, long the maximum time to wait timeout, TimeUnit the time unit of the timeout argument unit)Overrides java. Implements java. Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first. |
public < the type of the values returned from the tasks T> List | Returns: a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completedthe collection of tasks tasks)Uninterrupible version of |
public <T> T | invokeAny(Collection<? extends Callable<T>>
the collection of tasks tasks)Overrides java. Implements java. Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. |
public <T> T | invokeAny(Collection<? extends Callable<T>>
the collection of tasks tasks, long the maximum time to wait timeout, TimeUnit the time unit of the timeout argument unit)Overrides java. Implements java. Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. |
public boolean | Returns: true if all threads are currently idleReturns |
public boolean | Returns: true if this pool has been shut downImplements java. Returns |
public boolean | Returns: true if all tasks have completed following shut downImplements java. Returns |
public boolean | Returns: true if terminating but not yet terminatedReturns |
public < the type of the task's result T> ForkJoinTask | Returns: the taskthe task task)Submits the given task without guaranteeing that it will eventually execute in the absence of available active threads. |
private int | |
public static void | managedBlock(ForkJoinPool.
the blocker task blockerRuns the given possibly blocking task. |
protected <T> RunnableFuture | newTaskFor(Runnable
the runnable task being wrapped runnable, T the default value for the returned future value)Overrides java. Returns a |
protected <T> RunnableFuture | newTaskFor(Callable<T>
the callable task being wrapped callable)Overrides java. Returns a |
pack-priv final ForkJoinTask | Returns: a task, if availableGets and removes a local or stolen task for the given worker. |
pack-priv final String | |
private ForkJoinTask | pollScan(boolean
if true, only scan submission queues submissionsOnly)Scans for and returns a polled task, if available. |
protected ForkJoinTask | Returns: the next submission, ornull if noneRemoves and returns the next unexecuted submission if one is available. |
pack-priv static boolean | |
private void | |
private boolean | Returns: true if terminating or all workers are inactive and submission queues are empty and unlocked; if so, setting STOP if shutdown is enabledInternal version of isQuiescent and related functionality. |
private void | reactivate(ForkJoinPool.
Reactivates the given worker, and possibly others if not top of ctl stack. |
pack-priv final void | registerWorker(ForkJoinPool.
caller's WorkQueue wFinishes initializing and records internal queue. |
pack-priv final void | runWorker(ForkJoinPool.
caller's WorkQueue (may be null on failed initialization) wTop-level runloop for workers, called by ForkJoinWorkerThread.run. |
private long | Returns: the next window to use, with RESCAN set for rescancaller's WorkQueue w,up to three queue indices window, int random seed r)Scans for and if found executes top-level tasks: Tries to poll each queue starting at initial index with random stride, returning next scan window and retry indicator. |
public int | Returns: the previous parallelism level.the target parallelism level size)Changes the target parallelism of this pool, controlling the future creation, use, and termination of worker threads. |
public void | shutdown()
Implements java. Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. |
public List | Returns: an empty listImplements java. Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. |
pack-priv final void | signalWork(ForkJoinTask<?>[]
if nonnull, a task array holding task signalled a, int index of task in array k)Releases an idle worker, or creates one if not enough exist, returning on contention if a signal task is already taken. |
pack-priv static long | slotOffset(int index)
Returns the array offset corresponding to the given index for Unsafe task queue operations |
private int | |
private ForkJoinPool. | submissionQueue(int
current ThreadLocalRandom.getProbe() value r)Finds and locks a WorkQueue for an external submitter, or throws RejectedExecutionException if shutdown or terminating. |
public < the type of the task's result T> ForkJoinTask | Returns: the taskthe task to submit task)Submits a ForkJoinTask for execution. |
public <T> ForkJoinTask | submit(Callable<T>
the task to submit task)Overrides java. Implements java. Submits a value-returning task for execution and returns a Future representing the pending results of the task. |
public <T> ForkJoinTask | submit(Runnable
the task to submit task, T the result to return result)Overrides java. Implements java. Submits a Runnable task for execution and returns a Future representing that task. |
public ForkJoinTask | submit(Runnable
the task to submit task)Overrides java. Implements java. Submits a Runnable task for execution and returns a Future representing that task. |
private CountDownLatch | |
public String | Returns: a string identifying this pool, as well as its stateOverrides java. Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts. |
private int | Returns: UNCOMPENSATE: block then adjust, 0: block, -1 : retryincoming ctl value c)Tries to decrement counts (sometimes implicitly) and possibly arrange for a compensating worker in preparation for blocking. |
private int | Returns: runState on exitif true, unconditionally terminate, else only
if no work and no active workers now, boolean if true, terminate when next possible enable)Possibly initiates and/or completes pool termination. |
pack-priv final void | |
private void | |
private static void |