Class ForkJoinPool
- java.lang.Object
-
- java.util.concurrent.AbstractExecutorService
-
- akka.dispatch.forkjoin.ForkJoinPool
-
- All Implemented Interfaces:
java.util.concurrent.Executor,java.util.concurrent.ExecutorService
- Direct Known Subclasses:
ForkJoinExecutorConfigurator.AkkaForkJoinPool
public class ForkJoinPool extends java.util.concurrent.AbstractExecutorServiceAnExecutorServicefor runningForkJoinTasks. AForkJoinPoolprovides the entry point for submissions from non-ForkJoinTaskclients, as well as management and monitoring operations.A
ForkJoinPooldiffers from other kinds ofExecutorServicemainly 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 mostForkJoinTasks), 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.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
ForkJoinPoolmay 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 nestedForkJoinPool.ManagedBlockerinterface 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, methodtoString()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 plainRunnable- orCallable- 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 propertieswith prefixjava.util.concurrent.ForkJoinPool.common:parallelism-- an integer greater than zero,threadFactory-- the class name of aForkJoinPool.ForkJoinWorkerThreadFactory, andexceptionHandler-- the class name of aThread.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.- Since:
- 1.7
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceForkJoinPool.ForkJoinWorkerThreadFactoryFactory for creating newForkJoinWorkerThreads.static interfaceForkJoinPool.ManagedBlockerInterface for extending managed parallelism for tasks running inForkJoinPools.
-
Field Summary
Fields Modifier and Type Field Description static ForkJoinPool.ForkJoinWorkerThreadFactorydefaultForkJoinWorkerThreadFactoryCreates a new ForkJoinWorkerThread.
-
Constructor Summary
Constructors Constructor Description ForkJoinPool()Creates aForkJoinPoolwith parallelism equal toRuntime.availableProcessors(), using the default thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.ForkJoinPool(int parallelism)Creates aForkJoinPoolwith 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 aForkJoinPoolwith the given parameters.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanawaitQuiescence(long timeout, java.util.concurrent.TimeUnit unit)If called by a ForkJoinTask operating in this pool, equivalent in effect toForkJoinTask.helpQuiesce().booleanawaitTermination(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.static ForkJoinPoolcommonPool()Returns the common pool instance.protected intdrainTasksTo(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.voidexecute(ForkJoinTask<?> task)Arranges for (asynchronous) execution of the given task.voidexecute(java.lang.Runnable task)intgetActiveThreadCount()Returns an estimate of the number of threads that are currently stealing or executing tasks.booleangetAsyncMode()Returnstrueif this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.static intgetCommonPoolParallelism()Returns the targeted parallelism level of the common pool.ForkJoinPool.ForkJoinWorkerThreadFactorygetFactory()Returns the factory used for constructing new workers.intgetParallelism()Returns the targeted parallelism level of this pool.intgetPoolSize()Returns the number of worker threads that have started but not yet terminated.intgetQueuedSubmissionCount()Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing.longgetQueuedTaskCount()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).intgetRunningThreadCount()Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization.longgetStealCount()Returns an estimate of the total number of tasks stolen from one thread's work queue by another.java.lang.Thread.UncaughtExceptionHandlergetUncaughtExceptionHandler()Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.booleanhasQueuedSubmissions()Returnstrueif there are any tasks submitted to this pool that have not yet begun executing.<T> Tinvoke(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)booleanisQuiescent()Returnstrueif all worker threads are currently idle.booleanisShutdown()Returnstrueif this pool has been shut down.booleanisTerminated()Returnstrueif all tasks have completed following shut down.booleanisTerminating()Returnstrueif the process of termination has commenced but not yet completed.static voidmanagedBlock(ForkJoinPool.ManagedBlocker blocker)Blocks in accord with the given blocker.protected <T> java.util.concurrent.RunnableFuture<T>newTaskFor(java.lang.Runnable runnable, T value)protected <T> java.util.concurrent.RunnableFuture<T>newTaskFor(java.util.concurrent.Callable<T> callable)protected ForkJoinTask<?>pollSubmission()Removes and returns the next unexecuted submission if one is available.voidshutdown()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.<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)<T> ForkJoinTask<T>submit(java.util.concurrent.Callable<T> task)java.lang.StringtoString()Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.
-
-
-
Field Detail
-
defaultForkJoinWorkerThreadFactory
public static final ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread. This factory is used unless overridden in ForkJoinPool constructors.
-
-
Constructor Detail
-
ForkJoinPool
public ForkJoinPool()
Creates aForkJoinPoolwith parallelism equal toRuntime.availableProcessors(), using the default thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.- Throws:
java.lang.SecurityException- if a security manager exists and the caller is not permitted to modify threads because it does not holdRuntimePermission("modifyThread")
-
ForkJoinPool
public ForkJoinPool(int parallelism)
Creates aForkJoinPoolwith the indicated parallelism level, the default thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.- Parameters:
parallelism- the parallelism level- Throws:
java.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 holdRuntimePermission("modifyThread")
-
ForkJoinPool
public ForkJoinPool(int parallelism, ForkJoinPool.ForkJoinWorkerThreadFactory factory, java.lang.Thread.UncaughtExceptionHandler handler, boolean asyncMode)Creates aForkJoinPoolwith the given parameters.- Parameters:
parallelism- the parallelism level. For default value, useRuntime.availableProcessors().factory- the factory for creating new threads. For default value, usedefaultForkJoinWorkerThreadFactory.handler- the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. For default value, usenull.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, usefalse.- Throws:
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 holdRuntimePermission("modifyThread")
-
-
Method Detail
-
commonPool
public static ForkJoinPool commonPool()
Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts toshutdown()orshutdownNow(). However this pool and any ongoing processing are automatically terminated upon programSystem.exit(int). Any program that relies on asynchronous task processing to complete before program termination should invokecommonPool().awaitQuiescence(long, java.util.concurrent.TimeUnit), before exit.- Returns:
- the common pool instance
- Since:
- 1.8
-
invoke
public <T> T invoke(ForkJoinTask<T> task)
Performs the given task, returning its result upon completion. If the computation encounters an unchecked Exception or Error, it is rethrown as the outcome of this invocation. Rethrown exceptions behave in the same way as regular exceptions, but, when possible, contain stack traces (as displayed for example usingex.printStackTrace()) of both the current thread as well as the thread actually encountering the exception; minimally only the latter.- Parameters:
task- the task- Returns:
- the task's result
- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
execute
public void execute(ForkJoinTask<?> task)
Arranges for (asynchronous) execution of the given task.- Parameters:
task- the task- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
execute
public void execute(java.lang.Runnable task)
- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
submit
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)
Submits a ForkJoinTask for execution.- Parameters:
task- the task to submit- Returns:
- the task
- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
submit
public <T> ForkJoinTask<T> submit(java.util.concurrent.Callable<T> task)
- Specified by:
submitin interfacejava.util.concurrent.ExecutorService- Overrides:
submitin classjava.util.concurrent.AbstractExecutorService- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
submit
public <T> ForkJoinTask<T> submit(java.lang.Runnable task, T result)
- Specified by:
submitin interfacejava.util.concurrent.ExecutorService- Overrides:
submitin classjava.util.concurrent.AbstractExecutorService- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
submit
public ForkJoinTask<?> submit(java.lang.Runnable task)
- Specified by:
submitin interfacejava.util.concurrent.ExecutorService- Overrides:
submitin classjava.util.concurrent.AbstractExecutorService- Throws:
java.lang.NullPointerException- if the task is nulljava.util.concurrent.RejectedExecutionException- if the task cannot be scheduled for execution
-
invokeAll
public <T> java.util.List<java.util.concurrent.Future<T>> invokeAll(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks)
- Specified by:
invokeAllin interfacejava.util.concurrent.ExecutorService- Overrides:
invokeAllin classjava.util.concurrent.AbstractExecutorService- Throws:
java.lang.NullPointerExceptionjava.util.concurrent.RejectedExecutionException
-
getFactory
public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
Returns the factory used for constructing new workers.- Returns:
- the factory used for constructing new workers
-
getUncaughtExceptionHandler
public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.- Returns:
- the handler, or
nullif none
-
getParallelism
public int getParallelism()
Returns the targeted parallelism level of this pool.- Returns:
- the targeted parallelism level of this pool
-
getCommonPoolParallelism
public static int getCommonPoolParallelism()
Returns the targeted parallelism level of the common pool.- Returns:
- the targeted parallelism level of the common pool
- Since:
- 1.8
-
getPoolSize
public int getPoolSize()
Returns the number of worker threads that have started but not yet terminated. The result returned by this method may differ fromgetParallelism()when threads are created to maintain parallelism when others are cooperatively blocked.- Returns:
- the number of worker threads
-
getAsyncMode
public boolean getAsyncMode()
Returnstrueif this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.- Returns:
trueif this pool uses async mode
-
getRunningThreadCount
public int getRunningThreadCount()
Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization. This method may overestimate the number of running threads.- Returns:
- the number of worker threads
-
getActiveThreadCount
public int getActiveThreadCount()
Returns an estimate of the number of threads that are currently stealing or executing tasks. This method may overestimate the number of active threads.- Returns:
- the number of active threads
-
isQuiescent
public boolean isQuiescent()
Returnstrueif 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 returntrueimmediately upon idleness of all threads, but will eventually become true if threads remain inactive.- Returns:
trueif all threads are currently idle
-
getStealCount
public long getStealCount()
Returns an estimate of the total number of tasks stolen from one thread's work queue by another. The reported value underestimates the actual total number of steals when the pool is not quiescent. This value may be useful for monitoring and tuning fork/join programs: in general, steal counts should be high enough to keep threads busy, but low enough to avoid overhead and contention across threads.- Returns:
- the number of steals
-
getQueuedTaskCount
public 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). This value is only an approximation, obtained by iterating across all threads in the pool. This method may be useful for tuning task granularities.- Returns:
- the number of queued tasks
-
getQueuedSubmissionCount
public int getQueuedSubmissionCount()
Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing. This method may take time proportional to the number of submissions.- Returns:
- the number of queued submissions
-
hasQueuedSubmissions
public boolean hasQueuedSubmissions()
Returnstrueif there are any tasks submitted to this pool that have not yet begun executing.- Returns:
trueif there are any queued submissions
-
pollSubmission
protected ForkJoinTask<?> pollSubmission()
Removes and returns the next unexecuted submission if one is available. This method may be useful in extensions to this class that re-assign work in systems with multiple pools.- Returns:
- the next submission, or
nullif none
-
drainTasksTo
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. These may include artificially generated or wrapped tasks. This method is designed to be invoked only when the pool is known to be quiescent. Invocations at other times may not remove all tasks. A failure encountered while attempting to add elements to collectioncmay 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.- Parameters:
c- the collection to transfer elements into- Returns:
- the number of elements transferred
-
toString
public 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.- Overrides:
toStringin classjava.lang.Object- Returns:
- a string identifying this pool, as well as its state
-
shutdown
public void shutdown()
Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no effect on execution state if this is thecommonPool(), 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.- Throws:
java.lang.SecurityException- if a security manager exists and the caller is not permitted to modify threads because it does not holdRuntimePermission("modifyThread")
-
shutdownNow
public java.util.List<java.lang.Runnable> shutdownNow()
Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. Invocation has no effect on execution state if this is thecommonPool(), 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).- Returns:
- an empty list
- Throws:
java.lang.SecurityException- if a security manager exists and the caller is not permitted to modify threads because it does not holdRuntimePermission("modifyThread")
-
isTerminated
public boolean isTerminated()
Returnstrueif all tasks have completed following shut down.- Returns:
trueif all tasks have completed following shut down
-
isTerminating
public boolean isTerminating()
Returnstrueif the process of termination has commenced but not yet completed. This method may be useful for debugging. A return oftruereported 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 classForkJoinTaskstating that tasks should not normally entail blocking operations. But if they do, they must abort them on interrupt.)- Returns:
trueif terminating but not yet terminated
-
isShutdown
public boolean isShutdown()
Returnstrueif this pool has been shut down.- Returns:
trueif this pool has been shut down
-
awaitTermination
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) throws java.lang.InterruptedExceptionBlocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. Because thecommonPool()never terminates until program shutdown, when applied to the common pool, this method is equivalent toawaitQuiescence(long, java.util.concurrent.TimeUnit)but always returnsfalse.- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout argument- Returns:
trueif this executor terminated andfalseif the timeout elapsed before termination- Throws:
java.lang.InterruptedException- if interrupted while waiting
-
awaitQuiescence
public boolean awaitQuiescence(long timeout, java.util.concurrent.TimeUnit unit)If called by a ForkJoinTask operating in this pool, equivalent in effect toForkJoinTask.helpQuiesce(). Otherwise, waits and/or attempts to assist performing tasks until this poolisQuiescent()or the indicated timeout elapses.- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout argument- Returns:
trueif quiescent;falseif the timeout elapsed.
-
managedBlock
public static void managedBlock(ForkJoinPool.ManagedBlocker blocker) throws java.lang.InterruptedException
Blocks in accord with the given blocker. If the current thread is aForkJoinWorkerThread, 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
If the caller is awhile (!blocker.isReleasable()) if (blocker.block()) return;ForkJoinTask, then the pool may first be expanded to ensure parallelism, and later adjusted.- Parameters:
blocker- the blocker- Throws:
java.lang.InterruptedException- if blocker.block did so
-
newTaskFor
protected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.lang.Runnable runnable, T value)- Overrides:
newTaskForin classjava.util.concurrent.AbstractExecutorService
-
newTaskFor
protected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.util.concurrent.Callable<T> callable)
- Overrides:
newTaskForin classjava.util.concurrent.AbstractExecutorService
-
-