jsr166z.forkjoin
Class ForkJoinPool

java.lang.Object
  extended by jsr166z.forkjoin.ForkJoinPool
All Implemented Interfaces:
ForkJoinExecutor

public class ForkJoinPool
extends java.lang.Object
implements ForkJoinExecutor

Host for a group of ForkJoinWorkerThreads that perform ForkJoinTasks. It also provides the entry point for tasks submitted from non-ForkJoinTasks, as well as management and monitoring operations. Normally a single ForkJoinPool is used for a large number of submitted tasks. Otherwise, use would not always outweigh the construction overhead of creating a large set of threads and the associated startup bookkeeping.

Class ForkJoinPool does not implement the ExecutorService interface because it only executes ForkJoinTasks, not arbitrary Runnables. However, for the sake of uniformity, it supports analogous lifecycle control methods such as shutdown.

A ForkJoinPool may be constructed with any number of worker threads, and worker threads may be added and removed dynamically. However, as a general rule, using a pool size of the number of processors on a given system, as arranged by the default constructor) will result in the best performance. Resizing may be expensive and may cause transient imbalances and slowdowns.

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.


Nested Class Summary
static class ForkJoinPool.DefaultForkJoinWorkerThreadFactory
          The default ForkJoinWorkerThreadFactory, used unless overridden in ForkJoinPool constructors.
static interface ForkJoinPool.ForkJoinWorkerThreadFactory
          Factory for creating new ForkJoinWorkerThreads.
 
Constructor Summary
ForkJoinPool()
          Creates a ForkJoinPool with a pool size equal to the number of processors available on the system and using the default ForkJoinWorkerThreadFactory,
ForkJoinPool(ForkJoinPool.ForkJoinWorkerThreadFactory factory)
          Creates a ForkJoinPool with a pool size equal to the number of processors available on the system and using the given ForkJoinWorkerThreadFactory,
ForkJoinPool(int poolSize)
          Creates a ForkJoinPool with the indicated number of Worker threads, and using the default ForkJoinWorkerThreadFactory,
ForkJoinPool(int poolSize, ForkJoinPool.ForkJoinWorkerThreadFactory factory)
          Creates a ForkJoinPool with the indicated number of worker threads and the given factory.
 
Method Summary
 int addWorkers(int numberToAdd)
          Tries to adds the indicated number of new worker threads to the pool.
 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.
<T> void
execute(ForkJoinTask<T> task)
          Arranges for (asynchronous) execution of the given task.
 int getActiveSubmissionCount()
          Returns the number of tasks that have been submitted (via submit or invoke) and are currently executing in the pool.
 int getActiveThreadCount()
          Returns the approximate number of threads that are currently executing tasks.
 ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
          Returns the factory used for constructing new workers
 int getIdleThreadCount()
          Returns the approximate number of threads that are currently idle waiting for tasks.
 int getParallelismLevel()
          Equivalent to getPoolSize().
 int getPoolSize()
          Returns the targetted number of worker threads in this pool.
 int getRunningWorkerCount()
          Returns the number of worker threads that have started but not yet terminated.
 long getStealCount()
          Returns the total number of tasks stolen from one thread's work queue by another.
 long getTotalPerThreadQueueSize()
          Returns 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).
 java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
          Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.
 boolean hasQueuedSubmissions()
          Returns true if there are any tasks submitted to this pool that have not yet begun executing.
<T> T
invoke(ForkJoinTask<T> task)
          Performs the given task; returning its result upon completion
 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 termination has commenced but has not yet completed.
 int removeWorkers(int numberToRemove)
          Tries to remove the indicated number of worker threads from the pool.
 int setPoolSize(int newSize)
          Tries to add or remove workers to attain the given pool size.
 java.lang.Thread.UncaughtExceptionHandler setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler h)
          Sets the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.
 void shutdown()
          Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
 void shutdownNow()
          Attempts to stop all actively executing tasks, and cancels all waiting tasks.
<T> java.util.concurrent.Future<T>
submit(ForkJoinTask<T> task)
          Arranges for (asynchronous) execution of the given task, returning a Future that may be used to obtain results upon completion.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ForkJoinPool

public ForkJoinPool()
Creates a ForkJoinPool with a pool size equal to the number of processors available on the system and using the default ForkJoinWorkerThreadFactory,

Throws:
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

ForkJoinPool

public ForkJoinPool(int poolSize)
Creates a ForkJoinPool with the indicated number of Worker threads, and using the default ForkJoinWorkerThreadFactory,

Parameters:
poolSize - the number of worker threads
Throws:
java.lang.IllegalArgumentException - if poolSize less than or equal to zero
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

ForkJoinPool

public ForkJoinPool(ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with a pool size equal to the number of processors available on the system and using the given ForkJoinWorkerThreadFactory,

Parameters:
factory - the factory for creating new threads
Throws:
java.lang.NullPointerException - if factory is null
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

ForkJoinPool

public ForkJoinPool(int poolSize,
                    ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with the indicated number of worker threads and the given factory.

You can also add and remove threads while the pool is running. But it is generally more efficient and leads to more predictable performance to initialize the pool with a sufficient number of threads to support the desired concurrency level and leave this value fixed.

Parameters:
poolSize - the number of worker threads
factory - the factory for creating new threads
Throws:
java.lang.IllegalArgumentException - if poolSize less than or equal to zero
java.lang.NullPointerException - if factory is null
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),
Method Detail

invoke

public <T> T invoke(ForkJoinTask<T> task)
Performs the given task; returning its result upon completion

Specified by:
invoke in interface ForkJoinExecutor
Parameters:
task - the task
Returns:
the task's result
Throws:
java.lang.NullPointerException - if task is null
java.util.concurrent.RejectedExecutionException - if pool is shut down

submit

public <T> java.util.concurrent.Future<T> submit(ForkJoinTask<T> task)
Arranges for (asynchronous) execution of the given task, returning a Future that may be used to obtain results upon completion.

Specified by:
submit in interface ForkJoinExecutor
Parameters:
task - the task
Returns:
a Future that can be used to get the task's results.
Throws:
java.lang.NullPointerException - if task is null
java.util.concurrent.RejectedExecutionException - if pool is shut down

execute

public <T> void execute(ForkJoinTask<T> task)
Arranges for (asynchronous) execution of the given task.

Specified by:
execute in interface ForkJoinExecutor
Parameters:
task - the task
Throws:
java.lang.NullPointerException - if task is null
java.util.concurrent.RejectedExecutionException - if pool is shut down

getPoolSize

public int getPoolSize()
Returns the targetted number of worker threads in this pool. This value does not necessarily reflect transient changes as threads are added, removed, or abruptly terminate.

Returns:
the number of worker threads in this pool

getParallelismLevel

public int getParallelismLevel()
Equivalent to getPoolSize().

Specified by:
getParallelismLevel in interface ForkJoinExecutor
Returns:
the number of worker threads in this pool

getRunningWorkerCount

public int getRunningWorkerCount()
Returns the number of worker threads that have started but not yet terminated. This result returned by this method may differ from getPoolSize when threads are added, removed, or abruptly terminate.

Returns:
the number of worker threads

setUncaughtExceptionHandler

public java.lang.Thread.UncaughtExceptionHandler setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler h)
Sets the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. Unless set, the current default or ThreadGroup handler is used as handler.

Parameters:
h - the new handler
Returns:
the old handler, or null if none
Throws:
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

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 null if none

addWorkers

public int addWorkers(int numberToAdd)
Tries to adds the indicated number of new worker threads to the pool. This method may be used to increase the amount of parallelism available to tasks. The actual number of threads added may be less than requested if the pool is terminating or terminated

Returns:
the number of threads added
Throws:
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

removeWorkers

public int removeWorkers(int numberToRemove)
Tries to remove the indicated number of worker threads from the pool. The workers will exit the next time they are idle. This method may be used to decrease the amount of parallelism available to tasks. The actual number of workers removed may be less than requested if the pool size would become zero or the pool is terminating or terminated.

Returns:
the number removed.
Throws:
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

setPoolSize

public int setPoolSize(int newSize)
Tries to add or remove workers to attain the given pool size. This may fail to attain the given target if the pool is terminating or terminated.

Parameters:
newSize - the target poolSize
Returns:
the pool size upon exit of this method
Throws:
java.lang.IllegalArgumentException - if newSize less than or equal to zero
java.lang.SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread"),

shutdown

public void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has 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 hold RuntimePermission("modifyThread"),

shutdownNow

public void shutdownNow()
Attempts to stop all actively executing tasks, and cancels all waiting tasks. Tasks that are in the process of being submitted or executed 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 hold RuntimePermission("modifyThread"),

isShutdown

public boolean isShutdown()
Returns true if this pool has been shut down.

Returns:
true if this pool has been shut down

isTerminated

public boolean isTerminated()
Returns true if all tasks have completed following shut down.

Returns:
true if all tasks have completed following shut down

isTerminating

public boolean isTerminating()
Returns true if termination has commenced but has not yet completed.

Returns:
true if in the process of terminating

awaitTermination

public boolean awaitTermination(long timeout,
                                java.util.concurrent.TimeUnit unit)
                         throws java.lang.InterruptedException
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Parameters:
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
true if this executor terminated and false if the timeout elapsed before termination
Throws:
java.lang.InterruptedException - if interrupted while waiting

isQuiescent

public final boolean isQuiescent()
Returns 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.

Returns:
true if all threads are currently idle

getActiveThreadCount

public int getActiveThreadCount()
Returns the approximate number of threads that are currently executing tasks. This method may overestimate the number of active threads.

Returns:
the number of active threads.

getIdleThreadCount

public int getIdleThreadCount()
Returns the approximate number of threads that are currently idle waiting for tasks. This method may underestimate the number of idel threads.

Returns:
the number of idle threads.

getStealCount

public long getStealCount()
Returns the total number of tasks stolen from one thread's work queue by another. This value is only an approximation, obtained by iterating across all threads in the pool, and may lag the actual total number of steals when the pool is not quiescent. But the value is still 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.

getTotalPerThreadQueueSize

public long getTotalPerThreadQueueSize()
Returns 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 tasks.

hasQueuedSubmissions

public boolean hasQueuedSubmissions()
Returns true if there are any tasks submitted to this pool that have not yet begun executing.

Returns:
true if there are any queued submissions.

getActiveSubmissionCount

public int getActiveSubmissionCount()
Returns the number of tasks that have been submitted (via submit or invoke) and are currently executing in the pool.

Returns:
the number of tasks.

getFactory

public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
Returns the factory used for constructing new workers

Returns:
the factory used for constructing new workers