that executes each submitted task using
one of possibly several pooled threads, normally configured
using
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#newCachedThreadPool (unbounded thread pool, with
automatic thread reclamation), Executors#newFixedThreadPool
(fixed size thread pool) and Executors#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:
| Constructor: |
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default thread factory and rejected execution handler.
It may be more convenient to use one of the Executors factory
methods instead of this general purpose constructor. 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
|
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default rejected execution handler. 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
|
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters and default thread factory. 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
|
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize < = 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
Creates a new {@code ThreadPoolExecutor} with the given initial
parameters. 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
|
| Method from java.util.concurrent.ThreadPoolExecutor Detail: |
protected void afterExecute(Runnable r,
Throwable t) {
}
Method invoked upon completion of execution of the given Runnable.
This method is invoked by the thread that executed the task. If
non-null, the Throwable is the uncaught {@code RuntimeException}
or {@code Error} that caused execution to terminate abruptly.
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);
}
}} |
public void allowCoreThreadTimeOut(boolean value) {
if (value && keepAliveTime < = 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
allowCoreThreadTimeOut = value;
if (value)
interruptIdleWorkers();
}
}
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. When false, core
threads are never terminated due to lack of incoming
tasks. When true, the same keep-alive policy applying to
non-core threads applies also to core threads. To avoid
continual thread replacement, the keep-alive time must be
greater than zero when setting {@code true}. This method
should in general be called before the pool is actively used. |
public boolean allowsCoreThreadTimeOut() {
return allowCoreThreadTimeOut;
}
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. When true, the same
keep-alive policy applying to non-core threads applies also to
core threads. When false (the default), core threads are never
terminated due to lack of incoming tasks. |
public boolean awaitTermination(long timeout,
TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
if (nanos < = 0)
return false;
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}
|
protected void beforeExecute(Thread t,
Runnable r) {
}
Method invoked prior to executing the given Runnable in the
given thread. This method is invoked by thread {@code t} that
will execute task {@code r}, and may be used to re-initialize
ThreadLocals, or to perform logging.
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. |
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
Executes the given task sometime in the future. The task
may execute in a new thread or in an existing pooled thread.
If the task cannot be submitted for execution, either because this
executor has been shutdown or because its capacity has been reached,
the task is handled by the current {@code RejectedExecutionHandler}. |
protected void finalize() {
shutdown();
}
Invokes {@code shutdown} when this executor is no longer
referenced and it has no threads. |
public int getActiveCount() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
int n = 0;
for (Worker w : workers)
if (w.isLocked())
++n;
return n;
} finally {
mainLock.unlock();
}
}
Returns the approximate number of threads that are actively
executing tasks. |
public long getCompletedTaskCount() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
long n = completedTaskCount;
for (Worker w : workers)
n += w.completedTasks;
return n;
} finally {
mainLock.unlock();
}
}
Returns the approximate total number of tasks that have
completed execution. Because the states of tasks and threads
may change dynamically during computation, the returned value
is only an approximation, but one that does not ever decrease
across successive calls. |
public int getCorePoolSize() {
return corePoolSize;
}
Returns the core number of threads. |
public long getKeepAliveTime(TimeUnit unit) {
return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
}
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. |
public int getLargestPoolSize() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
return largestPoolSize;
} finally {
mainLock.unlock();
}
}
Returns the largest number of threads that have ever
simultaneously been in the pool. |
public int getMaximumPoolSize() {
return maximumPoolSize;
}
Returns the maximum allowed number of threads. |
public int getPoolSize() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Remove rare and surprising possibility of
// isTerminated() && getPoolSize() > 0
return runStateAtLeast(ctl.get(), TIDYING) ? 0
: workers.size();
} finally {
mainLock.unlock();
}
}
Returns the current number of threads in the pool. |
public BlockingQueue<Runnable> getQueue() {
return workQueue;
}
Returns the task queue used by this executor. Access to the
task queue is intended primarily for debugging and monitoring.
This queue may be in active use. Retrieving the task queue
does not prevent queued tasks from executing. |
public RejectedExecutionHandler getRejectedExecutionHandler() {
return handler;
}
Returns the current handler for unexecutable tasks. |
public long getTaskCount() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
long n = completedTaskCount;
for (Worker w : workers) {
n += w.completedTasks;
if (w.isLocked())
++n;
}
return n + workQueue.size();
} finally {
mainLock.unlock();
}
}
Returns the approximate total number of tasks that have ever been
scheduled for execution. Because the states of tasks and
threads may change dynamically during computation, the returned
value is only an approximation. |
public ThreadFactory getThreadFactory() {
return threadFactory;
}
Returns the thread factory used to create new threads. |
final boolean isRunningOrShutdown(boolean shutdownOK) {
int rs = runStateOf(ctl.get());
return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
}
State check needed by ScheduledThreadPoolExecutor to
enable running tasks during shutdown. |
public boolean isShutdown() {
return ! isRunning(ctl.get());
}
|
public boolean isTerminated() {
return runStateAtLeast(ctl.get(), TERMINATED);
}
|
public boolean isTerminating() {
int c = ctl.get();
return ! isRunning(c) && runStateLessThan(c, TERMINATED);
}
Returns true if this executor is in the process of terminating
after #shutdown or #shutdownNow but has not
completely terminated. This method may be useful for
debugging. A return of {@code true} reported a sufficient
period after shutdown may indicate that submitted tasks have
ignored or suppressed interruption, causing this executor not
to properly terminate. |
void onShutdown() {
}
Performs any further cleanup following run state transition on
invocation of shutdown. A no-op here, but used by
ScheduledThreadPoolExecutor to cancel delayed tasks. |
public int prestartAllCoreThreads() {
int n = 0;
while (addWorker(null, true))
++n;
return n;
}
Starts all core threads, causing them to idly wait for work. This
overrides the default policy of starting core threads only when
new tasks are executed. |
public boolean prestartCoreThread() {
return workerCountOf(ctl.get()) < corePoolSize &&
addWorker(null, true);
}
Starts a core thread, causing it to idly wait for work. This
overrides the default policy of starting core threads only when
new tasks are executed. This method will return {@code false}
if all core threads have already been started. |
public void purge() {
final BlockingQueue< Runnable > q = workQueue;
try {
Iterator< Runnable > it = q.iterator();
while (it.hasNext()) {
Runnable r = it.next();
if (r instanceof Future< ? > && ((Future< ? >)r).isCancelled())
it.remove();
}
} catch (ConcurrentModificationException fallThrough) {
// Take slow path if we encounter interference during traversal.
// Make copy for traversal and call remove for cancelled entries.
// The slow path is more likely to be O(N*N).
for (Object r : q.toArray())
if (r instanceof Future< ? > && ((Future< ? >)r).isCancelled())
q.remove(r);
}
tryTerminate(); // In case SHUTDOWN and now empty
}
Tries to remove from the work queue all Future
tasks that have been cancelled. This method can be useful as a
storage reclamation operation, that has no other impact on
functionality. Cancelled tasks are never executed, but may
accumulate in work queues until worker threads can actively
remove them. Invoking this method instead tries to remove them now.
However, this method may fail to remove tasks in
the presence of interference by other threads. |
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}
Invokes the rejected execution handler for the given command.
Package-protected for use by ScheduledThreadPoolExecutor. |
public boolean remove(Runnable task) {
boolean removed = workQueue.remove(task);
tryTerminate(); // In case SHUTDOWN and now empty
return removed;
}
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.
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 #purge may be used to
remove those Futures that have been cancelled. |
final void runWorker(Worker w) {
Runnable task = w.firstTask;
w.firstTask = null;
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
clearInterruptsForTaskRun();
try {
beforeExecute(w.thread, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
Main worker run loop. Repeatedly gets tasks from queue and
executes them, while coping with a number of issues:
1. We may start out with an initial task, in which case we
don't need to get the first one. Otherwise, as long as pool is
running, we get tasks from getTask. If it returns null then the
worker exits due to changed pool state or configuration
parameters. Other exits result from exception throws in
external code, in which case completedAbruptly holds, which
usually leads processWorkerExit to replace this thread.
2. Before running any task, the lock is acquired to prevent
other pool interrupts while the task is executing, and
clearInterruptsForTaskRun called to ensure that unless pool is
stopping, this thread does not have its interrupt set.
3. Each task run is preceded by a call to beforeExecute, which
might throw an exception, in which case we cause thread to die
(breaking loop with completedAbruptly true) without processing
the task.
4. Assuming beforeExecute completes normally, we run the task,
gathering any of its thrown exceptions to send to
afterExecute. We separately handle RuntimeException, Error
(both of which the specs guarantee that we trap) and arbitrary
Throwables. Because we cannot rethrow Throwables within
Runnable.run, we wrap them within Errors on the way out (to the
thread's UncaughtExceptionHandler). Any thrown exception also
conservatively causes thread to die.
5. After task.run completes, we call afterExecute, which may
also throw an exception, which will also cause thread to
die. According to JLS Sec 14.20, this exception is the one that
will be in effect even if task.run throws.
The net effect of the exception mechanics is that afterExecute
and the thread's UncaughtExceptionHandler have as accurate
information as we can provide about any problems encountered by
user code. |
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
int delta = corePoolSize - this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get()) > corePoolSize)
interruptIdleWorkers();
else if (delta > 0) {
// We don't really know how many new threads are "needed".
// As a heuristic, prestart enough new workers (up to new
// core size) to handle the current number of tasks in
// queue, but stop if queue becomes empty while doing so.
int k = Math.min(delta, workQueue.size());
while (k-- > 0 && addWorker(null, true)) {
if (workQueue.isEmpty())
break;
}
}
}
Sets the core number of threads. This overrides any value set
in the constructor. If the new value is smaller than the
current value, excess existing threads will be terminated when
they next become idle. If larger, new threads will, if needed,
be started to execute any queued tasks. |
public void setKeepAliveTime(long time,
TimeUnit unit) {
if (time < 0)
throw new IllegalArgumentException();
if (time == 0 && allowsCoreThreadTimeOut())
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
long keepAliveTime = unit.toNanos(time);
long delta = keepAliveTime - this.keepAliveTime;
this.keepAliveTime = keepAliveTime;
if (delta < 0)
interruptIdleWorkers();
}
Sets the time limit for which threads may remain idle before
being terminated. If there are more than the core number of
threads currently in the pool, after waiting this amount of
time without processing a task, excess threads will be
terminated. This overrides any value set in the constructor. |
public void setMaximumPoolSize(int maximumPoolSize) {
if (maximumPoolSize < = 0 || maximumPoolSize < corePoolSize)
throw new IllegalArgumentException();
this.maximumPoolSize = maximumPoolSize;
if (workerCountOf(ctl.get()) > maximumPoolSize)
interruptIdleWorkers();
}
Sets the maximum allowed number of threads. This overrides any
value set in the constructor. If the new value is smaller than
the current value, excess existing threads will be
terminated when they next become idle. |
public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
if (handler == null)
throw new NullPointerException();
this.handler = handler;
}
Sets a new handler for unexecutable tasks. |
public void setThreadFactory(ThreadFactory threadFactory) {
if (threadFactory == null)
throw new NullPointerException();
this.threadFactory = threadFactory;
}
Sets the thread factory used to create new threads. |
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN);
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
tryTerminate();
}
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.
This method does not wait for previously submitted tasks to
complete execution. Use awaitTermination
to do that. |
public List<Runnable> shutdownNow() {
List< Runnable > tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(STOP);
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
}
tryTerminate();
return tasks;
}
Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks
that were awaiting execution. These tasks are drained (removed)
from the task queue upon return from this method.
This method does not wait for actively executing tasks to
terminate. Use awaitTermination to
do that.
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. |
protected void terminated() {
}
Method invoked when the Executor has terminated. Default
implementation does nothing. Note: To properly nest multiple
overridings, subclasses should generally invoke
{@code super.terminated} within this method. |
public String toString() {
long ncompleted;
int nworkers, nactive;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
ncompleted = completedTaskCount;
nactive = 0;
nworkers = workers.size();
for (Worker w : workers) {
ncompleted += w.completedTasks;
if (w.isLocked())
++nactive;
}
} finally {
mainLock.unlock();
}
int c = ctl.get();
String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
(runStateAtLeast(c, TERMINATED) ? "Terminated" :
"Shutting down"));
return super.toString() +
"[" + rs +
", pool size = " + nworkers +
", active threads = " + nactive +
", queued tasks = " + workQueue.size() +
", completed tasks = " + ncompleted +
"]";
}
Returns a string identifying this pool, as well as its state,
including indications of run state and estimated worker and
task counts. |
final void tryTerminate() {
for (;;) {
int c = ctl.get();
if (isRunning(c) ||
runStateAtLeast(c, TIDYING) ||
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
return;
if (workerCountOf(c) != 0) { // Eligible to terminate
interruptIdleWorkers(ONLY_ONE);
return;
}
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
try {
terminated();
} finally {
ctl.set(ctlOf(TERMINATED, 0));
termination.signalAll();
}
return;
}
} finally {
mainLock.unlock();
}
// else retry on failed CAS
}
}
Transitions to TERMINATED state if either (SHUTDOWN and pool
and queue empty) or (STOP and pool empty). If otherwise
eligible to terminate but workerCount is nonzero, interrupts an
idle worker to ensure that shutdown signals propagate. This
method must be called following any action that might make
termination possible -- reducing worker count or removing tasks
from the queue during shutdown. The method is non-private to
allow access from ScheduledThreadPoolExecutor. |