public class ForkJoinPool
extends java.util.concurrent.AbstractExecutorService
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.
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 ForkJoinPool.ManagedBlocker
interface enables extension of the kinds of
synchronization accommodated.
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 common pool is by default constructed with default
parameters, but these may be controlled by setting three system properties
with prefix java.util.concurrent.ForkJoinPool.common
: parallelism
--
an integer greater than zero, threadFactory
-- the class
name of a ForkJoinPool.ForkJoinWorkerThreadFactory
, and exceptionHandler
-- the class name of a Thread.UncaughtExceptionHandler
. Upon any error in establishing
these settings, default parameters are used.
Implementation notes: This implementation restricts the
maximum number of running threads to 32767. Attempts to create
pools with greater than the maximum number result in
IllegalArgumentException
.
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 |
---|---|
(package private) static class |
ForkJoinPool.DefaultForkJoinWorkerThreadFactory
Default ForkJoinWorkerThreadFactory implementation; creates a
new ForkJoinWorkerThread.
|
(package private) static class |
ForkJoinPool.EmptyTask
Class for artificial tasks that are used to replace the target
of local joins if they are removed from an interior queue slot
in WorkQueue.tryRemoveAndExec.
|
static interface |
ForkJoinPool.ForkJoinWorkerThreadFactory
Factory for creating new
ForkJoinWorkerThread s. |
static interface |
ForkJoinPool.ManagedBlocker
Interface for extending managed parallelism for tasks running
in
ForkJoinPool s. |
(package private) static class |
ForkJoinPool.Submitter
Per-thread records for threads that submit to pools.
|
(package private) static class |
ForkJoinPool.WorkQueue
Queues supporting work-stealing as well as external task
submission.
|
Modifier and Type | Field and Description |
---|---|
private static int |
ABASE |
private static long |
AC_MASK |
private static int |
AC_SHIFT |
private static long |
AC_UNIT |
private static int |
ASHIFT |
(package private) static ForkJoinPool |
common
Common (static) pool.
|
(package private) static int |
commonParallelism
Common pool parallelism.
|
(package private) int |
config |
(package private) long |
ctl |
private static long |
CTL |
static ForkJoinPool.ForkJoinWorkerThreadFactory |
defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread.
|
private static int |
E_MASK |
private static int |
E_SEQ |
private static int |
EC_SHIFT |
private static int |
EVENMASK |
(package private) ForkJoinPool.ForkJoinWorkerThreadFactory |
factory |
private static long |
FAST_IDLE_TIMEOUT
Timeout value when there are more threads than parallelism level
|
(package private) static int |
FIFO_QUEUE |
private static long |
IDLE_TIMEOUT
Initial timeout value (in nanoseconds) for the thread
triggering quiescence to park waiting for new work.
|
(package private) int |
indexSeed |
private static long |
INDEXSEED |
private static int |
INT_SIGN |
(package private) static int |
LIFO_QUEUE |
private static int |
MAX_CAP |
private static int |
MAX_HELP
The maximum stolen->joining link depth allowed in method
tryHelpStealer.
|
private static int |
MAX_SCAN |
private static int |
MIN_SCAN |
private static java.lang.RuntimePermission |
modifyThreadPermission
Permission required for callers of methods that may start or
kill threads.
|
(package private) long |
pad00 |
(package private) long |
pad01 |
(package private) long |
pad02 |
(package private) long |
pad03 |
(package private) long |
pad04 |
(package private) long |
pad05 |
(package private) long |
pad06 |
(package private) java.lang.Object |
pad10 |
(package private) java.lang.Object |
pad11 |
(package private) java.lang.Object |
pad12 |
(package private) java.lang.Object |
pad13 |
(package private) java.lang.Object |
pad14 |
(package private) java.lang.Object |
pad15 |
(package private) java.lang.Object |
pad16 |
(package private) java.lang.Object |
pad17 |
(package private) java.lang.Object |
pad18 |
(package private) java.lang.Object |
pad19 |
(package private) java.lang.Object |
pad1a |
(package private) java.lang.Object |
pad1b |
private static long |
PARKBLOCKER |
private static int |
PL_LOCK |
private static int |
PL_SIGNAL |
private static int |
PL_SPINS |
(package private) int |
plock |
private static long |
PLOCK |
private static int |
poolNumberSequence
Sequence number for creating workerNamePrefix.
|
private static long |
QLOCK |
private static int |
SEED_INCREMENT
Increment for seed generators.
|
(package private) static int |
SHARED_QUEUE |
private static int |
SHORT_SIGN |
private static int |
SHUTDOWN |
private static int |
SMASK |
private static int |
SQMASK |
private static int |
ST_SHIFT |
(package private) long |
stealCount |
private static long |
STEALCOUNT |
private static long |
STOP_BIT |
(package private) static java.lang.ThreadLocal<ForkJoinPool.Submitter> |
submitters
Per-thread submission bookkeeping.
|
private static long |
TC_MASK |
private static int |
TC_SHIFT |
private static long |
TC_UNIT |
private static long |
TIMEOUT_SLOP
Tolerance for idle timeouts, to cope with timer undershoots
|
private static sun.misc.Unsafe |
U |
private static int |
UAC_MASK |
private static int |
UAC_SHIFT |
private static int |
UAC_UNIT |
(package private) java.lang.Thread.UncaughtExceptionHandler |
ueh |
private static int |
UTC_MASK |
private static int |
UTC_SHIFT |
private static int |
UTC_UNIT |
(package private) java.lang.String |
workerNamePrefix |
(package private) ForkJoinPool.WorkQueue[] |
workQueues |
Constructor and Description |
---|
ForkJoinPool()
Creates a
ForkJoinPool with parallelism equal to Runtime.availableProcessors() , using the default thread factory,
no UncaughtExceptionHandler, and non-async LIFO processing mode. |
ForkJoinPool(int parallelism)
Creates a
ForkJoinPool with the indicated parallelism
level, the default thread factory,
no UncaughtExceptionHandler, and non-async LIFO processing mode. |
ForkJoinPool(int parallelism,
ForkJoinPool.ForkJoinWorkerThreadFactory factory,
java.lang.Thread.UncaughtExceptionHandler handler,
boolean asyncMode)
Creates a
ForkJoinPool with the given parameters. |
ForkJoinPool(int parallelism,
long ctl,
ForkJoinPool.ForkJoinWorkerThreadFactory factory,
java.lang.Thread.UncaughtExceptionHandler handler)
Constructor for common pool, suitable only for static initialization.
|
Modifier and Type | Method and Description |
---|---|
private int |
acquirePlock()
Acquires the plock lock to protect worker array and related
updates.
|
(package private) int |
awaitJoin(ForkJoinPool.WorkQueue joiner,
ForkJoinTask<?> task)
Helps and/or blocks until the given task is done.
|
boolean |
awaitQuiescence(long timeout,
java.util.concurrent.TimeUnit unit)
If called by a ForkJoinTask operating in this pool, equivalent
in effect to
ForkJoinTask.helpQuiesce() . |
boolean |
awaitTermination(long timeout,
java.util.concurrent.TimeUnit unit)
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 static void |
checkPermission()
If there is a security manager, makes sure caller has
permission to modify threads.
|
static ForkJoinPool |
commonPool()
Returns the common pool instance.
|
(package private) static ForkJoinPool.WorkQueue |
commonSubmitterQueue()
Returns common pool queue for a thread that has submitted at
least one task.
|
(package private) void |
deregisterWorker(ForkJoinWorkerThread wt,
java.lang.Throwable ex)
Final callback from terminating worker, as well as upon failure
to construct or start a worker.
|
protected int |
drainTasksTo(java.util.Collection<? super ForkJoinTask<?>> c)
Removes all available unexecuted submitted and forked tasks
from scheduling queues and adds them to the given collection,
without altering their execution status.
|
void |
execute(ForkJoinTask<?> task)
Arranges for (asynchronous) execution of the given task.
|
void |
execute(java.lang.Runnable task) |
private void |
externalHelpComplete(ForkJoinPool.WorkQueue q,
ForkJoinTask<?> root)
Tries to pop and run local tasks within the same computation
as the given root.
|
(package private) static void |
externalHelpJoin(ForkJoinTask<?> t)
Tries to help execute or signal availability of the given task
from submitter's queue in common pool.
|
(package private) void |
externalPush(ForkJoinTask<?> task)
Unless shutting down, adds the given task to a submission queue
at submitter's current queue index (modulo submission
range).
|
private ForkJoinPool.WorkQueue |
findNonEmptyStealQueue(int r)
Returns a (probably) non-empty steal queue, if one is found
during a scan, else null.
|
private void |
fullExternalPush(ForkJoinTask<?> task)
Full version of externalPush.
|
int |
getActiveThreadCount()
Returns an estimate of the number of threads that are currently
stealing or executing tasks.
|
boolean |
getAsyncMode()
Returns
true if this pool uses local first-in-first-out
scheduling mode for forked tasks that are never joined. |
static int |
getCommonPoolParallelism()
Returns the targeted parallelism level of the common pool.
|
ForkJoinPool.ForkJoinWorkerThreadFactory |
getFactory()
Returns the factory used for constructing new workers.
|
int |
getParallelism()
Returns the targeted parallelism level of this pool.
|
int |
getPoolSize()
Returns the number of worker threads that have started but not
yet terminated.
|
int |
getQueuedSubmissionCount()
Returns an estimate of the number of tasks submitted to this
pool that have not yet begun executing.
|
long |
getQueuedTaskCount()
Returns 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).
|
int |
getRunningThreadCount()
Returns an estimate of the number of worker threads that are
not blocked waiting to join tasks or for other managed
synchronization.
|
long |
getStealCount()
Returns an estimate of the total number of tasks stolen from
one thread's work queue by another.
|
(package private) 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.
|
java.lang.Thread.UncaughtExceptionHandler |
getUncaughtExceptionHandler()
Returns the handler for internal worker threads that terminate
due to unrecoverable errors encountered while executing tasks.
|
private static sun.misc.Unsafe |
getUnsafe()
Returns a sun.misc.Unsafe.
|
boolean |
hasQueuedSubmissions()
Returns
true if there are any tasks submitted to this
pool that have not yet begun executing. |
private int |
helpComplete(ForkJoinTask<?> task,
int mode)
Analog of tryHelpStealer for CountedCompleters.
|
(package private) void |
helpJoinOnce(ForkJoinPool.WorkQueue joiner,
ForkJoinTask<?> task)
Stripped-down variant of awaitJoin used by timed joins.
|
(package private) void |
helpQuiescePool(ForkJoinPool.WorkQueue w)
Runs tasks until
isQuiescent() . |
private void |
helpSignal(ForkJoinTask<?> task,
int origin)
Scans through queues looking for work while joining a task; if
any present, signals.
|
private void |
idleAwaitWork(ForkJoinPool.WorkQueue w,
long currentCtl,
long prevCtl)
If inactivating worker w has caused the pool to become
quiescent, checks for pool termination, and, so long as this is
not the only worker, waits for event for up to a given
duration.
|
(package private) void |
incrementActiveCount()
Increments active count; mainly called upon return from blocking.
|
<T> T |
invoke(ForkJoinTask<T> task)
Performs the given task, returning its result upon completion.
|
<T> java.util.List<java.util.concurrent.Future<T>> |
invokeAll(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks) |
boolean |
isQuiescent()
Returns
true if all worker threads are currently idle. |
boolean |
isShutdown()
Returns
true if this pool has been shut down. |
boolean |
isTerminated()
Returns
true if all tasks have completed following shut down. |
boolean |
isTerminating()
Returns
true if the process of termination has
commenced but not yet completed. |
static void |
managedBlock(ForkJoinPool.ManagedBlocker blocker)
Blocks in accord with the given blocker.
|
protected <T> java.util.concurrent.RunnableFuture<T> |
newTaskFor(java.util.concurrent.Callable<T> callable) |
protected <T> java.util.concurrent.RunnableFuture<T> |
newTaskFor(java.lang.Runnable runnable,
T value) |
private static int |
nextPoolId()
Returns the next sequence number.
|
(package private) ForkJoinTask<?> |
nextTaskFor(ForkJoinPool.WorkQueue w)
Gets and removes a local or stolen task for the given worker.
|
protected ForkJoinTask<?> |
pollSubmission()
Removes and returns the next unexecuted submission if one is
available.
|
(package private) static void |
quiesceCommonPool()
Waits and/or attempts to assist performing tasks indefinitely
until the
commonPool() isQuiescent() . |
(package private) ForkJoinPool.WorkQueue |
registerWorker(ForkJoinWorkerThread wt)
Callback from ForkJoinWorkerThread to establish and record its
WorkQueue.
|
private void |
releasePlock(int ps)
Unlocks and signals any thread waiting for plock.
|
(package private) void |
runWorker(ForkJoinPool.WorkQueue w)
Top-level runloop for workers, called by ForkJoinWorkerThread.run.
|
private ForkJoinTask<?> |
scan(ForkJoinPool.WorkQueue w)
Scans for and, if found, returns one task, else possibly
inactivates the worker.
|
void |
shutdown()
Possibly initiates an orderly shutdown in which previously
submitted tasks are executed, but no new tasks will be
accepted.
|
java.util.List<java.lang.Runnable> |
shutdownNow()
Possibly attempts to cancel and/or stop all tasks, and reject
all subsequently submitted tasks.
|
(package private) void |
signalWork(ForkJoinPool.WorkQueue q)
Tries to create or activate a worker if too few are active.
|
<T> ForkJoinTask<T> |
submit(java.util.concurrent.Callable<T> task) |
<T> ForkJoinTask<T> |
submit(ForkJoinTask<T> task)
Submits a ForkJoinTask for execution.
|
ForkJoinTask<?> |
submit(java.lang.Runnable task) |
<T> ForkJoinTask<T> |
submit(java.lang.Runnable task,
T result) |
java.lang.String |
toString()
Returns a string identifying this pool, as well as its state,
including indications of run state, parallelism level, and
worker and task counts.
|
private void |
tryAddWorker()
Tries to create and start one worker if fewer than target
parallelism level exist.
|
(package private) boolean |
tryCompensate()
Tries to decrement active count (sometimes implicitly) and
possibly release or create a compensating worker in preparation
for blocking.
|
(package private) static boolean |
tryExternalUnpush(ForkJoinTask<?> t)
Tries to pop the given task from submitter's queue in common pool.
|
private int |
tryHelpStealer(ForkJoinPool.WorkQueue joiner,
ForkJoinTask<?> task)
Tries to locate and execute tasks for a stealer of the given
task, or in turn one of its stealers, Traces currentSteal ->
currentJoin links looking for a thread working on a descendant
of the given task and with a non-empty queue to steal back and
execute tasks from.
|
private boolean |
tryTerminate(boolean now,
boolean enable)
Possibly initiates and/or completes termination.
|
public static final ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory
static final java.lang.ThreadLocal<ForkJoinPool.Submitter> submitters
private static final java.lang.RuntimePermission modifyThreadPermission
static final ForkJoinPool common
static final int commonParallelism
private static int poolNumberSequence
private static final long IDLE_TIMEOUT
private static final long FAST_IDLE_TIMEOUT
private static final long TIMEOUT_SLOP
private static final int MAX_HELP
private static final int SEED_INCREMENT
private static final int AC_SHIFT
private static final int TC_SHIFT
private static final int ST_SHIFT
private static final int EC_SHIFT
private static final int SMASK
private static final int MAX_CAP
private static final int EVENMASK
private static final int SQMASK
private static final int SHORT_SIGN
private static final int INT_SIGN
private static final long STOP_BIT
private static final long AC_MASK
private static final long TC_MASK
private static final long TC_UNIT
private static final long AC_UNIT
private static final int UAC_SHIFT
private static final int UTC_SHIFT
private static final int UAC_MASK
private static final int UTC_MASK
private static final int UAC_UNIT
private static final int UTC_UNIT
private static final int E_MASK
private static final int E_SEQ
private static final int SHUTDOWN
private static final int PL_LOCK
private static final int PL_SIGNAL
private static final int PL_SPINS
static final int LIFO_QUEUE
static final int FIFO_QUEUE
static final int SHARED_QUEUE
private static final int MIN_SCAN
private static final int MAX_SCAN
volatile long pad00
volatile long pad01
volatile long pad02
volatile long pad03
volatile long pad04
volatile long pad05
volatile long pad06
volatile long stealCount
volatile long ctl
volatile int plock
volatile int indexSeed
final int config
ForkJoinPool.WorkQueue[] workQueues
final ForkJoinPool.ForkJoinWorkerThreadFactory factory
final java.lang.Thread.UncaughtExceptionHandler ueh
final java.lang.String workerNamePrefix
volatile java.lang.Object pad10
volatile java.lang.Object pad11
volatile java.lang.Object pad12
volatile java.lang.Object pad13
volatile java.lang.Object pad14
volatile java.lang.Object pad15
volatile java.lang.Object pad16
volatile java.lang.Object pad17
volatile java.lang.Object pad18
volatile java.lang.Object pad19
volatile java.lang.Object pad1a
volatile java.lang.Object pad1b
private static final sun.misc.Unsafe U
private static final long CTL
private static final long PARKBLOCKER
private static final int ABASE
private static final int ASHIFT
private static final long STEALCOUNT
private static final long PLOCK
private static final long INDEXSEED
private static final long QLOCK
public ForkJoinPool()
ForkJoinPool
with parallelism equal to Runtime.availableProcessors()
, using the default thread factory,
no UncaughtExceptionHandler, and non-async LIFO processing mode.java.lang.SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public ForkJoinPool(int parallelism)
ForkJoinPool
with the indicated parallelism
level, the default thread factory,
no UncaughtExceptionHandler, and non-async LIFO processing mode.parallelism
- the parallelism leveljava.lang.IllegalArgumentException
- if parallelism less than or
equal to zero, or greater than implementation limitjava.lang.SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public ForkJoinPool(int parallelism, ForkJoinPool.ForkJoinWorkerThreadFactory factory, java.lang.Thread.UncaughtExceptionHandler handler, boolean asyncMode)
ForkJoinPool
with the given parameters.parallelism
- the parallelism level. For default value,
use Runtime.availableProcessors()
.factory
- the factory for creating new threads. For default value,
use defaultForkJoinWorkerThreadFactory
.handler
- the handler for internal worker threads that
terminate due to unrecoverable errors encountered while executing
tasks. For default value, use null
.asyncMode
- 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 false
.java.lang.IllegalArgumentException
- if parallelism less than or
equal to zero, or greater than implementation limitjava.lang.NullPointerException
- if the factory is nulljava.lang.SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
ForkJoinPool(int parallelism, long ctl, ForkJoinPool.ForkJoinWorkerThreadFactory factory, java.lang.Thread.UncaughtExceptionHandler handler)
private static void checkPermission()
private static final int nextPoolId()
private int acquirePlock()
private void releasePlock(int ps)
private void tryAddWorker()
final ForkJoinPool.WorkQueue registerWorker(ForkJoinWorkerThread wt)
wt
- the worker threadfinal void deregisterWorker(ForkJoinWorkerThread wt, java.lang.Throwable ex)
wt
- the worker thread or null if construction failedex
- the exception causing failure, or null if nonefinal void externalPush(ForkJoinTask<?> task)
task
- the task. Caller must ensure non-null.private void fullExternalPush(ForkJoinTask<?> task)
final void incrementActiveCount()
final void signalWork(ForkJoinPool.WorkQueue q)
q
- the (non-null) queue holding tasks to be signalledfinal void runWorker(ForkJoinPool.WorkQueue w)
private final ForkJoinTask<?> scan(ForkJoinPool.WorkQueue w)
w
- the worker (via its WorkQueue)private void idleAwaitWork(ForkJoinPool.WorkQueue w, long currentCtl, long prevCtl)
w
- the calling workercurrentCtl
- the ctl value triggering possible quiescenceprevCtl
- the ctl value to restore if thread is terminatedprivate void helpSignal(ForkJoinTask<?> task, int origin)
task
- return early if doneorigin
- an index to start scanprivate int tryHelpStealer(ForkJoinPool.WorkQueue joiner, ForkJoinTask<?> task)
joiner
- the joining workertask
- the task to joinprivate int helpComplete(ForkJoinTask<?> task, int mode)
task
- the task to joinmode
- if shared, exit upon completing any task
if all workers are activefinal boolean tryCompensate()
final int awaitJoin(ForkJoinPool.WorkQueue joiner, ForkJoinTask<?> task)
joiner
- the joining workertask
- the taskfinal void helpJoinOnce(ForkJoinPool.WorkQueue joiner, ForkJoinTask<?> task)
joiner
- the joining workertask
- the taskprivate ForkJoinPool.WorkQueue findNonEmptyStealQueue(int r)
r
- a (random) seed for scanningfinal void helpQuiescePool(ForkJoinPool.WorkQueue w)
isQuiescent()
. We piggyback on
active count ctl maintenance, but rather than blocking
when tasks cannot be found, we rescan until all others cannot
find tasks either.final ForkJoinTask<?> nextTaskFor(ForkJoinPool.WorkQueue w)
static int getSurplusQueuedTaskCount()
private boolean tryTerminate(boolean now, boolean enable)
now
- if true, unconditionally terminate, else only
if no work and no active workersenable
- if true, enable shutdown when next possiblestatic ForkJoinPool.WorkQueue commonSubmitterQueue()
static boolean tryExternalUnpush(ForkJoinTask<?> t)
private void externalHelpComplete(ForkJoinPool.WorkQueue q, ForkJoinTask<?> root)
static void externalHelpJoin(ForkJoinTask<?> t)
public static ForkJoinPool commonPool()
shutdown()
or shutdownNow()
. 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(long, java.util.concurrent.TimeUnit)
, before
exit.public <T> T invoke(ForkJoinTask<T> task)
ex.printStackTrace()
) of both the current thread
as well as the thread actually encountering the exception;
minimally only the latter.task
- the taskjava.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic void execute(ForkJoinTask<?> task)
task
- the taskjava.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic void execute(java.lang.Runnable task)
java.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)
task
- the task to submitjava.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(java.util.concurrent.Callable<T> task)
submit
in interface java.util.concurrent.ExecutorService
submit
in class java.util.concurrent.AbstractExecutorService
java.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(java.lang.Runnable task, T result)
submit
in interface java.util.concurrent.ExecutorService
submit
in class java.util.concurrent.AbstractExecutorService
java.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic ForkJoinTask<?> submit(java.lang.Runnable task)
submit
in interface java.util.concurrent.ExecutorService
submit
in class java.util.concurrent.AbstractExecutorService
java.lang.NullPointerException
- if the task is nulljava.util.concurrent.RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> java.util.List<java.util.concurrent.Future<T>> invokeAll(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks)
invokeAll
in interface java.util.concurrent.ExecutorService
invokeAll
in class java.util.concurrent.AbstractExecutorService
java.lang.NullPointerException
java.util.concurrent.RejectedExecutionException
public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
null
if nonepublic int getParallelism()
public static int getCommonPoolParallelism()
public int getPoolSize()
getParallelism()
when threads are created to
maintain parallelism when others are cooperatively blocked.public boolean getAsyncMode()
true
if this pool uses local first-in-first-out
scheduling mode for forked tasks that are never joined.true
if this pool uses async modepublic int getRunningThreadCount()
public int getActiveThreadCount()
public boolean isQuiescent()
true
if all worker threads are currently idle.
An idle worker is one that cannot obtain a task to execute
because none are available to steal from other threads, and
there are no pending submissions to the pool. This method is
conservative; it might not return true
immediately upon
idleness of all threads, but will eventually become true if
threads remain inactive.true
if all threads are currently idlepublic long getStealCount()
public long getQueuedTaskCount()
public int getQueuedSubmissionCount()
public boolean hasQueuedSubmissions()
true
if there are any tasks submitted to this
pool that have not yet begun executing.true
if there are any queued submissionsprotected ForkJoinTask<?> pollSubmission()
null
if noneprotected int drainTasksTo(java.util.Collection<? super ForkJoinTask<?>> c)
c
may result in elements being in
neither, either or both collections when the associated
exception is thrown. The behavior of this operation is
undefined if the specified collection is modified while the
operation is in progress.c
- the collection to transfer elements intopublic java.lang.String toString()
toString
in class java.lang.Object
public void shutdown()
commonPool()
, and no additional effect if
already shut down. Tasks that are in the process of being
submitted concurrently during the course of this method may or
may not be rejected.java.lang.SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public java.util.List<java.lang.Runnable> shutdownNow()
commonPool()
, and no
additional effect if already shut down. Otherwise, tasks that
are in the process of being submitted or executed concurrently
during the course of this method may or may not be
rejected. This method cancels both existing and unexecuted
tasks, in order to permit termination in the presence of task
dependencies. So the method always returns an empty list
(unlike the case for some other Executors).java.lang.SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public boolean isTerminated()
true
if all tasks have completed following shut down.true
if all tasks have completed following shut downpublic boolean isTerminating()
true
if the process of termination has
commenced but not yet completed. This method may be useful for
debugging. A return of true
reported a sufficient
period after shutdown may indicate that submitted tasks have
ignored or suppressed interruption, or are waiting for I/O,
causing this executor not to properly terminate. (See the
advisory notes for class ForkJoinTask
stating that
tasks should not normally entail blocking operations. But if
they do, they must abort them on interrupt.)true
if terminating but not yet terminatedpublic boolean isShutdown()
true
if this pool has been shut down.true
if this pool has been shut downpublic boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) throws java.lang.InterruptedException
commonPool()
never terminates until program shutdown, when
applied to the common pool, this method is equivalent to awaitQuiescence(long, java.util.concurrent.TimeUnit)
but always returns false
.timeout
- the maximum time to waitunit
- the time unit of the timeout argumenttrue
if this executor terminated and
false
if the timeout elapsed before terminationjava.lang.InterruptedException
- if interrupted while waitingpublic boolean awaitQuiescence(long timeout, java.util.concurrent.TimeUnit unit)
ForkJoinTask.helpQuiesce()
. Otherwise,
waits and/or attempts to assist performing tasks until this
pool isQuiescent()
or the indicated timeout elapses.timeout
- the maximum time to waitunit
- the time unit of the timeout argumenttrue
if quiescent; false
if the
timeout elapsed.static void quiesceCommonPool()
commonPool()
isQuiescent()
.public static void managedBlock(ForkJoinPool.ManagedBlocker blocker) throws java.lang.InterruptedException
ForkJoinWorkerThread
, this method possibly
arranges for a spare thread to be activated if necessary to
ensure sufficient parallelism while the current thread is blocked.
If the caller is not a ForkJoinTask
, this method is
behaviorally equivalent to
while (!blocker.isReleasable())
if (blocker.block())
return;
If the caller is a ForkJoinTask
, then the pool may
first be expanded to ensure parallelism, and later adjusted.blocker
- the blockerjava.lang.InterruptedException
- if blocker.block did soprotected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.lang.Runnable runnable, T value)
newTaskFor
in class java.util.concurrent.AbstractExecutorService
protected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.util.concurrent.Callable<T> callable)
newTaskFor
in class java.util.concurrent.AbstractExecutorService
private static sun.misc.Unsafe getUnsafe()