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 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 newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation), newFixedThreadPool(int) (fixed size thread pool) and newSingleThreadExecutor() (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:
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();
}
}
} | Nested Class Summary | |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
| Constructor Summary |
|---|
|
Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler. |
|
Creates a new ThreadPoolExecutor with the given initial parameters and default rejected execution handler. |
|
Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory. |
|
Creates a new ThreadPoolExecutor with the given initial parameters. |
| Method Summary | |
|---|---|
| protected void |
Method invoked upon completion of execution of the given Runnable. |
| void |
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 |
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 |
No description provided. |
| protected void |
Method invoked prior to executing the given Runnable in the given thread. |
| void |
Executes the given task sometime in the future. |
| protected void |
Invokes shutdown when this executor is no longer referenced and it has no threads. |
| int |
Returns the approximate number of threads that are actively executing tasks. |
| long |
Returns the approximate total number of tasks that have completed execution. |
| int |
Returns the core number of threads. |
| long |
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 |
Returns the largest number of threads that have ever simultaneously been in the pool. |
| int |
Returns the maximum allowed number of threads. |
| int |
Returns the current number of threads in the pool. |
| BlockingQueue<Runnable> |
Returns the task queue used by this executor. |
| RejectedExecutionHandler |
Returns the current handler for unexecutable tasks. |
| long |
Returns the approximate total number of tasks that have ever been scheduled for execution. |
| ThreadFactory |
Returns the thread factory used to create new threads. |
| boolean |
No description provided. |
| boolean |
No description provided. |
| boolean |
Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated. |
| int |
Starts all core threads, causing them to idly wait for work. |
| boolean |
Starts a core thread, causing it to idly wait for work. |
| void |
Tries to remove from the work queue all Future tasks that have been cancelled. |
| boolean |
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 |
Sets the core number of threads. |
| void |
Sets the time limit for which threads may remain idle before being terminated. |
| void |
Sets the maximum allowed number of threads. |
| void |
Sets a new handler for unexecutable tasks. |
| void |
Sets the thread factory used to create new threads. |
| void |
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. |
| List<Runnable> |
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 |
Method invoked when the Executor has terminated. |
| Methods inherited from java.util.concurrentExecutorService |
|---|
| Methods inherited from java.langObject |
|---|
public ThreadPoolExecutor
(
int
corePoolSize,
int
maximumPoolSize,
long
keepAliveTime,
TimeUnit
unit,
BlockingQueue<Runnable>
workQueue
)
public ThreadPoolExecutor
(
int
corePoolSize,
int
maximumPoolSize,
long
keepAliveTime,
TimeUnit
unit,
BlockingQueue<Runnable>
workQueue,
ThreadFactory
threadFactory
)
public ThreadPoolExecutor
(
int
corePoolSize,
int
maximumPoolSize,
long
keepAliveTime,
TimeUnit
unit,
BlockingQueue<Runnable>
workQueue,
RejectedExecutionHandler
handler
)
public ThreadPoolExecutor
(
int
corePoolSize,
int
maximumPoolSize,
long
keepAliveTime,
TimeUnit
unit,
BlockingQueue<Runnable>
workQueue,
ThreadFactory
threadFactory,
RejectedExecutionHandler
handler
)
This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke 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 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:
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);
}
}
public
void
allowCoreThreadTimeOut
(
boolean
value
)
public
boolean
allowsCoreThreadTimeOut
(
)
This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke super.beforeExecute at the end of this method.
protected
void
finalize
(
)
public
int
getActiveCount
(
)
public
long
getCompletedTaskCount
(
)
public
int
getCorePoolSize
(
)
public
int
getLargestPoolSize
(
)
public
int
getMaximumPoolSize
(
)
public
int
getPoolSize
(
)
public
long
getTaskCount
(
)
public
boolean
isShutdown
(
)
public
boolean
isTerminated
(
)
public
boolean
isTerminating
(
)
public
int
prestartAllCoreThreads
(
)
public
boolean
prestartCoreThread
(
)
public
void
purge
(
)
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 submit might be converted into a form that maintains Future status. However, in such cases, method purge() may be used to remove those Futures that have been cancelled.
public
void
setCorePoolSize
(
int
corePoolSize
)
public
void
setMaximumPoolSize
(
int
maximumPoolSize
)
public
void
shutdown
(
)
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via interrupt() , so any task that fails to respond to interrupts may never terminate.
protected
void
terminated
(
)