edu.emory.mathcs.backport.java.util.concurrent
public class ThreadPoolExecutor extends AbstractExecutorService
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each {@code ThreadPoolExecutor} also maintains some basic statistics, such as the number of completed tasks.
To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors (unbounded thread pool, with automatic thread reclamation), Executors (fixed size thread pool) and Executors (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:
If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
Extension example. Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature:
{@code class PausableThreadPoolExecutor extends ThreadPoolExecutor { private boolean isPaused; private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); public PausableThreadPoolExecutor(...) { super(...); } protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); pauseLock.lock(); try { while (isPaused) unpaused.await(); } catch (InterruptedException ie) { t.interrupt(); } finally { pauseLock.unlock(); } } public void pause() { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } } public void resume() { pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } }}
Since: 1.5
Nested Class Summary | |
---|---|
static class | ThreadPoolExecutor.AbortPolicy
A handler for rejected tasks that throws a
{@code RejectedExecutionException}. |
static class | ThreadPoolExecutor.CallerRunsPolicy
A handler for rejected tasks that runs the rejected task
directly in the calling thread of the {@code execute} method,
unless the executor has been shut down, in which case the task
is discarded. |
static class | ThreadPoolExecutor.DiscardOldestPolicy
A handler for rejected tasks that discards the oldest unhandled
request and then retries {@code execute}, unless the executor
is shut down, in which case the task is discarded. |
static class | ThreadPoolExecutor.DiscardPolicy
A handler for rejected tasks that silently discards the
rejected task. |
Constructor Summary | |
---|---|
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue)
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default thread factory and rejected execution handler.
| |
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory)
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default rejected execution handler.
| |
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler)
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default thread factory.
| |
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters.
|
Method Summary | |
---|---|
protected void | afterExecute(Runnable r, Throwable t)
Method invoked upon completion of execution of the given Runnable.
|
void | allowCoreThreadTimeOut(boolean value)
Sets the policy governing whether core threads may time out and
terminate if no tasks arrive within the keep-alive time, being
replaced if needed when new tasks arrive. |
boolean | allowsCoreThreadTimeOut()
Returns true if this pool allows core threads to time out and
terminate if no tasks arrive within the keepAlive time, being
replaced if needed when new tasks arrive. |
boolean | awaitTermination(long timeout, TimeUnit unit) |
protected void | beforeExecute(Thread t, Runnable r)
Method invoked prior to executing the given Runnable in the
given thread. |
void | execute(Runnable command)
Executes the given task sometime in the future. |
protected void | finalize()
Invokes {@code shutdown} when this executor is no longer
referenced and it has no threads. |
int | getActiveCount()
Returns the approximate number of threads that are actively
executing tasks.
|
long | getCompletedTaskCount()
Returns the approximate total number of tasks that have
completed execution. |
int | getCorePoolSize()
Returns the core number of threads.
|
long | getKeepAliveTime(TimeUnit unit)
Returns the thread keep-alive time, which is the amount of time
that threads in excess of the core pool size may remain
idle before being terminated.
|
int | getLargestPoolSize()
Returns the largest number of threads that have ever
simultaneously been in the pool.
|
int | getMaximumPoolSize()
Returns the maximum allowed number of threads.
|
int | getPoolSize()
Returns the current number of threads in the pool.
|
BlockingQueue | getQueue()
Returns the task queue used by this executor. |
RejectedExecutionHandler | getRejectedExecutionHandler()
Returns the current handler for unexecutable tasks.
|
long | getTaskCount()
Returns the approximate total number of tasks that have ever been
scheduled for execution. |
ThreadFactory | getThreadFactory()
Returns the thread factory used to create new threads.
|
boolean | isShutdown() |
boolean | isTerminated() |
boolean | isTerminating()
Returns true if this executor is in the process of terminating
after ThreadPoolExecutor or ThreadPoolExecutor but has not
completely terminated. |
int | prestartAllCoreThreads()
Starts all core threads, causing them to idly wait for work. |
boolean | prestartCoreThread()
Starts a core thread, causing it to idly wait for work. |
void | purge()
Tries to remove from the work queue all Future
tasks that have been cancelled. |
boolean | remove(Runnable task)
Removes this task from the executor's internal queue if it is
present, thus causing it not to be run if it has not already
started.
|
void | setCorePoolSize(int corePoolSize)
Sets the core number of threads. |
void | setKeepAliveTime(long time, TimeUnit unit)
Sets the time limit for which threads may remain idle before
being terminated. |
void | setMaximumPoolSize(int maximumPoolSize)
Sets the maximum allowed number of threads. |
void | setRejectedExecutionHandler(RejectedExecutionHandler handler)
Sets a new handler for unexecutable tasks.
|
void | setThreadFactory(ThreadFactory threadFactory)
Sets the thread factory used to create new threads.
|
void | shutdown()
Initiates an orderly shutdown in which previously submitted
tasks are executed, but no new tasks will be accepted.
|
List | shutdownNow()
Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks
that were awaiting execution. |
protected void | terminated()
Method invoked when the Executor has terminated. |
Parameters: corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set maximumPoolSize the maximum number of threads to allow in the pool keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. unit the time unit for the {@code keepAliveTime} argument workQueue the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method.
Throws: IllegalArgumentException if one of the following holds:
{@code corePoolSize < 0}
{@code keepAliveTime < 0}
{@code maximumPoolSize <= 0}
{@code maximumPoolSize < corePoolSize} NullPointerException if {@code workQueue} is null
Parameters: corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set maximumPoolSize the maximum number of threads to allow in the pool keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. unit the time unit for the {@code keepAliveTime} argument workQueue the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method. threadFactory the factory to use when the executor creates a new thread
Throws: IllegalArgumentException if one of the following holds:
{@code corePoolSize < 0}
{@code keepAliveTime < 0}
{@code maximumPoolSize <= 0}
{@code maximumPoolSize < corePoolSize} NullPointerException if {@code workQueue}
or {@code threadFactory} is null
Parameters: corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set maximumPoolSize the maximum number of threads to allow in the pool keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. unit the time unit for the {@code keepAliveTime} argument workQueue the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method. handler the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws: IllegalArgumentException if one of the following holds:
{@code corePoolSize < 0}
{@code keepAliveTime < 0}
{@code maximumPoolSize <= 0}
{@code maximumPoolSize < corePoolSize} NullPointerException if {@code workQueue}
or {@code handler} is null
Parameters: corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set maximumPoolSize the maximum number of threads to allow in the pool keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. unit the time unit for the {@code keepAliveTime} argument workQueue the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method. threadFactory the factory to use when the executor creates a new thread handler the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws: IllegalArgumentException if one of the following holds:
{@code corePoolSize < 0}
{@code keepAliveTime < 0}
{@code maximumPoolSize <= 0}
{@code maximumPoolSize < corePoolSize} NullPointerException if {@code workQueue}
or {@code threadFactory} or {@code handler} is null
This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke {@code super.afterExecute} at the beginning of this method.
Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as {@code submit}, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:
{@code class ExtendedExecutor extends ThreadPoolExecutor { // ... protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t == null && r instanceof Future>) { try { Object result = ((Future>) r).get(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // ignore/reset } } if (t != null) System.out.println(t); } }}
Parameters: r the runnable that has completed t the exception that caused termination, or null if execution completed normally
Parameters: value {@code true} if should time out, else {@code false}
Throws: IllegalArgumentException if value is {@code true} and the current keep-alive time is not greater than zero
Since: 1.6
Returns: {@code true} if core threads are allowed to time out, else {@code false}
Since: 1.6
This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke {@code super.beforeExecute} at the end of this method.
Parameters: t the thread that will run task {@code r} r the task that will be executed
Parameters: command the task to execute
Throws: RejectedExecutionException at discretion of {@code RejectedExecutionHandler}, if the task cannot be accepted for execution NullPointerException if {@code command} is null
Returns: the number of threads
Returns: the number of tasks
Returns: the core number of threads
See Also: ThreadPoolExecutor
Parameters: unit the desired time unit of the result
Returns: the time limit
See Also: ThreadPoolExecutor
Returns: the number of threads
Returns: the maximum allowed number of threads
See Also: ThreadPoolExecutor
Returns: the number of threads
Returns: the task queue
Returns: the current handler
See Also: ThreadPoolExecutor
Returns: the number of tasks
Returns: the current thread factory
See Also: ThreadPoolExecutor
Returns: true if terminating but not yet terminated
Returns: the number of threads started
Returns: {@code true} if a thread was started
This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using {@code submit} might be converted into a form that maintains {@code Future} status. However, in such cases, method ThreadPoolExecutor may be used to remove those Futures that have been cancelled.
Parameters: task the task to remove
Returns: true if the task was removed
Parameters: corePoolSize the new core size
Throws: IllegalArgumentException if {@code corePoolSize < 0}
See Also: ThreadPoolExecutor
Parameters: time the time to wait. A time value of zero will cause excess threads to terminate immediately after executing tasks. unit the time unit of the {@code time} argument
Throws: IllegalArgumentException if {@code time} less than zero or if {@code time} is zero and {@code allowsCoreThreadTimeOut}
See Also: ThreadPoolExecutor
Parameters: maximumPoolSize the new maximum
Throws: IllegalArgumentException if the new maximum is less than or equal to zero, or less than the core pool size
See Also: ThreadPoolExecutor
Parameters: handler the new handler
Throws: NullPointerException if handler is null
See Also: ThreadPoolExecutor
Parameters: threadFactory the new thread factory
Throws: NullPointerException if threadFactory is null
See Also: ThreadPoolExecutor
Throws: SecurityException {@inheritDoc }
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread#interrupt, so any task that fails to respond to interrupts may never terminate.
Throws: SecurityException {@inheritDoc }