|
||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||
java.lang.Objectjava.util.concurrent.AbstractExecutorService
jsr166y.ForkJoinPool
public class ForkJoinPool
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 subtasks 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). When setting asyncMode to true in
constructors, ForkJoinPools may also be appropriate for use
with event-style tasks that are never joined.
A ForkJoinPool is 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 IO 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 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
NOT use these pool execution methods, but instead use the
within-computation forms listed in the table.
| 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) |
Sample Usage. Normally a single ForkJoinPool is
used for all parallel task execution in a program or subsystem.
Otherwise, use would not usually outweigh the construction and
bookkeeping overhead of creating a large set of threads. For
example, a common pool could be used for the SortTasks
illustrated in RecursiveAction. Because ForkJoinPool uses threads in daemon mode, there is typically no need to explicitly shutdown such a pool upon program exit.
static final ForkJoinPool mainPool = new ForkJoinPool();
...
public void sort(long[] array) {
mainPool.invoke(new SortTask(array, 0, array.length));
}
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.
| Nested Class Summary | |
|---|---|
static interface |
ForkJoinPool.ForkJoinWorkerThreadFactory
Factory for creating new ForkJoinWorkerThreads. |
static interface |
ForkJoinPool.ManagedBlocker
Interface for extending managed parallelism for tasks running in ForkJoinPools. |
| Field Summary | |
|---|---|
static ForkJoinPool.ForkJoinWorkerThreadFactory |
defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread. |
| Constructor Summary | |
|---|---|
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. |
|
| Method Summary | ||
|---|---|---|
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. |
|
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)
|
|
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. |
|
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. |
|
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. |
|
|
invoke(ForkJoinTask<T> task)
Performs the given task, returning its result upon completion. |
|
|
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
|
newTaskFor(java.util.concurrent.Callable<T> callable)
|
|
protected
|
newTaskFor(java.lang.Runnable runnable,
T value)
|
|
protected ForkJoinTask<?> |
pollSubmission()
Removes and returns the next unexecuted submission if one is available. |
|
void |
shutdown()
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()
Attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. |
|
|
submit(java.util.concurrent.Callable<T> task)
|
|
|
submit(ForkJoinTask<T> task)
Submits a ForkJoinTask for execution. |
|
ForkJoinTask<?> |
submit(java.lang.Runnable task)
|
|
|
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. |
|
| Methods inherited from class java.util.concurrent.AbstractExecutorService |
|---|
invokeAll, invokeAny, invokeAny |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
|---|
public static final ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory
| Constructor Detail |
|---|
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 level
java.lang.IllegalArgumentException - if parallelism less than or
equal to zero, or greater than implementation limit
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.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 limit
java.lang.NullPointerException - if the 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 |
|---|
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 task
java.lang.NullPointerException - if the task is null
java.util.concurrent.RejectedExecutionException - if the task cannot be
scheduled for executionpublic void execute(ForkJoinTask<?> task)
task - the task
java.lang.NullPointerException - if the task is null
java.util.concurrent.RejectedExecutionException - if the task cannot be
scheduled for executionpublic void execute(java.lang.Runnable task)
java.lang.NullPointerException - if the task is null
java.util.concurrent.RejectedExecutionException - if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)
task - the task to submit
java.lang.NullPointerException - if the task is null
java.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.ExecutorServicesubmit in class java.util.concurrent.AbstractExecutorServicejava.lang.NullPointerException - if the task is null
java.util.concurrent.RejectedExecutionException - if the task cannot be
scheduled for execution
public <T> ForkJoinTask<T> submit(java.lang.Runnable task,
T result)
submit in interface java.util.concurrent.ExecutorServicesubmit in class java.util.concurrent.AbstractExecutorServicejava.lang.NullPointerException - if the task is null
java.util.concurrent.RejectedExecutionException - if the task cannot be
scheduled for executionpublic ForkJoinTask<?> submit(java.lang.Runnable task)
submit in interface java.util.concurrent.ExecutorServicesubmit in class java.util.concurrent.AbstractExecutorServicejava.lang.NullPointerException - if the task is null
java.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.ExecutorServiceinvokeAll in class java.util.concurrent.AbstractExecutorServicejava.lang.NullPointerException
java.util.concurrent.RejectedExecutionExceptionpublic ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
null if nonepublic int getParallelism()
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 into
public java.lang.String toString()
toString in class java.lang.Objectpublic void shutdown()
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()
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 IO,
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 down
public boolean awaitTermination(long timeout,
java.util.concurrent.TimeUnit unit)
throws java.lang.InterruptedException
timeout - the maximum time to waitunit - the time unit of the timeout argument
true if this executor terminated and
false if the timeout elapsed before termination
java.lang.InterruptedException - if interrupted while waiting
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 blocker
java.lang.InterruptedException - if blocker.block did so
protected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.lang.Runnable runnable,
T value)
newTaskFor in class java.util.concurrent.AbstractExecutorServiceprotected <T> java.util.concurrent.RunnableFuture<T> newTaskFor(java.util.concurrent.Callable<T> callable)
newTaskFor in class java.util.concurrent.AbstractExecutorService
|
||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||