APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class ForkJoinPool

extends AbstractExecutorService
implements ScheduledExecutorService
Class Inheritance
All Implemented Interfaces
java.util.concurrent.ScheduledExecutorService, java.util.concurrent.ExecutorService, java.lang.AutoCloseable, java.util.concurrent.Executor
Imports
java.lang.Thread.UncaughtExceptionHandler, java.lang.reflect.Field, java.util.ArrayList, .Collection, .Collections, .List, .Objects, java.util.function.Consumer, .Predicate, java.util.concurrent.CountDownLatch, java.util.concurrent.locks.LockSupport, jdk.internal.access.JavaLangAccess, .JavaUtilConcurrentFJPAccess, .SharedSecrets, jdk.internal.misc.Unsafe, jdk.internal.vm.SharedThreadContainer

An ExecutorService for running ForkJoinTasks. 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. 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.

Summary of task execution 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)

Additionally, this class supports ScheduledExecutorService methods to delay or periodically execute tasks, as well as method submitWithTimeout to cancel tasks that take too long. The scheduled functions or actions may create and invoke other ForkJoinTasks. Delayed actions become enabled for execution and behave as ordinary submitted tasks when their delays elapse. Scheduling methods return ForkJoinTasks that implement the ScheduledFuture interface. Resource exhaustion encountered after initial submission results in task cancellation. When time-based methods are used, shutdown policies match the default policies of class ScheduledThreadPoolExecutor: upon shutdown, existing periodic tasks will not re-execute, and the pool terminates when quiescent and existing delayed tasks complete. Method cancelDelayedTasksOnShutdown may be used to disable all delayed tasks upon shutdown, and method shutdownNow may be used to instead unconditionally initiate pool termination. Monitoring methods such as getQueuedTaskCount do not include scheduled tasks that are not yet enabled for execution, which are reported separately by method getDelayedTaskCount.

The parameters used to construct the common pool may be controlled by setting the following system properties:

If no thread factory is supplied via a system property, then the common pool uses a factory that uses the system class loader as the thread context class loader. Upon any error in establishing these settings, default parameters are used. It is possible to disable use of threads by using a factory that may return null, in which case some tasks may never execute. While possible, it is strongly discouraged to set the parallelism property to zero, which may be internally overridden in the presence of intrinsically async tasks.

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.

Author
Doug Lea
Since
1.7

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
ForkJoinPool.DefaultForkJoinWorkerThreadFactory

Default ForkJoinWorkerThreadFactory implementation; creates a new ForkJoinWorkerThread using the system class loader as the thread context class loader.

public static interface
public static interface
ForkJoinPool.ManagedBlocker

Interface for extending managed parallelism for tasks running in ForkJoinPools.

pack-priv static class
ForkJoinPool.TimeoutAction<V>

Body of a task performed on timeout of another task

pack-priv static class
ForkJoinPool.WorkQueue

Queues supporting work-stealing as well as external task submission.

Field Summary

Modifier and TypeField and Description
pack-priv static final long
pack-priv static final int
pack-priv static final long
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.ForkJoinWorkerThreadFactory
defaultForkJoinWorkerThreadFactory

Creates a new ForkJoinWorkerThread.

pack-priv volatile DelayScheduler
pack-priv static final int
pack-priv static final int
pack-priv final ForkJoinPool.ForkJoinWorkerThreadFactory
pack-priv static final int
pack-priv static final int
pack-priv static final int
INITIAL_EXTERNAL_QUEUE_CAPACITY

Initial capacity of work-stealing queue array for external queues.

pack-priv static final int
INITIAL_QUEUE_CAPACITY

Initial capacity of work-stealing queue array for workers.

pack-priv static final int
private static final JavaLangAccess
JLA

For VirtualThread intrinsics

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 final int
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 final String
pack-priv static final int
pack-priv ForkJoinPool.WorkQueue[]
pack-priv static final long
pack-priv static final int
pack-priv static final long
pack-priv static final long
pack-priv volatile long
private static final long
pack-priv final Predicate<? super ForkJoinPool>
pack-priv static final long
pack-priv static final int
pack-priv static final int
pack-priv volatile long
pack-priv static final long
pack-priv static final long
pack-priv static final int
pack-priv static final long
pack-priv static final long
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, also serving as the minimum allowed timeout value.

private static final Unsafe
U

pack-priv final Thread.UncaughtExceptionHandler
pack-priv static final long
pack-priv static final int
pack-priv final String

Constructor Summary

AccessConstructor and Description
public
public
ForkJoinPool(int
the parallelism level
parallelism
)

Creates a ForkJoinPool with the indicated parallelism level, using defaults for all other parameters (see ForkJoinPool(int, ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean, int, int, int, Predicate, long, TimeUnit)).

public
ForkJoinPool(int
the parallelism level. For default value, use java.lang.Runtime#availableProcessors.
parallelism
,
ForkJoinPool.ForkJoinWorkerThreadFactory
the factory for creating new threads. For default value, use defaultForkJoinWorkerThreadFactory.
factory
,
Thread.UncaughtExceptionHandler
the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. For default value, use null.
handler
,
boolean
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.
asyncMode
)

Creates a ForkJoinPool with the given parameters (using defaults for others -- see ForkJoinPool(int, ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean, int, int, int, Predicate, long, TimeUnit)).

public
ForkJoinPool(int
the parallelism level. For default value, use java.lang.Runtime#availableProcessors.
parallelism
,
ForkJoinPool.ForkJoinWorkerThreadFactory
the factory for creating new threads. For default value, use defaultForkJoinWorkerThreadFactory.
factory
,
Thread.UncaughtExceptionHandler
the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. For default value, use null.
handler
,
boolean
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.
asyncMode
,
int
ignored: used in previous releases of this class but no longer applicable. Using 0 maintains compatibility across releases.
corePoolSize
,
int
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 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).
maximumPoolSize
,
int
the minimum allowed number of core threads not blocked by a join or 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.
minimumRunnable
,
Predicate<? super ForkJoinPool>
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 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.
saturate
,
long
the elapsed time since last use before a thread is terminated (and then later replaced if needed). For the default value, use 60, TimeUnit.SECONDS.
keepAliveTime
,
TimeUnit
the time unit for the keepAliveTime argument
unit
)

Creates a ForkJoinPool with the given parameters.

private
ForkJoinPool(byte forCommonPoolOnly)

Constructor for common pool using parameters possibly overridden by system properties

Method Summary

Modifier and TypeMethod and Description
pack-priv static ForkJoinPool
asyncCommonPool()

Package-private access to commonPool overriding zero parallelism

public boolean

Returns:

true if quiescent; false if the timeout elapsed.
awaitQuiescence
(long
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 ForkJoinTask#helpQuiesce.

public boolean

Returns:

true if this executor terminated and false if the timeout elapsed before termination
awaitTermination
(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Implements java.util.concurrent.ExecutorService.awaitTermination.

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 exit
awaitWork
(ForkJoinPool.WorkQueue
the work queue
w
,
int
current phase (known to be idle)
p
)

Awaits signal or termination.

pack-priv final long

Returns:

value to use in endCompensatedBlock
beginCompensatedBlock
()

Invokes tryCompensate to create or re-activate a spare thread to compensate for a thread that performs a blocking operation.

public void
cancelDelayedTasksOnShutdown()

Arranges that scheduled tasks that are not executing and have not already been enabled for execution will not be executed and will be cancelled upon shutdown (unless this pool is the commonPool() which never shuts down).

private boolean
casRunState(long c, long v)

private boolean

Returns:

true if all queues empty
cleanQueues
()

Scans queues in a psuedorandom order based on thread id, cancelling tasks until empty, or returning early upon interference or still-active external queues, in which case other calls will finish cancellation.

public void
close()

Overrides default java.util.concurrent.ExecutorService.close.

Unless this is the commonPool(), initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted, and waits until all tasks have completed execution and the executor has terminated.

private CountDownLatch
public static ForkJoinPool

Returns:

the common pool instance
commonPool
()

Returns the common pool instance.

pack-priv static ForkJoinPool.WorkQueue
commonQueue()

Returns external queue for common pool.

private long
compareAndExchangeCtl(long c, long v)

private boolean
compareAndSetCtl(long c, long v)

private void
compensatedBlock(ForkJoinPool.ManagedBlocker blocker)

ManagedBlock for ForkJoinWorkerThreads

private boolean

Returns:

true if successful
createWorker
()

Tries to construct and start one worker.

private int

Returns:

current phase, with IDLE set if worker should exit
deactivate
(ForkJoinPool.WorkQueue
the worker
w
,
int
current phase
phase
)

Deactivates and if necessary awaits signal or termination.

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 transferred
drainTasksTo
(Collection<? super ForkJoinTask<?>>
the 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
endCompensatedBlock(long
value from beginCompensatedBlock
post
)

Re-adjusts parallelism after a blocking operation completes.

public void
execute(ForkJoinTask<?>
the task
task
)

Arranges for (asynchronous) execution of the given task.

public void
execute(Runnable task)

Implements java.util.concurrent.Executor.execute.

Executes the given command at some time in the future.

pack-priv final void
executeEnabledScheduledTask(DelayScheduler.ScheduledForkJoinTask<?> task)

Arranges execution of a ScheduledForkJoinTask whose delay has elapsed

private int

Returns:

positive if quiescent, negative if interrupted, else 0
externalHelpQuiesce
(long
max 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.WorkQueue
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.WorkQueue
externalSubmissionQueue(boolean rejectOnShutdown)

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<T>

Returns:

the task
externalSubmit
(ForkJoinTask<T>
the task to submit
task
)

Submits the given task as if submitted from a non-ForkJoinTask client.

public int

Returns:

the number of active threads
getActiveThreadCount
()

Returns an estimate of the number of threads that are currently stealing or executing tasks.

private long
getAndAddCtl(long v)

private static int
private long
private int
public boolean

Returns:

true if this pool uses async mode
getAsyncMode
()

Returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.

public static int

Returns:

the targeted parallelism level of the common pool
getCommonPoolParallelism
()

Returns the targeted parallelism level of the common pool.

public long

Returns:

an estimate of the number of delayed tasks
getDelayedTaskCount
()

Returns an estimate of the number of delayed (including periodic) tasks scheduled in this pool that are not yet ready to submit for execution.

public ForkJoinPool.ForkJoinWorkerThreadFactory

Returns:

the factory used for constructing new workers
getFactory
()

Returns the factory used for constructing new workers.

public int

Returns:

the targeted parallelism level of this pool
getParallelism
()

Returns the targeted parallelism level of this pool.

private int
public int

Returns:

the number of worker threads
getPoolSize
()

Returns the number of worker threads that have started but not yet terminated.

public int

Returns:

the number of queued submissions
getQueuedSubmissionCount
()

Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing.

public long

Returns:

the number of queued tasks
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).

public int

Returns:

the number of worker threads
getRunningThreadCount
()

Returns 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 steals
getStealCount
()

Returns 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.UncaughtExceptionHandler

Returns:

the handler, or null if none
getUncaughtExceptionHandler
()

Returns 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 submissions
hasQueuedSubmissions
()

Returns true if there are any tasks submitted to this pool that have not yet begun executing.

pack-priv static void
helpAsyncBlocker(Executor e, ForkJoinPool.ManagedBlocker blocker)

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 blocking
helpComplete
(ForkJoinTask<?>
root of computation (only called when a CountedCompleter)
task
,
ForkJoinPool.WorkQueue
caller's WorkQueue
w
,
boolean
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 blocking
helpJoin
(ForkJoinTask<?>
the task
task
,
ForkJoinPool.WorkQueue
caller's WorkQueue
w
,
boolean
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 0
helpQuiesce
(ForkJoinPool.WorkQueue w, long
max 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 0
helpQuiescePool
(ForkJoinPool
the 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
interruptAll()

Interrupts all workers

public <
the type of the task's result
T
>
T

Returns:

the task's result
invoke
(ForkJoinTask<T>
the task
task
)

Performs the given task, returning its result upon completion.

private <T> List<Future<T>>
invokeAll(Collection<? extends Callable<T>> tasks, long deadline)

Common support for timed and untimed invokeAll

public <T> List<Future<T>>
invokeAll(Collection<? extends Callable<T>> tasks)

Overrides java.util.concurrent.AbstractExecutorService.invokeAll.

Implements java.util.concurrent.ExecutorService.invokeAll.

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

public <T> List<Future<T>>
invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)

Overrides java.util.concurrent.AbstractExecutorService.invokeAll.

Implements java.util.concurrent.ExecutorService.invokeAll.

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<Future<T>>

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 completed
invokeAllUninterruptibly
(Collection<? extends Callable<T>>
the collection of tasks
tasks
)

Uninterrupible version of invokeAll.

public <T> T
invokeAny(Collection<? extends Callable<T>> tasks)

Overrides java.util.concurrent.AbstractExecutorService.invokeAny.

Implements java.util.concurrent.ExecutorService.invokeAny.

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>> tasks, long timeout, TimeUnit unit)

Overrides java.util.concurrent.AbstractExecutorService.invokeAny.

Implements java.util.concurrent.ExecutorService.invokeAny.

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 idle
isQuiescent
()

Returns true if all worker threads are currently idle.

public boolean

Returns:

true if this pool has been shut down
isShutdown
()

Implements java.util.concurrent.ExecutorService.isShutdown.

Returns true if this pool has been shut down.

public boolean

Returns:

true if all tasks have completed following shut down
isTerminated
()

Implements java.util.concurrent.ExecutorService.isTerminated.

Returns true if all tasks have completed following shut down.

public boolean

Returns:

true if terminating but not yet terminated
isTerminating
()

Returns true if the process of termination has commenced but not yet completed.

public <
the type of the task's result
T
>
ForkJoinTask<T>

Returns:

the task
lazySubmit
(ForkJoinTask<T>
the task
task
)

Submits the given task without guaranteeing that it will eventually execute in the absence of available active threads.

private long
public static void
managedBlock(ForkJoinPool.ManagedBlocker
the blocker task
blocker
)

Runs the given possibly blocking task.

protected <T> RunnableFuture<T>
newTaskFor(Runnable runnable, T value)

Overrides java.util.concurrent.AbstractExecutorService.newTaskFor.

Returns a RunnableFuture for the given runnable and default value.

protected <T> RunnableFuture<T>
newTaskFor(Callable<T> callable)

Overrides java.util.concurrent.AbstractExecutorService.newTaskFor.

Returns a RunnableFuture for the given callable task.

pack-priv final ForkJoinTask<?>

Returns:

a task, if available
nextTaskFor
(ForkJoinPool.WorkQueue w)

Gets and removes a local or stolen task for the given worker.

pack-priv final String
nextWorkerThreadName()

Provides a name for ForkJoinWorkerThread constructor.

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, or null if none
pollSubmission
()

Removes and returns the next unexecuted submission if one is available.

pack-priv static boolean
private <T> ForkJoinTask<T>
poolSubmit(boolean signalIfEmpty, ForkJoinTask<T> task)

private int

Returns:

positive if stopping, nonnegative if terminating or all workers are inactive and submission queues are empty and unlocked; if so, setting STOP if shutdown is enabled
quiescent
()

Internal version of isQuiescent and related functionality.

pack-priv final void
registerWorker(ForkJoinPool.WorkQueue
caller's WorkQueue
w
)

Finishes initializing and records internal queue.

private void
releaseWaiters()

Releases all waiting workers.

pack-priv final void
runWorker(ForkJoinPool.WorkQueue
caller's WorkQueue (may be null on failed initialization)
w
)

Top-level runloop for workers, called by ForkJoinWorkerThread.run.

public ScheduledFuture<?>

Returns:

a ForkJoinTask implementing the ScheduledFuture interface, whose get() method will return null upon normal completion.
schedule
(Runnable
the task to execute
command
,
long
the time from now to delay execution
delay
,
TimeUnit
the time unit of the delay parameter
unit
)

Implements java.util.concurrent.ScheduledExecutorService.schedule.

Submits a one-shot task that becomes enabled for execution after the given delay.

public <
the type of the callable's result
V
>
ScheduledFuture<V>

Returns:

a ForkJoinTask implementing the ScheduledFuture interface, whose get() method will return the value from the callable upon normal completion.
schedule
(Callable<V>
the function to execute
callable
,
long
the time from now to delay execution
delay
,
TimeUnit
the time unit of the delay parameter
unit
)

Implements java.util.concurrent.ScheduledExecutorService.schedule.

Submits a value-returning one-shot task that becomes enabled for execution after the given delay.

public ScheduledFuture<?>

Returns:

a ForkJoinTask implementing the ScheduledFuture interface. The future's get() method will never return normally, and will throw an exception upon task cancellation or abnormal termination of a task execution.
scheduleAtFixedRate
(Runnable
the task to execute
command
,
long
the time to delay first execution
initialDelay
,
long
the period between successive executions
period
,
TimeUnit
the time unit of the initialDelay and period parameters
unit
)

Implements java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate.

Submits a periodic action that becomes enabled for execution first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay, then initialDelay + period, then initialDelay + 2 * period, and so on.

pack-priv final <T> DelayScheduler.ScheduledForkJoinTask<T>

Returns:

the task
scheduleDelayedTask
(DelayScheduler.ScheduledForkJoinTask<T> task)

Arranges delayed execution of a ScheduledForkJoinTask via the DelayScheduler, creating and starting it if necessary.

public ScheduledFuture<?>

Returns:

a ForkJoinTask implementing the ScheduledFuture interface. The future's get() method will never return normally, and will throw an exception upon task cancellation or abnormal termination of a task execution.
scheduleWithFixedDelay
(Runnable
the task to execute
command
,
long
the time to delay first execution
initialDelay
,
long
the delay between the termination of one execution and the commencement of the next
delay
,
TimeUnit
the time unit of the initialDelay and delay parameters
unit
)

Implements java.util.concurrent.ScheduledExecutorService.scheduleWithFixedDelay.

Submits a periodic action that becomes enabled for execution first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

public int

Returns:

the previous parallelism level.
setParallelism
(int
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.util.concurrent.ExecutorService.shutdown.

Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

public List<Runnable>

Returns:

an empty list
shutdownNow
()

Implements java.util.concurrent.ExecutorService.shutdownNow.

Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks.

pack-priv final int
shutdownStatus(DelayScheduler ds)

Returns STOP and SHUTDOWN status (zero if neither), masking or truncating out other bits.

pack-priv final void
signalWork()

Releases an idle worker, or creates one if not enough exist.

pack-priv static long
slotOffset(int index)

Returns the array offset corresponding to the given index for Unsafe task queue operations

private long
private DelayScheduler
startDelayScheduler()

Creates and starts DelayScheduler

private ForkJoinPool.WorkQueue
submissionQueue(int
current ThreadLocalRandom.getProbe() value
r
,
boolean
true if RejectedExecutionException should be thrown when shutdown (else only if terminating)
rejectOnShutdown
)

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<T>

Returns:

the task
submit
(ForkJoinTask<T>
the task to submit
task
)

Submits a ForkJoinTask for execution.

public <T> ForkJoinTask<T>
submit(Callable<T> task)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

public <T> ForkJoinTask<T>
submit(Runnable task, T result)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a Runnable task for execution and returns a Future representing that task.

public ForkJoinTask<?>
submit(Runnable task)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a Runnable task for execution and returns a Future representing that task.

public <
the type of the callable's result
V
>
ForkJoinTask<V>

Returns:

a Future that can be used to extract result or cancel
submitWithTimeout
(Callable<V>
the function to execute
callable
,
long
the time to wait before cancelling if not completed
timeout
,
TimeUnit
the time unit of the timeout parameter
unit
,
Consumer<? super ForkJoinTask<V>>
if nonnull, an action to perform on timeout, otherwise the default action is to cancel using cancel(true).
timeoutAction
)

Submits a task executing the given function, cancelling the task or performing a given timeoutAction if not completed within the given timeout period.

private CountDownLatch
terminationSignal()

Returns termination signal, constructing if necessary

public String

Returns:

a string identifying this pool, as well as its state
toString
()

Overrides java.lang.Object.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 int

Returns:

UNCOMPENSATE: block then adjust, 0: block, -1 : retry
tryCompensate
(long
incoming ctl value
c
)

Tries to decrement counts (sometimes implicitly) and possibly arrange for a compensating worker in preparation for blocking.

pack-priv final boolean
tryStopIfShutdown(DelayScheduler ds)

Tries to stop and possibly terminate if already enabled, return success.

private long

Returns:

runState on exit
tryTerminate
(boolean
if 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.

private int

Returns:

> 0: trimmed, < 0 : not trimmable, else 0
tryTrim
(ForkJoinPool.WorkQueue w, int phase, long deadline)

Tries to remove and deregister worker after timeout, and release another to do the same.

pack-priv final void
uncompensate()

Readjusts RC count; called from ForkJoinTask after blocking.

private void
private static void
unmanagedBlock(ForkJoinPool.ManagedBlocker blocker)

ManagedBlock for external threads