|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectjava.util.concurrent.AbstractExecutorService
java.util.concurrent.ForkJoinPool
public class ForkJoinPool
Disabled: no SafeJ information.
An ExecutorService
for running ForkJoinTask
s.
A ForkJoinPool
provides the entry point for submissions
from non-ForkJoinTask
s, 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 ForkJoinTask
s). A ForkJoinPool
may also be used for mixed
execution of some plain Runnable
- or Callable
-
based activities along with ForkJoinTask
s. When setting
async mode, a ForkJoinPool
may
also be appropriate for use with fine-grained tasks of any form
that are never joined. Otherwise, other ExecutorService
implementations are typically more appropriate choices.
A ForkJoinPool
is constructed with a given target
parallelism level; by default, equal to the number of available
processors. Unless configured otherwise via setMaintainsParallelism(boolean)
, the pool attempts to maintain this
number of 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 performed in the face of blocked IO or other unmanaged
synchronization. The nested ForkJoinPool.ManagedBlocker
interface
enables extension of the kinds of synchronization accommodated.
The target parallelism level may also be changed dynamically
(setParallelism(int)
). The total number of threads may be
limited using method setMaximumPoolSize(int)
, in which case it
may become possible for the activities of a pool to stall due to
the lack of available threads to process new tasks.
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.
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.
Nested Class Summary | |
---|---|
static interface |
ForkJoinPool.ForkJoinWorkerThreadFactory
Factory for creating new ForkJoinWorkerThread s. |
static interface |
ForkJoinPool.ManagedBlocker
Interface for extending managed parallelism for tasks running in ForkJoinPool s. |
Field Summary | |
---|---|
static ForkJoinPool.ForkJoinWorkerThreadFactory |
defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread. |
Constructor Summary | |
---|---|
ForkJoinPool()
Creates a ForkJoinPool with parallelism equal to Runtime.availableProcessors() , and using the default thread factory. |
|
ForkJoinPool(ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with parallelism equal to Runtime.availableProcessors() , and using the given
thread factory. |
|
ForkJoinPool(int parallelism)
Creates a ForkJoinPool with the indicated parallelism
level and using the default thread factory. |
|
ForkJoinPool(int parallelism,
ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with the given parallelism and
thread factory. |
Method Summary | ||
---|---|---|
boolean |
awaitTermination(long timeout,
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(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(Runnable task)
Executes the given command at some time in the future. |
|
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. |
|
boolean |
getMaintainsParallelism()
Returns true if this pool dynamically maintains its
target parallelism level. |
|
int |
getMaximumPoolSize()
Returns the maximum number of threads allowed to exist in the pool. |
|
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. |
|
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(Collection<? extends Callable<T>> tasks)
Executes the given tasks, returning a list of Futures holding their status and results when all complete. |
|
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,
boolean maintainParallelism)
Blocks in accord with the given blocker. |
|
protected
|
newTaskFor(Callable<T> callable)
Returns a RunnableFuture for the given callable task. |
|
protected
|
newTaskFor(Runnable runnable,
T value)
Returns a RunnableFuture for the given runnable and default value. |
|
protected ForkJoinTask<?> |
pollSubmission()
Removes and returns the next unexecuted submission if one is available. |
|
boolean |
setAsyncMode(boolean async)
Establishes local first-in-first-out scheduling mode for forked tasks that are never joined. |
|
void |
setMaintainsParallelism(boolean enable)
Sets whether this pool dynamically maintains its target parallelism level. |
|
void |
setMaximumPoolSize(int newMax)
Sets the maximum number of threads allowed to exist in the pool. |
|
void |
setParallelism(int parallelism)
Sets the target parallelism level of this pool. |
|
Thread.UncaughtExceptionHandler |
setUncaughtExceptionHandler(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. |
|
List<Runnable> |
shutdownNow()
Attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. |
|
|
submit(Callable<T> task)
Submits a value-returning task for execution and returns a Future representing the pending results of the task. |
|
|
submit(ForkJoinTask<T> task)
Submits a ForkJoinTask for execution. |
|
ForkJoinTask<?> |
submit(Runnable task)
Submits a Runnable task for execution and returns a Future representing that task. |
|
|
submit(Runnable task,
T result)
Submits a Runnable task for execution and returns a Future representing that task. |
|
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()
, and using the default thread factory.
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 and using the default thread factory.
parallelism
- the parallelism level
IllegalArgumentException
- if parallelism less than or
equal to zero, or greater than implementation limit
SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public ForkJoinPool(ForkJoinPool.ForkJoinWorkerThreadFactory factory)
ForkJoinPool
with parallelism equal to Runtime.availableProcessors()
, and using the given
thread factory.
factory
- the factory for creating new threads
NullPointerException
- if the factory is null
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)
ForkJoinPool
with the given parallelism and
thread factory.
parallelism
- the parallelism levelfactory
- the factory for creating new threads
IllegalArgumentException
- if parallelism less than or
equal to zero, or greater than implementation limit
NullPointerException
- if the factory is null
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)
task
- the task
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic void execute(ForkJoinTask<?> task)
task
- the task
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic void execute(Runnable task)
Executor
task
- the runnable task
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(Callable<T> task)
ExecutorService
If you would like to immediately block waiting for a task, you can use constructions of the form result = exec.submit(aCallable).get();
Note: The Executors
class includes a set of methods
that can convert some other common closure-like objects,
for example, PrivilegedAction
to
Callable
form so they can be submitted.
submit
in interface ExecutorService
submit
in class AbstractExecutorService
task
- the task to submit
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(Runnable task, T result)
ExecutorService
submit
in interface ExecutorService
submit
in class AbstractExecutorService
task
- the task to submitresult
- the result to return
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic ForkJoinTask<?> submit(Runnable task)
ExecutorService
submit
in interface ExecutorService
submit
in class AbstractExecutorService
task
- the task to submit
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)
task
- the task to submit
NullPointerException
- if the task is null
RejectedExecutionException
- if the task cannot be
scheduled for executionpublic <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
ExecutorService
Future.isDone()
is true for each
element of the returned list.
Note that a completed task could have
terminated either normally or by throwing an exception.
The results of this method are undefined if the given
collection is modified while this operation is in progress.
invokeAll
in interface ExecutorService
invokeAll
in class AbstractExecutorService
tasks
- the collection of tasks
NullPointerException
- if tasks or any of its elements are null
RejectedExecutionException
- if any task cannot be
scheduled for executionpublic ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
null
if nonepublic Thread.UncaughtExceptionHandler setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
h
- the new handler
null
if none
SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public void setParallelism(int parallelism)
parallelism
- the target parallelism
IllegalArgumentException
- if parallelism less than or
equal to zero or greater than maximum size bounds
SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public int getParallelism()
public int getPoolSize()
getParallelism()
when threads are created to
maintain parallelism when others are cooperatively blocked.
public int getMaximumPoolSize()
setMaximumPoolSize(int)
, the
maximum is an implementation-defined value designed only to
prevent runaway growth.
public void setMaximumPoolSize(int newMax)
parallelism
level. Setting this
value has no effect on current pool size. It controls
construction of new threads.
IllegalArgumentException
- if negative or greater than
internal implementation limitpublic boolean getMaintainsParallelism()
true
if this pool dynamically maintains its
target parallelism level. If false, new threads are added only
to avoid possible starvation. This setting is by default true.
true
if maintains parallelismpublic void setMaintainsParallelism(boolean enable)
enable
- true
to maintain parallelismpublic boolean setAsyncMode(boolean async)
async
- if true
, use locally FIFO scheduling
getAsyncMode()
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 modesetAsyncMode(boolean)
public 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(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 String toString()
toString
in class Object
public void shutdown()
SecurityException
- if a security manager exists and
the caller is not permitted to modify threads
because it does not hold RuntimePermission
("modifyThread")
public List<Runnable> shutdownNow()
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, causing this executor not
to properly terminate.
true
if terminating but not yet terminatedpublic boolean isShutdown()
true
if this pool has been shut down.
true
if this pool has been shut downpublic boolean awaitTermination(long timeout, TimeUnit unit) throws 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
InterruptedException
- if interrupted while waitingpublic static void managedBlock(ForkJoinPool.ManagedBlocker blocker, boolean maintainParallelism) throws InterruptedException
ForkJoinWorkerThread
, this method possibly
arranges for a spare thread to be activated if necessary to
ensure parallelism while the current thread is blocked.
If maintainParallelism
is true
and the pool
supports it (getMaintainsParallelism()
), this method
attempts to maintain the pool's nominal parallelism. Otherwise
it activates a thread only if necessary to avoid complete
starvation. This option may be preferable when blockages use
timeouts, or are almost always brief.
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 blockermaintainParallelism
- if true
and supported by
this pool, attempt to maintain the pool's nominal parallelism;
otherwise activate a thread only if necessary to avoid
complete starvation.
InterruptedException
- if blocker.block did soprotected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value)
AbstractExecutorService
newTaskFor
in class AbstractExecutorService
runnable
- the runnable task being wrappedvalue
- the default value for the returned future
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable)
AbstractExecutorService
newTaskFor
in class AbstractExecutorService
callable
- the callable task being wrapped
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |