2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
7 package java
.util
.concurrent
;
9 import java
.util
.ArrayList
;
10 import java
.util
.ConcurrentModificationException
;
11 import java
.util
.HashSet
;
12 import java
.util
.Iterator
;
13 import java
.util
.List
;
14 import java
.util
.concurrent
.atomic
.AtomicInteger
;
15 import java
.util
.concurrent
.locks
.AbstractQueuedSynchronizer
;
16 import java
.util
.concurrent
.locks
.Condition
;
17 import java
.util
.concurrent
.locks
.ReentrantLock
;
20 // removed security manager docs
24 * An {@link ExecutorService} that executes each submitted task using
25 * one of possibly several pooled threads, normally configured
26 * using {@link Executors} factory methods.
28 * <p>Thread pools address two different problems: they usually
29 * provide improved performance when executing large numbers of
30 * asynchronous tasks, due to reduced per-task invocation overhead,
31 * and they provide a means of bounding and managing the resources,
32 * including threads, consumed when executing a collection of tasks.
33 * Each {@code ThreadPoolExecutor} also maintains some basic
34 * statistics, such as the number of completed tasks.
36 * <p>To be useful across a wide range of contexts, this class
37 * provides many adjustable parameters and extensibility
38 * hooks. However, programmers are urged to use the more convenient
39 * {@link Executors} factory methods {@link
40 * Executors#newCachedThreadPool} (unbounded thread pool, with
41 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
42 * (fixed size thread pool) and {@link
43 * Executors#newSingleThreadExecutor} (single background thread), that
44 * preconfigure settings for the most common usage
45 * scenarios. Otherwise, use the following guide when manually
46 * configuring and tuning this class:
50 * <dt>Core and maximum pool sizes</dt>
52 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
53 * A {@code ThreadPoolExecutor} will automatically adjust the
54 * pool size (see {@link #getPoolSize})
55 * according to the bounds set by
56 * corePoolSize (see {@link #getCorePoolSize}) and
57 * maximumPoolSize (see {@link #getMaximumPoolSize}).
59 * When a new task is submitted in method {@link #execute(Runnable)},
60 * and fewer than corePoolSize threads are running, a new thread is
61 * created to handle the request, even if other worker threads are
62 * idle. If there are more than corePoolSize but less than
63 * maximumPoolSize threads running, a new thread will be created only
64 * if the queue is full. By setting corePoolSize and maximumPoolSize
65 * the same, you create a fixed-size thread pool. By setting
66 * maximumPoolSize to an essentially unbounded value such as {@code
67 * Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
68 * number of concurrent tasks. Most typically, core and maximum pool
69 * sizes are set only upon construction, but they may also be changed
70 * dynamically using {@link #setCorePoolSize} and {@link
71 * #setMaximumPoolSize}. </dd>
73 * <dt>On-demand construction</dt>
75 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
76 * By default, even core threads are initially created and
77 * started only when new tasks arrive, but this can be overridden
78 * dynamically using method {@link #prestartCoreThread} or {@link
79 * #prestartAllCoreThreads}. You probably want to prestart threads if
80 * you construct the pool with a non-empty queue. </dd>
82 * <dt>Creating new threads</dt>
84 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
85 * New threads are created using a {@link ThreadFactory}. If not
86 * otherwise specified, a {@link Executors#defaultThreadFactory} is
87 * used, that creates threads to all be in the same {@link
88 * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
89 * non-daemon status. By supplying a different ThreadFactory, you can
90 * alter the thread's name, thread group, priority, daemon status,
91 * etc. If a {@code ThreadFactory} fails to create a thread when asked
92 * by returning null from {@code newThread}, the executor will
93 * continue, but might not be able to execute any tasks. Threads
94 * should possess the "modifyThread" {@code RuntimePermission}. If
95 * worker threads or other threads using the pool do not possess this
96 * permission, service may be degraded: configuration changes may not
97 * take effect in a timely manner, and a shutdown pool may remain in a
98 * state in which termination is possible but not completed.</dd>
100 * <dt>Keep-alive times</dt>
102 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
103 * If the pool currently has more than corePoolSize threads,
104 * excess threads will be terminated if they have been idle for more
105 * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
106 * This provides a means of reducing resource consumption when the
107 * pool is not being actively used. If the pool becomes more active
108 * later, new threads will be constructed. This parameter can also be
109 * changed dynamically using method {@link #setKeepAliveTime(long,
110 * TimeUnit)}. Using a value of {@code Long.MAX_VALUE} {@link
111 * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
112 * terminating prior to shut down. By default, the keep-alive policy
113 * applies only when there are more than corePoolSize threads, but
114 * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
115 * apply this time-out policy to core threads as well, so long as the
116 * keepAliveTime value is non-zero. </dd>
120 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
121 * Any {@link BlockingQueue} may be used to transfer and hold
122 * submitted tasks. The use of this queue interacts with pool sizing:
126 * <li>If fewer than corePoolSize threads are running, the Executor
127 * always prefers adding a new thread
128 * rather than queuing.
130 * <li>If corePoolSize or more threads are running, the Executor
131 * always prefers queuing a request rather than adding a new
134 * <li>If a request cannot be queued, a new thread is created unless
135 * this would exceed maximumPoolSize, in which case, the task will be
140 * There are three general strategies for queuing:
143 * <li><em> Direct handoffs.</em> A good default choice for a work
144 * queue is a {@link SynchronousQueue} that hands off tasks to threads
145 * without otherwise holding them. Here, an attempt to queue a task
146 * will fail if no threads are immediately available to run it, so a
147 * new thread will be constructed. This policy avoids lockups when
148 * handling sets of requests that might have internal dependencies.
149 * Direct handoffs generally require unbounded maximumPoolSizes to
150 * avoid rejection of new submitted tasks. This in turn admits the
151 * possibility of unbounded thread growth when commands continue to
152 * arrive on average faster than they can be processed.
154 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
155 * example a {@link LinkedBlockingQueue} without a predefined
156 * capacity) will cause new tasks to wait in the queue when all
157 * corePoolSize threads are busy. Thus, no more than corePoolSize
158 * threads will ever be created. (And the value of the maximumPoolSize
159 * therefore doesn't have any effect.) This may be appropriate when
160 * each task is completely independent of others, so tasks cannot
161 * affect each others execution; for example, in a web page server.
162 * While this style of queuing can be useful in smoothing out
163 * transient bursts of requests, it admits the possibility of
164 * unbounded work queue growth when commands continue to arrive on
165 * average faster than they can be processed.
167 * <li><em>Bounded queues.</em> A bounded queue (for example, an
168 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
169 * used with finite maximumPoolSizes, but can be more difficult to
170 * tune and control. Queue sizes and maximum pool sizes may be traded
171 * off for each other: Using large queues and small pools minimizes
172 * CPU usage, OS resources, and context-switching overhead, but can
173 * lead to artificially low throughput. If tasks frequently block (for
174 * example if they are I/O bound), a system may be able to schedule
175 * time for more threads than you otherwise allow. Use of small queues
176 * generally requires larger pool sizes, which keeps CPUs busier but
177 * may encounter unacceptable scheduling overhead, which also
178 * decreases throughput.
184 * <dt>Rejected tasks</dt>
186 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
187 * New tasks submitted in method {@link #execute(Runnable)} will be
188 * <em>rejected</em> when the Executor has been shut down, and also when
189 * the Executor uses finite bounds for both maximum threads and work queue
190 * capacity, and is saturated. In either case, the {@code execute} method
192 * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
193 * method of its {@link RejectedExecutionHandler}. Four predefined handler
194 * policies are provided:
198 * <li>In the default {@link ThreadPoolExecutor.AbortPolicy}, the
199 * handler throws a runtime {@link RejectedExecutionException} upon
202 * <li>In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
203 * that invokes {@code execute} itself runs the task. This provides a
204 * simple feedback control mechanism that will slow down the rate that
205 * new tasks are submitted.
207 * <li>In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
208 * cannot be executed is simply dropped.
210 * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
211 * executor is not shut down, the task at the head of the work queue
212 * is dropped, and then execution is retried (which can fail again,
213 * causing this to be repeated.)
217 * It is possible to define and use other kinds of {@link
218 * RejectedExecutionHandler} classes. Doing so requires some care
219 * especially when policies are designed to work only under particular
220 * capacity or queuing policies. </dd>
222 * <dt>Hook methods</dt>
224 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
225 * This class provides {@code protected} overridable
226 * {@link #beforeExecute(Thread, Runnable)} and
227 * {@link #afterExecute(Runnable, Throwable)} methods that are called
228 * before and after execution of each task. These can be used to
229 * manipulate the execution environment; for example, reinitializing
230 * ThreadLocals, gathering statistics, or adding log entries.
231 * Additionally, method {@link #terminated} can be overridden to perform
232 * any special processing that needs to be done once the Executor has
235 * <p>If hook, callback, or BlockingQueue methods throw exceptions,
236 * internal worker threads may in turn fail, abruptly terminate, and
237 * possibly be replaced.</dd>
239 * <dt>Queue maintenance</dt>
241 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
242 * Method {@link #getQueue()} allows access to the work queue
243 * for purposes of monitoring and debugging. Use of this method for
244 * any other purpose is strongly discouraged. Two supplied methods,
245 * {@link #remove(Runnable)} and {@link #purge} are available to
246 * assist in storage reclamation when large numbers of queued tasks
247 * become cancelled.</dd>
249 * <dt>Finalization</dt>
251 * <dd style="font-family:'DejaVu Sans', Arial, Helvetica, sans-serif">
252 * A pool that is no longer referenced in a program <em>AND</em>
253 * has no remaining threads will be {@code shutdown} automatically. If
254 * you would like to ensure that unreferenced pools are reclaimed even
255 * if users forget to call {@link #shutdown}, then you must arrange
256 * that unused threads eventually die, by setting appropriate
257 * keep-alive times, using a lower bound of zero core threads and/or
258 * setting {@link #allowCoreThreadTimeOut(boolean)}. </dd>
262 * <p><b>Extension example</b>. Most extensions of this class
263 * override one or more of the protected hook methods. For example,
264 * here is a subclass that adds a simple pause/resume feature:
267 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
268 * private boolean isPaused;
269 * private ReentrantLock pauseLock = new ReentrantLock();
270 * private Condition unpaused = pauseLock.newCondition();
272 * public PausableThreadPoolExecutor(...) { super(...); }
274 * protected void beforeExecute(Thread t, Runnable r) {
275 * super.beforeExecute(t, r);
278 * while (isPaused) unpaused.await();
279 * } catch (InterruptedException ie) {
282 * pauseLock.unlock();
286 * public void pause() {
291 * pauseLock.unlock();
295 * public void resume() {
299 * unpaused.signalAll();
301 * pauseLock.unlock();
309 public class ThreadPoolExecutor
extends AbstractExecutorService
{
311 * The main pool control state, ctl, is an atomic integer packing
312 * two conceptual fields
313 * workerCount, indicating the effective number of threads
314 * runState, indicating whether running, shutting down etc
316 * In order to pack them into one int, we limit workerCount to
317 * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
318 * billion) otherwise representable. If this is ever an issue in
319 * the future, the variable can be changed to be an AtomicLong,
320 * and the shift/mask constants below adjusted. But until the need
321 * arises, this code is a bit faster and simpler using an int.
323 * The workerCount is the number of workers that have been
324 * permitted to start and not permitted to stop. The value may be
325 * transiently different from the actual number of live threads,
326 * for example when a ThreadFactory fails to create a thread when
327 * asked, and when exiting threads are still performing
328 * bookkeeping before terminating. The user-visible pool size is
329 * reported as the current size of the workers set.
331 * The runState provides the main lifecycle control, taking on values:
333 * RUNNING: Accept new tasks and process queued tasks
334 * SHUTDOWN: Don't accept new tasks, but process queued tasks
335 * STOP: Don't accept new tasks, don't process queued tasks,
336 * and interrupt in-progress tasks
337 * TIDYING: All tasks have terminated, workerCount is zero,
338 * the thread transitioning to state TIDYING
339 * will run the terminated() hook method
340 * TERMINATED: terminated() has completed
342 * The numerical order among these values matters, to allow
343 * ordered comparisons. The runState monotonically increases over
344 * time, but need not hit each state. The transitions are:
346 * RUNNING -> SHUTDOWN
347 * On invocation of shutdown(), perhaps implicitly in finalize()
348 * (RUNNING or SHUTDOWN) -> STOP
349 * On invocation of shutdownNow()
350 * SHUTDOWN -> TIDYING
351 * When both queue and pool are empty
354 * TIDYING -> TERMINATED
355 * When the terminated() hook method has completed
357 * Threads waiting in awaitTermination() will return when the
358 * state reaches TERMINATED.
360 * Detecting the transition from SHUTDOWN to TIDYING is less
361 * straightforward than you'd like because the queue may become
362 * empty after non-empty and vice versa during SHUTDOWN state, but
363 * we can only terminate if, after seeing that it is empty, we see
364 * that workerCount is 0 (which sometimes entails a recheck -- see
367 private final AtomicInteger ctl
= new AtomicInteger(ctlOf(RUNNING
, 0));
368 private static final int COUNT_BITS
= Integer
.SIZE
- 3;
369 private static final int CAPACITY
= (1 << COUNT_BITS
) - 1;
371 // runState is stored in the high-order bits
372 private static final int RUNNING
= -1 << COUNT_BITS
;
373 private static final int SHUTDOWN
= 0 << COUNT_BITS
;
374 private static final int STOP
= 1 << COUNT_BITS
;
375 private static final int TIDYING
= 2 << COUNT_BITS
;
376 private static final int TERMINATED
= 3 << COUNT_BITS
;
378 // Packing and unpacking ctl
379 private static int runStateOf(int c
) { return c
& ~CAPACITY
; }
380 private static int workerCountOf(int c
) { return c
& CAPACITY
; }
381 private static int ctlOf(int rs
, int wc
) { return rs
| wc
; }
384 * Bit field accessors that don't require unpacking ctl.
385 * These depend on the bit layout and on workerCount being never negative.
388 private static boolean runStateLessThan(int c
, int s
) {
392 private static boolean runStateAtLeast(int c
, int s
) {
396 private static boolean isRunning(int c
) {
401 * Attempts to CAS-increment the workerCount field of ctl.
403 private boolean compareAndIncrementWorkerCount(int expect
) {
404 return ctl
.compareAndSet(expect
, expect
+ 1);
408 * Attempts to CAS-decrement the workerCount field of ctl.
410 private boolean compareAndDecrementWorkerCount(int expect
) {
411 return ctl
.compareAndSet(expect
, expect
- 1);
415 * Decrements the workerCount field of ctl. This is called only on
416 * abrupt termination of a thread (see processWorkerExit). Other
417 * decrements are performed within getTask.
419 private void decrementWorkerCount() {
420 do {} while (! compareAndDecrementWorkerCount(ctl
.get()));
424 * The queue used for holding tasks and handing off to worker
425 * threads. We do not require that workQueue.poll() returning
426 * null necessarily means that workQueue.isEmpty(), so rely
427 * solely on isEmpty to see if the queue is empty (which we must
428 * do for example when deciding whether to transition from
429 * SHUTDOWN to TIDYING). This accommodates special-purpose
430 * queues such as DelayQueues for which poll() is allowed to
431 * return null even if it may later return non-null when delays
434 private final BlockingQueue
<Runnable
> workQueue
;
437 * Lock held on access to workers set and related bookkeeping.
438 * While we could use a concurrent set of some sort, it turns out
439 * to be generally preferable to use a lock. Among the reasons is
440 * that this serializes interruptIdleWorkers, which avoids
441 * unnecessary interrupt storms, especially during shutdown.
442 * Otherwise exiting threads would concurrently interrupt those
443 * that have not yet interrupted. It also simplifies some of the
444 * associated statistics bookkeeping of largestPoolSize etc. We
445 * also hold mainLock on shutdown and shutdownNow, for the sake of
446 * ensuring workers set is stable while separately checking
447 * permission to interrupt and actually interrupting.
449 private final ReentrantLock mainLock
= new ReentrantLock();
452 * Set containing all worker threads in pool. Accessed only when
455 private final HashSet
<Worker
> workers
= new HashSet
<>();
458 * Wait condition to support awaitTermination.
460 private final Condition termination
= mainLock
.newCondition();
463 * Tracks largest attained pool size. Accessed only under
466 private int largestPoolSize
;
469 * Counter for completed tasks. Updated only on termination of
470 * worker threads. Accessed only under mainLock.
472 private long completedTaskCount
;
475 * All user control parameters are declared as volatiles so that
476 * ongoing actions are based on freshest values, but without need
477 * for locking, since no internal invariants depend on them
478 * changing synchronously with respect to other actions.
482 * Factory for new threads. All threads are created using this
483 * factory (via method addWorker). All callers must be prepared
484 * for addWorker to fail, which may reflect a system or user's
485 * policy limiting the number of threads. Even though it is not
486 * treated as an error, failure to create threads may result in
487 * new tasks being rejected or existing ones remaining stuck in
490 * We go further and preserve pool invariants even in the face of
491 * errors such as OutOfMemoryError, that might be thrown while
492 * trying to create threads. Such errors are rather common due to
493 * the need to allocate a native stack in Thread.start, and users
494 * will want to perform clean pool shutdown to clean up. There
495 * will likely be enough memory available for the cleanup code to
496 * complete without encountering yet another OutOfMemoryError.
498 private volatile ThreadFactory threadFactory
;
501 * Handler called when saturated or shutdown in execute.
503 private volatile RejectedExecutionHandler handler
;
506 * Timeout in nanoseconds for idle threads waiting for work.
507 * Threads use this timeout when there are more than corePoolSize
508 * present or if allowCoreThreadTimeOut. Otherwise they wait
509 * forever for new work.
511 private volatile long keepAliveTime
;
514 * If false (default), core threads stay alive even when idle.
515 * If true, core threads use keepAliveTime to time out waiting
518 private volatile boolean allowCoreThreadTimeOut
;
521 * Core pool size is the minimum number of workers to keep alive
522 * (and not allow to time out etc) unless allowCoreThreadTimeOut
523 * is set, in which case the minimum is zero.
525 private volatile int corePoolSize
;
528 * Maximum pool size. Note that the actual maximum is internally
529 * bounded by CAPACITY.
531 private volatile int maximumPoolSize
;
534 * The default rejected execution handler.
536 private static final RejectedExecutionHandler defaultHandler
=
540 * Permission required for callers of shutdown and shutdownNow.
541 * We additionally require (see checkShutdownAccess) that callers
542 * have permission to actually interrupt threads in the worker set
543 * (as governed by Thread.interrupt, which relies on
544 * ThreadGroup.checkAccess, which in turn relies on
545 * SecurityManager.checkAccess). Shutdowns are attempted only if
548 * All actual invocations of Thread.interrupt (see
549 * interruptIdleWorkers and interruptWorkers) ignore
550 * SecurityExceptions, meaning that the attempted interrupts
551 * silently fail. In the case of shutdown, they should not fail
552 * unless the SecurityManager has inconsistent policies, sometimes
553 * allowing access to a thread and sometimes not. In such cases,
554 * failure to actually interrupt threads may disable or delay full
555 * termination. Other uses of interruptIdleWorkers are advisory,
556 * and failure to actually interrupt will merely delay response to
557 * configuration changes so is not handled exceptionally.
559 private static final RuntimePermission shutdownPerm
=
560 new RuntimePermission("modifyThread");
563 * Class Worker mainly maintains interrupt control state for
564 * threads running tasks, along with other minor bookkeeping.
565 * This class opportunistically extends AbstractQueuedSynchronizer
566 * to simplify acquiring and releasing a lock surrounding each
567 * task execution. This protects against interrupts that are
568 * intended to wake up a worker thread waiting for a task from
569 * instead interrupting a task being run. We implement a simple
570 * non-reentrant mutual exclusion lock rather than use
571 * ReentrantLock because we do not want worker tasks to be able to
572 * reacquire the lock when they invoke pool control methods like
573 * setCorePoolSize. Additionally, to suppress interrupts until
574 * the thread actually starts running tasks, we initialize lock
575 * state to a negative value, and clear it upon start (in
578 private final class Worker
579 extends AbstractQueuedSynchronizer
583 * This class will never be serialized, but we provide a
584 * serialVersionUID to suppress a javac warning.
586 private static final long serialVersionUID
= 6138294804551838833L;
588 /** Thread this worker is running in. Null if factory fails. */
590 /** Initial task to run. Possibly null. */
592 /** Per-thread task counter */
593 volatile long completedTasks
;
596 * Creates with given first task and thread from ThreadFactory.
597 * @param firstTask the first task (null if none)
599 Worker(Runnable firstTask
) {
600 setState(-1); // inhibit interrupts until runWorker
601 this.firstTask
= firstTask
;
602 this.thread
= getThreadFactory().newThread(this);
605 /** Delegates main run loop to outer runWorker. */
612 // The value 0 represents the unlocked state.
613 // The value 1 represents the locked state.
615 protected boolean isHeldExclusively() {
616 return getState() != 0;
619 protected boolean tryAcquire(int unused
) {
620 if (compareAndSetState(0, 1)) {
621 setExclusiveOwnerThread(Thread
.currentThread());
627 protected boolean tryRelease(int unused
) {
628 setExclusiveOwnerThread(null);
633 public void lock() { acquire(1); }
634 public boolean tryLock() { return tryAcquire(1); }
635 public void unlock() { release(1); }
636 public boolean isLocked() { return isHeldExclusively(); }
638 void interruptIfStarted() {
640 if (getState() >= 0 && (t
= thread
) != null && !t
.isInterrupted()) {
643 } catch (SecurityException ignore
) {
650 * Methods for setting control state
654 * Transitions runState to given target, or leaves it alone if
655 * already at least the given target.
657 * @param targetState the desired state, either SHUTDOWN or STOP
658 * (but not TIDYING or TERMINATED -- use tryTerminate for that)
660 private void advanceRunState(int targetState
) {
661 // assert targetState == SHUTDOWN || targetState == STOP;
664 if (runStateAtLeast(c
, targetState
) ||
665 ctl
.compareAndSet(c
, ctlOf(targetState
, workerCountOf(c
))))
671 * Transitions to TERMINATED state if either (SHUTDOWN and pool
672 * and queue empty) or (STOP and pool empty). If otherwise
673 * eligible to terminate but workerCount is nonzero, interrupts an
674 * idle worker to ensure that shutdown signals propagate. This
675 * method must be called following any action that might make
676 * termination possible -- reducing worker count or removing tasks
677 * from the queue during shutdown. The method is non-private to
678 * allow access from ScheduledThreadPoolExecutor.
680 final void tryTerminate() {
684 runStateAtLeast(c
, TIDYING
) ||
685 (runStateOf(c
) == SHUTDOWN
&& ! workQueue
.isEmpty()))
687 if (workerCountOf(c
) != 0) { // Eligible to terminate
688 interruptIdleWorkers(ONLY_ONE
);
692 final ReentrantLock mainLock
= this.mainLock
;
695 if (ctl
.compareAndSet(c
, ctlOf(TIDYING
, 0))) {
699 ctl
.set(ctlOf(TERMINATED
, 0));
700 termination
.signalAll();
707 // else retry on failed CAS
712 * Methods for controlling interrupts to worker threads.
716 * If there is a security manager, makes sure caller has
717 * permission to shut down threads in general (see shutdownPerm).
718 * If this passes, additionally makes sure the caller is allowed
719 * to interrupt each worker thread. This might not be true even if
720 * first check passed, if the SecurityManager treats some threads
723 private void checkShutdownAccess() {
724 SecurityManager security
= System
.getSecurityManager();
725 if (security
!= null) {
726 security
.checkPermission(shutdownPerm
);
727 final ReentrantLock mainLock
= this.mainLock
;
730 for (Worker w
: workers
)
731 security
.checkAccess(w
.thread
);
739 * Interrupts all threads, even if active. Ignores SecurityExceptions
740 * (in which case some threads may remain uninterrupted).
742 private void interruptWorkers() {
743 final ReentrantLock mainLock
= this.mainLock
;
746 for (Worker w
: workers
)
747 w
.interruptIfStarted();
754 * Interrupts threads that might be waiting for tasks (as
755 * indicated by not being locked) so they can check for
756 * termination or configuration changes. Ignores
757 * SecurityExceptions (in which case some threads may remain
760 * @param onlyOne If true, interrupt at most one worker. This is
761 * called only from tryTerminate when termination is otherwise
762 * enabled but there are still other workers. In this case, at
763 * most one waiting worker is interrupted to propagate shutdown
764 * signals in case all threads are currently waiting.
765 * Interrupting any arbitrary thread ensures that newly arriving
766 * workers since shutdown began will also eventually exit.
767 * To guarantee eventual termination, it suffices to always
768 * interrupt only one idle worker, but shutdown() interrupts all
769 * idle workers so that redundant workers exit promptly, not
770 * waiting for a straggler task to finish.
772 private void interruptIdleWorkers(boolean onlyOne
) {
773 final ReentrantLock mainLock
= this.mainLock
;
776 for (Worker w
: workers
) {
778 if (!t
.isInterrupted() && w
.tryLock()) {
781 } catch (SecurityException ignore
) {
795 * Common form of interruptIdleWorkers, to avoid having to
796 * remember what the boolean argument means.
798 private void interruptIdleWorkers() {
799 interruptIdleWorkers(false);
802 private static final boolean ONLY_ONE
= true;
805 * Misc utilities, most of which are also exported to
806 * ScheduledThreadPoolExecutor
810 * Invokes the rejected execution handler for the given command.
811 * Package-protected for use by ScheduledThreadPoolExecutor.
813 final void reject(Runnable command
) {
814 handler
.rejectedExecution(command
, this);
818 * Performs any further cleanup following run state transition on
819 * invocation of shutdown. A no-op here, but used by
820 * ScheduledThreadPoolExecutor to cancel delayed tasks.
826 * State check needed by ScheduledThreadPoolExecutor to
827 * enable running tasks during shutdown.
829 * @param shutdownOK true if should return true if SHUTDOWN
831 final boolean isRunningOrShutdown(boolean shutdownOK
) {
832 int rs
= runStateOf(ctl
.get());
833 return rs
== RUNNING
|| (rs
== SHUTDOWN
&& shutdownOK
);
837 * Drains the task queue into a new list, normally using
838 * drainTo. But if the queue is a DelayQueue or any other kind of
839 * queue for which poll or drainTo may fail to remove some
840 * elements, it deletes them one by one.
842 private List
<Runnable
> drainQueue() {
843 BlockingQueue
<Runnable
> q
= workQueue
;
844 ArrayList
<Runnable
> taskList
= new ArrayList
<>();
847 for (Runnable r
: q
.toArray(new Runnable
[0])) {
856 * Methods for creating, running and cleaning up after workers
860 * Checks if a new worker can be added with respect to current
861 * pool state and the given bound (either core or maximum). If so,
862 * the worker count is adjusted accordingly, and, if possible, a
863 * new worker is created and started, running firstTask as its
864 * first task. This method returns false if the pool is stopped or
865 * eligible to shut down. It also returns false if the thread
866 * factory fails to create a thread when asked. If the thread
867 * creation fails, either due to the thread factory returning
868 * null, or due to an exception (typically OutOfMemoryError in
869 * Thread.start()), we roll back cleanly.
871 * @param firstTask the task the new thread should run first (or
872 * null if none). Workers are created with an initial first task
873 * (in method execute()) to bypass queuing when there are fewer
874 * than corePoolSize threads (in which case we always start one),
875 * or when the queue is full (in which case we must bypass queue).
876 * Initially idle threads are usually created via
877 * prestartCoreThread or to replace other dying workers.
879 * @param core if true use corePoolSize as bound, else
880 * maximumPoolSize. (A boolean indicator is used here rather than a
881 * value to ensure reads of fresh values after checking other pool
883 * @return true if successful
885 private boolean addWorker(Runnable firstTask
, boolean core
) {
889 int rs
= runStateOf(c
);
891 // Check if queue empty only if necessary.
892 if (rs
>= SHUTDOWN
&&
895 ! workQueue
.isEmpty()))
899 int wc
= workerCountOf(c
);
900 if (wc
>= CAPACITY
||
901 wc
>= (core ? corePoolSize
: maximumPoolSize
))
903 if (compareAndIncrementWorkerCount(c
))
905 c
= ctl
.get(); // Re-read ctl
906 if (runStateOf(c
) != rs
)
908 // else CAS failed due to workerCount change; retry inner loop
912 boolean workerStarted
= false;
913 boolean workerAdded
= false;
916 w
= new Worker(firstTask
);
917 final Thread t
= w
.thread
;
919 final ReentrantLock mainLock
= this.mainLock
;
922 // Recheck while holding lock.
923 // Back out on ThreadFactory failure or if
924 // shut down before lock acquired.
925 int rs
= runStateOf(ctl
.get());
928 (rs
== SHUTDOWN
&& firstTask
== null)) {
929 if (t
.isAlive()) // precheck that t is startable
930 throw new IllegalThreadStateException();
932 int s
= workers
.size();
933 if (s
> largestPoolSize
)
942 workerStarted
= true;
949 return workerStarted
;
953 * Rolls back the worker thread creation.
954 * - removes worker from workers, if present
955 * - decrements worker count
956 * - rechecks for termination, in case the existence of this
957 * worker was holding up termination
959 private void addWorkerFailed(Worker w
) {
960 final ReentrantLock mainLock
= this.mainLock
;
965 decrementWorkerCount();
973 * Performs cleanup and bookkeeping for a dying worker. Called
974 * only from worker threads. Unless completedAbruptly is set,
975 * assumes that workerCount has already been adjusted to account
976 * for exit. This method removes thread from worker set, and
977 * possibly terminates the pool or replaces the worker if either
978 * it exited due to user task exception or if fewer than
979 * corePoolSize workers are running or queue is non-empty but
980 * there are no workers.
982 * @param w the worker
983 * @param completedAbruptly if the worker died due to user exception
985 private void processWorkerExit(Worker w
, boolean completedAbruptly
) {
986 if (completedAbruptly
) // If abrupt, then workerCount wasn't adjusted
987 decrementWorkerCount();
989 final ReentrantLock mainLock
= this.mainLock
;
992 completedTaskCount
+= w
.completedTasks
;
1001 if (runStateLessThan(c
, STOP
)) {
1002 if (!completedAbruptly
) {
1003 int min
= allowCoreThreadTimeOut ?
0 : corePoolSize
;
1004 if (min
== 0 && ! workQueue
.isEmpty())
1006 if (workerCountOf(c
) >= min
)
1007 return; // replacement not needed
1009 addWorker(null, false);
1014 * Performs blocking or timed wait for a task, depending on
1015 * current configuration settings, or returns null if this worker
1016 * must exit because of any of:
1017 * 1. There are more than maximumPoolSize workers (due to
1018 * a call to setMaximumPoolSize).
1019 * 2. The pool is stopped.
1020 * 3. The pool is shutdown and the queue is empty.
1021 * 4. This worker timed out waiting for a task, and timed-out
1022 * workers are subject to termination (that is,
1023 * {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
1024 * both before and after the timed wait, and if the queue is
1025 * non-empty, this worker is not the last thread in the pool.
1027 * @return task, or null if the worker must exit, in which case
1028 * workerCount is decremented
1030 private Runnable
getTask() {
1031 boolean timedOut
= false; // Did the last poll() time out?
1035 int rs
= runStateOf(c
);
1037 // Check if queue empty only if necessary.
1038 if (rs
>= SHUTDOWN
&& (rs
>= STOP
|| workQueue
.isEmpty())) {
1039 decrementWorkerCount();
1043 int wc
= workerCountOf(c
);
1045 // Are workers subject to culling?
1046 boolean timed
= allowCoreThreadTimeOut
|| wc
> corePoolSize
;
1048 if ((wc
> maximumPoolSize
|| (timed
&& timedOut
))
1049 && (wc
> 1 || workQueue
.isEmpty())) {
1050 if (compareAndDecrementWorkerCount(c
))
1056 Runnable r
= timed ?
1057 workQueue
.poll(keepAliveTime
, TimeUnit
.NANOSECONDS
) :
1062 } catch (InterruptedException retry
) {
1069 * Main worker run loop. Repeatedly gets tasks from queue and
1070 * executes them, while coping with a number of issues:
1072 * 1. We may start out with an initial task, in which case we
1073 * don't need to get the first one. Otherwise, as long as pool is
1074 * running, we get tasks from getTask. If it returns null then the
1075 * worker exits due to changed pool state or configuration
1076 * parameters. Other exits result from exception throws in
1077 * external code, in which case completedAbruptly holds, which
1078 * usually leads processWorkerExit to replace this thread.
1080 * 2. Before running any task, the lock is acquired to prevent
1081 * other pool interrupts while the task is executing, and then we
1082 * ensure that unless pool is stopping, this thread does not have
1083 * its interrupt set.
1085 * 3. Each task run is preceded by a call to beforeExecute, which
1086 * might throw an exception, in which case we cause thread to die
1087 * (breaking loop with completedAbruptly true) without processing
1090 * 4. Assuming beforeExecute completes normally, we run the task,
1091 * gathering any of its thrown exceptions to send to afterExecute.
1092 * We separately handle RuntimeException, Error (both of which the
1093 * specs guarantee that we trap) and arbitrary Throwables.
1094 * Because we cannot rethrow Throwables within Runnable.run, we
1095 * wrap them within Errors on the way out (to the thread's
1096 * UncaughtExceptionHandler). Any thrown exception also
1097 * conservatively causes thread to die.
1099 * 5. After task.run completes, we call afterExecute, which may
1100 * also throw an exception, which will also cause thread to
1101 * die. According to JLS Sec 14.20, this exception is the one that
1102 * will be in effect even if task.run throws.
1104 * The net effect of the exception mechanics is that afterExecute
1105 * and the thread's UncaughtExceptionHandler have as accurate
1106 * information as we can provide about any problems encountered by
1109 * @param w the worker
1111 final void runWorker(Worker w
) {
1112 Thread wt
= Thread
.currentThread();
1113 Runnable task
= w
.firstTask
;
1115 w
.unlock(); // allow interrupts
1116 boolean completedAbruptly
= true;
1118 while (task
!= null || (task
= getTask()) != null) {
1120 // If pool is stopping, ensure thread is interrupted;
1121 // if not, ensure thread is not interrupted. This
1122 // requires a recheck in second case to deal with
1123 // shutdownNow race while clearing interrupt
1124 if ((runStateAtLeast(ctl
.get(), STOP
) ||
1125 (Thread
.interrupted() &&
1126 runStateAtLeast(ctl
.get(), STOP
))) &&
1127 !wt
.isInterrupted())
1130 beforeExecute(wt
, task
);
1131 Throwable thrown
= null;
1134 } catch (RuntimeException x
) {
1135 thrown
= x
; throw x
;
1137 thrown
= x
; throw x
;
1138 } catch (Throwable x
) {
1139 thrown
= x
; throw new Error(x
);
1141 afterExecute(task
, thrown
);
1149 completedAbruptly
= false;
1151 processWorkerExit(w
, completedAbruptly
);
1155 // Public constructors and methods
1158 * Creates a new {@code ThreadPoolExecutor} with the given initial
1159 * parameters and default thread factory and rejected execution handler.
1160 * It may be more convenient to use one of the {@link Executors} factory
1161 * methods instead of this general purpose constructor.
1163 * @param corePoolSize the number of threads to keep in the pool, even
1164 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1165 * @param maximumPoolSize the maximum number of threads to allow in the
1167 * @param keepAliveTime when the number of threads is greater than
1168 * the core, this is the maximum time that excess idle threads
1169 * will wait for new tasks before terminating.
1170 * @param unit the time unit for the {@code keepAliveTime} argument
1171 * @param workQueue the queue to use for holding tasks before they are
1172 * executed. This queue will hold only the {@code Runnable}
1173 * tasks submitted by the {@code execute} method.
1174 * @throws IllegalArgumentException if one of the following holds:<br>
1175 * {@code corePoolSize < 0}<br>
1176 * {@code keepAliveTime < 0}<br>
1177 * {@code maximumPoolSize <= 0}<br>
1178 * {@code maximumPoolSize < corePoolSize}
1179 * @throws NullPointerException if {@code workQueue} is null
1181 public ThreadPoolExecutor(int corePoolSize
,
1182 int maximumPoolSize
,
1185 BlockingQueue
<Runnable
> workQueue
) {
1186 this(corePoolSize
, maximumPoolSize
, keepAliveTime
, unit
, workQueue
,
1187 Executors
.defaultThreadFactory(), defaultHandler
);
1191 * Creates a new {@code ThreadPoolExecutor} with the given initial
1192 * parameters and default rejected execution handler.
1194 * @param corePoolSize the number of threads to keep in the pool, even
1195 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1196 * @param maximumPoolSize the maximum number of threads to allow in the
1198 * @param keepAliveTime when the number of threads is greater than
1199 * the core, this is the maximum time that excess idle threads
1200 * will wait for new tasks before terminating.
1201 * @param unit the time unit for the {@code keepAliveTime} argument
1202 * @param workQueue the queue to use for holding tasks before they are
1203 * executed. This queue will hold only the {@code Runnable}
1204 * tasks submitted by the {@code execute} method.
1205 * @param threadFactory the factory to use when the executor
1206 * creates a new thread
1207 * @throws IllegalArgumentException if one of the following holds:<br>
1208 * {@code corePoolSize < 0}<br>
1209 * {@code keepAliveTime < 0}<br>
1210 * {@code maximumPoolSize <= 0}<br>
1211 * {@code maximumPoolSize < corePoolSize}
1212 * @throws NullPointerException if {@code workQueue}
1213 * or {@code threadFactory} is null
1215 public ThreadPoolExecutor(int corePoolSize
,
1216 int maximumPoolSize
,
1219 BlockingQueue
<Runnable
> workQueue
,
1220 ThreadFactory threadFactory
) {
1221 this(corePoolSize
, maximumPoolSize
, keepAliveTime
, unit
, workQueue
,
1222 threadFactory
, defaultHandler
);
1226 * Creates a new {@code ThreadPoolExecutor} with the given initial
1227 * parameters and default thread factory.
1229 * @param corePoolSize the number of threads to keep in the pool, even
1230 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1231 * @param maximumPoolSize the maximum number of threads to allow in the
1233 * @param keepAliveTime when the number of threads is greater than
1234 * the core, this is the maximum time that excess idle threads
1235 * will wait for new tasks before terminating.
1236 * @param unit the time unit for the {@code keepAliveTime} argument
1237 * @param workQueue the queue to use for holding tasks before they are
1238 * executed. This queue will hold only the {@code Runnable}
1239 * tasks submitted by the {@code execute} method.
1240 * @param handler the handler to use when execution is blocked
1241 * because the thread bounds and queue capacities are reached
1242 * @throws IllegalArgumentException if one of the following holds:<br>
1243 * {@code corePoolSize < 0}<br>
1244 * {@code keepAliveTime < 0}<br>
1245 * {@code maximumPoolSize <= 0}<br>
1246 * {@code maximumPoolSize < corePoolSize}
1247 * @throws NullPointerException if {@code workQueue}
1248 * or {@code handler} is null
1250 public ThreadPoolExecutor(int corePoolSize
,
1251 int maximumPoolSize
,
1254 BlockingQueue
<Runnable
> workQueue
,
1255 RejectedExecutionHandler handler
) {
1256 this(corePoolSize
, maximumPoolSize
, keepAliveTime
, unit
, workQueue
,
1257 Executors
.defaultThreadFactory(), handler
);
1261 * Creates a new {@code ThreadPoolExecutor} with the given initial
1264 * @param corePoolSize the number of threads to keep in the pool, even
1265 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1266 * @param maximumPoolSize the maximum number of threads to allow in the
1268 * @param keepAliveTime when the number of threads is greater than
1269 * the core, this is the maximum time that excess idle threads
1270 * will wait for new tasks before terminating.
1271 * @param unit the time unit for the {@code keepAliveTime} argument
1272 * @param workQueue the queue to use for holding tasks before they are
1273 * executed. This queue will hold only the {@code Runnable}
1274 * tasks submitted by the {@code execute} method.
1275 * @param threadFactory the factory to use when the executor
1276 * creates a new thread
1277 * @param handler the handler to use when execution is blocked
1278 * because the thread bounds and queue capacities are reached
1279 * @throws IllegalArgumentException if one of the following holds:<br>
1280 * {@code corePoolSize < 0}<br>
1281 * {@code keepAliveTime < 0}<br>
1282 * {@code maximumPoolSize <= 0}<br>
1283 * {@code maximumPoolSize < corePoolSize}
1284 * @throws NullPointerException if {@code workQueue}
1285 * or {@code threadFactory} or {@code handler} is null
1287 public ThreadPoolExecutor(int corePoolSize
,
1288 int maximumPoolSize
,
1291 BlockingQueue
<Runnable
> workQueue
,
1292 ThreadFactory threadFactory
,
1293 RejectedExecutionHandler handler
) {
1294 if (corePoolSize
< 0 ||
1295 maximumPoolSize
<= 0 ||
1296 maximumPoolSize
< corePoolSize
||
1298 throw new IllegalArgumentException();
1299 if (workQueue
== null || threadFactory
== null || handler
== null)
1300 throw new NullPointerException();
1301 this.corePoolSize
= corePoolSize
;
1302 this.maximumPoolSize
= maximumPoolSize
;
1303 this.workQueue
= workQueue
;
1304 this.keepAliveTime
= unit
.toNanos(keepAliveTime
);
1305 this.threadFactory
= threadFactory
;
1306 this.handler
= handler
;
1310 * Executes the given task sometime in the future. The task
1311 * may execute in a new thread or in an existing pooled thread.
1313 * If the task cannot be submitted for execution, either because this
1314 * executor has been shutdown or because its capacity has been reached,
1315 * the task is handled by the current {@code RejectedExecutionHandler}.
1317 * @param command the task to execute
1318 * @throws RejectedExecutionException at discretion of
1319 * {@code RejectedExecutionHandler}, if the task
1320 * cannot be accepted for execution
1321 * @throws NullPointerException if {@code command} is null
1323 public void execute(Runnable command
) {
1324 if (command
== null)
1325 throw new NullPointerException();
1327 * Proceed in 3 steps:
1329 * 1. If fewer than corePoolSize threads are running, try to
1330 * start a new thread with the given command as its first
1331 * task. The call to addWorker atomically checks runState and
1332 * workerCount, and so prevents false alarms that would add
1333 * threads when it shouldn't, by returning false.
1335 * 2. If a task can be successfully queued, then we still need
1336 * to double-check whether we should have added a thread
1337 * (because existing ones died since last checking) or that
1338 * the pool shut down since entry into this method. So we
1339 * recheck state and if necessary roll back the enqueuing if
1340 * stopped, or start a new thread if there are none.
1342 * 3. If we cannot queue task, then we try to add a new
1343 * thread. If it fails, we know we are shut down or saturated
1344 * and so reject the task.
1347 if (workerCountOf(c
) < corePoolSize
) {
1348 if (addWorker(command
, true))
1352 if (isRunning(c
) && workQueue
.offer(command
)) {
1353 int recheck
= ctl
.get();
1354 if (! isRunning(recheck
) && remove(command
))
1356 else if (workerCountOf(recheck
) == 0)
1357 addWorker(null, false);
1359 else if (!addWorker(command
, false))
1364 * Initiates an orderly shutdown in which previously submitted
1365 * tasks are executed, but no new tasks will be accepted.
1366 * Invocation has no additional effect if already shut down.
1368 * <p>This method does not wait for previously submitted tasks to
1369 * complete execution. Use {@link #awaitTermination awaitTermination}
1372 // android-note: Removed @throws SecurityException
1373 public void shutdown() {
1374 final ReentrantLock mainLock
= this.mainLock
;
1377 checkShutdownAccess();
1378 advanceRunState(SHUTDOWN
);
1379 interruptIdleWorkers();
1380 onShutdown(); // hook for ScheduledThreadPoolExecutor
1388 * Attempts to stop all actively executing tasks, halts the
1389 * processing of waiting tasks, and returns a list of the tasks
1390 * that were awaiting execution. These tasks are drained (removed)
1391 * from the task queue upon return from this method.
1393 * <p>This method does not wait for actively executing tasks to
1394 * terminate. Use {@link #awaitTermination awaitTermination} to
1397 * <p>There are no guarantees beyond best-effort attempts to stop
1398 * processing actively executing tasks. This implementation
1399 * interrupts tasks via {@link Thread#interrupt}; any task that
1400 * fails to respond to interrupts may never terminate.
1402 // android-note: Removed @throws SecurityException
1403 public List
<Runnable
> shutdownNow() {
1404 List
<Runnable
> tasks
;
1405 final ReentrantLock mainLock
= this.mainLock
;
1408 checkShutdownAccess();
1409 advanceRunState(STOP
);
1411 tasks
= drainQueue();
1419 public boolean isShutdown() {
1420 return ! isRunning(ctl
.get());
1424 * Returns true if this executor is in the process of terminating
1425 * after {@link #shutdown} or {@link #shutdownNow} but has not
1426 * completely terminated. This method may be useful for
1427 * debugging. A return of {@code true} reported a sufficient
1428 * period after shutdown may indicate that submitted tasks have
1429 * ignored or suppressed interruption, causing this executor not
1430 * to properly terminate.
1432 * @return {@code true} if terminating but not yet terminated
1434 public boolean isTerminating() {
1436 return ! isRunning(c
) && runStateLessThan(c
, TERMINATED
);
1439 public boolean isTerminated() {
1440 return runStateAtLeast(ctl
.get(), TERMINATED
);
1443 public boolean awaitTermination(long timeout
, TimeUnit unit
)
1444 throws InterruptedException
{
1445 long nanos
= unit
.toNanos(timeout
);
1446 final ReentrantLock mainLock
= this.mainLock
;
1449 while (!runStateAtLeast(ctl
.get(), TERMINATED
)) {
1452 nanos
= termination
.awaitNanos(nanos
);
1461 * Invokes {@code shutdown} when this executor is no longer
1462 * referenced and it has no threads.
1464 protected void finalize() {
1469 * Sets the thread factory used to create new threads.
1471 * @param threadFactory the new thread factory
1472 * @throws NullPointerException if threadFactory is null
1473 * @see #getThreadFactory
1475 public void setThreadFactory(ThreadFactory threadFactory
) {
1476 if (threadFactory
== null)
1477 throw new NullPointerException();
1478 this.threadFactory
= threadFactory
;
1482 * Returns the thread factory used to create new threads.
1484 * @return the current thread factory
1485 * @see #setThreadFactory(ThreadFactory)
1487 public ThreadFactory
getThreadFactory() {
1488 return threadFactory
;
1492 * Sets a new handler for unexecutable tasks.
1494 * @param handler the new handler
1495 * @throws NullPointerException if handler is null
1496 * @see #getRejectedExecutionHandler
1498 public void setRejectedExecutionHandler(RejectedExecutionHandler handler
) {
1499 if (handler
== null)
1500 throw new NullPointerException();
1501 this.handler
= handler
;
1505 * Returns the current handler for unexecutable tasks.
1507 * @return the current handler
1508 * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
1510 public RejectedExecutionHandler
getRejectedExecutionHandler() {
1515 * Sets the core number of threads. This overrides any value set
1516 * in the constructor. If the new value is smaller than the
1517 * current value, excess existing threads will be terminated when
1518 * they next become idle. If larger, new threads will, if needed,
1519 * be started to execute any queued tasks.
1521 * @param corePoolSize the new core size
1522 * @throws IllegalArgumentException if {@code corePoolSize < 0}
1523 * @see #getCorePoolSize
1525 // Android-changed: Reverted code that threw an IAE when
1526 // {@code corePoolSize} is greater than the {@linkplain #getMaximumPoolSize()
1527 // maximum pool size}. This is due to defective code in a commonly used third
1528 // party library that does something like :
1530 // exec.setCorePoolSize(N);
1531 // exec.setMaxPoolSize(N);
1532 public void setCorePoolSize(int corePoolSize
) {
1533 if (corePoolSize
< 0)
1534 throw new IllegalArgumentException();
1535 int delta
= corePoolSize
- this.corePoolSize
;
1536 this.corePoolSize
= corePoolSize
;
1537 if (workerCountOf(ctl
.get()) > corePoolSize
)
1538 interruptIdleWorkers();
1539 else if (delta
> 0) {
1540 // We don't really know how many new threads are "needed".
1541 // As a heuristic, prestart enough new workers (up to new
1542 // core size) to handle the current number of tasks in
1543 // queue, but stop if queue becomes empty while doing so.
1544 int k
= Math
.min(delta
, workQueue
.size());
1545 while (k
-- > 0 && addWorker(null, true)) {
1546 if (workQueue
.isEmpty())
1553 * Returns the core number of threads.
1555 * @return the core number of threads
1556 * @see #setCorePoolSize
1558 public int getCorePoolSize() {
1559 return corePoolSize
;
1563 * Starts a core thread, causing it to idly wait for work. This
1564 * overrides the default policy of starting core threads only when
1565 * new tasks are executed. This method will return {@code false}
1566 * if all core threads have already been started.
1568 * @return {@code true} if a thread was started
1570 public boolean prestartCoreThread() {
1571 return workerCountOf(ctl
.get()) < corePoolSize
&&
1572 addWorker(null, true);
1576 * Same as prestartCoreThread except arranges that at least one
1577 * thread is started even if corePoolSize is 0.
1579 void ensurePrestart() {
1580 int wc
= workerCountOf(ctl
.get());
1581 if (wc
< corePoolSize
)
1582 addWorker(null, true);
1584 addWorker(null, false);
1588 * Starts all core threads, causing them to idly wait for work. This
1589 * overrides the default policy of starting core threads only when
1590 * new tasks are executed.
1592 * @return the number of threads started
1594 public int prestartAllCoreThreads() {
1596 while (addWorker(null, true))
1602 * Returns true if this pool allows core threads to time out and
1603 * terminate if no tasks arrive within the keepAlive time, being
1604 * replaced if needed when new tasks arrive. When true, the same
1605 * keep-alive policy applying to non-core threads applies also to
1606 * core threads. When false (the default), core threads are never
1607 * terminated due to lack of incoming tasks.
1609 * @return {@code true} if core threads are allowed to time out,
1610 * else {@code false}
1614 public boolean allowsCoreThreadTimeOut() {
1615 return allowCoreThreadTimeOut
;
1619 * Sets the policy governing whether core threads may time out and
1620 * terminate if no tasks arrive within the keep-alive time, being
1621 * replaced if needed when new tasks arrive. When false, core
1622 * threads are never terminated due to lack of incoming
1623 * tasks. When true, the same keep-alive policy applying to
1624 * non-core threads applies also to core threads. To avoid
1625 * continual thread replacement, the keep-alive time must be
1626 * greater than zero when setting {@code true}. This method
1627 * should in general be called before the pool is actively used.
1629 * @param value {@code true} if should time out, else {@code false}
1630 * @throws IllegalArgumentException if value is {@code true}
1631 * and the current keep-alive time is not greater than zero
1635 public void allowCoreThreadTimeOut(boolean value
) {
1636 if (value
&& keepAliveTime
<= 0)
1637 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1638 if (value
!= allowCoreThreadTimeOut
) {
1639 allowCoreThreadTimeOut
= value
;
1641 interruptIdleWorkers();
1646 * Sets the maximum allowed number of threads. This overrides any
1647 * value set in the constructor. If the new value is smaller than
1648 * the current value, excess existing threads will be
1649 * terminated when they next become idle.
1651 * @param maximumPoolSize the new maximum
1652 * @throws IllegalArgumentException if the new maximum is
1653 * less than or equal to zero, or
1654 * less than the {@linkplain #getCorePoolSize core pool size}
1655 * @see #getMaximumPoolSize
1657 public void setMaximumPoolSize(int maximumPoolSize
) {
1658 if (maximumPoolSize
<= 0 || maximumPoolSize
< corePoolSize
)
1659 throw new IllegalArgumentException();
1660 this.maximumPoolSize
= maximumPoolSize
;
1661 if (workerCountOf(ctl
.get()) > maximumPoolSize
)
1662 interruptIdleWorkers();
1666 * Returns the maximum allowed number of threads.
1668 * @return the maximum allowed number of threads
1669 * @see #setMaximumPoolSize
1671 public int getMaximumPoolSize() {
1672 return maximumPoolSize
;
1676 * Sets the thread keep-alive time, which is the amount of time
1677 * that threads may remain idle before being terminated.
1678 * Threads that wait this amount of time without processing a
1679 * task will be terminated if there are more than the core
1680 * number of threads currently in the pool, or if this pool
1681 * {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}.
1682 * This overrides any value set in the constructor.
1684 * @param time the time to wait. A time value of zero will cause
1685 * excess threads to terminate immediately after executing tasks.
1686 * @param unit the time unit of the {@code time} argument
1687 * @throws IllegalArgumentException if {@code time} less than zero or
1688 * if {@code time} is zero and {@code allowsCoreThreadTimeOut}
1689 * @see #getKeepAliveTime(TimeUnit)
1691 public void setKeepAliveTime(long time
, TimeUnit unit
) {
1693 throw new IllegalArgumentException();
1694 if (time
== 0 && allowsCoreThreadTimeOut())
1695 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1696 long keepAliveTime
= unit
.toNanos(time
);
1697 long delta
= keepAliveTime
- this.keepAliveTime
;
1698 this.keepAliveTime
= keepAliveTime
;
1700 interruptIdleWorkers();
1704 * Returns the thread keep-alive time, which is the amount of time
1705 * that threads may remain idle before being terminated.
1706 * Threads that wait this amount of time without processing a
1707 * task will be terminated if there are more than the core
1708 * number of threads currently in the pool, or if this pool
1709 * {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}.
1711 * @param unit the desired time unit of the result
1712 * @return the time limit
1713 * @see #setKeepAliveTime(long, TimeUnit)
1715 public long getKeepAliveTime(TimeUnit unit
) {
1716 return unit
.convert(keepAliveTime
, TimeUnit
.NANOSECONDS
);
1719 /* User-level queue utilities */
1722 * Returns the task queue used by this executor. Access to the
1723 * task queue is intended primarily for debugging and monitoring.
1724 * This queue may be in active use. Retrieving the task queue
1725 * does not prevent queued tasks from executing.
1727 * @return the task queue
1729 public BlockingQueue
<Runnable
> getQueue() {
1734 * Removes this task from the executor's internal queue if it is
1735 * present, thus causing it not to be run if it has not already
1738 * <p>This method may be useful as one part of a cancellation
1739 * scheme. It may fail to remove tasks that have been converted
1740 * into other forms before being placed on the internal queue.
1741 * For example, a task entered using {@code submit} might be
1742 * converted into a form that maintains {@code Future} status.
1743 * However, in such cases, method {@link #purge} may be used to
1744 * remove those Futures that have been cancelled.
1746 * @param task the task to remove
1747 * @return {@code true} if the task was removed
1749 public boolean remove(Runnable task
) {
1750 boolean removed
= workQueue
.remove(task
);
1751 tryTerminate(); // In case SHUTDOWN and now empty
1756 * Tries to remove from the work queue all {@link Future}
1757 * tasks that have been cancelled. This method can be useful as a
1758 * storage reclamation operation, that has no other impact on
1759 * functionality. Cancelled tasks are never executed, but may
1760 * accumulate in work queues until worker threads can actively
1761 * remove them. Invoking this method instead tries to remove them now.
1762 * However, this method may fail to remove tasks in
1763 * the presence of interference by other threads.
1765 public void purge() {
1766 final BlockingQueue
<Runnable
> q
= workQueue
;
1768 Iterator
<Runnable
> it
= q
.iterator();
1769 while (it
.hasNext()) {
1770 Runnable r
= it
.next();
1771 if (r
instanceof Future
<?
> && ((Future
<?
>)r
).isCancelled())
1774 } catch (ConcurrentModificationException fallThrough
) {
1775 // Take slow path if we encounter interference during traversal.
1776 // Make copy for traversal and call remove for cancelled entries.
1777 // The slow path is more likely to be O(N*N).
1778 for (Object r
: q
.toArray())
1779 if (r
instanceof Future
<?
> && ((Future
<?
>)r
).isCancelled())
1783 tryTerminate(); // In case SHUTDOWN and now empty
1789 * Returns the current number of threads in the pool.
1791 * @return the number of threads
1793 public int getPoolSize() {
1794 final ReentrantLock mainLock
= this.mainLock
;
1797 // Remove rare and surprising possibility of
1798 // isTerminated() && getPoolSize() > 0
1799 return runStateAtLeast(ctl
.get(), TIDYING
) ?
0
1807 * Returns the approximate number of threads that are actively
1810 * @return the number of threads
1812 public int getActiveCount() {
1813 final ReentrantLock mainLock
= this.mainLock
;
1817 for (Worker w
: workers
)
1827 * Returns the largest number of threads that have ever
1828 * simultaneously been in the pool.
1830 * @return the number of threads
1832 public int getLargestPoolSize() {
1833 final ReentrantLock mainLock
= this.mainLock
;
1836 return largestPoolSize
;
1843 * Returns the approximate total number of tasks that have ever been
1844 * scheduled for execution. Because the states of tasks and
1845 * threads may change dynamically during computation, the returned
1846 * value is only an approximation.
1848 * @return the number of tasks
1850 public long getTaskCount() {
1851 final ReentrantLock mainLock
= this.mainLock
;
1854 long n
= completedTaskCount
;
1855 for (Worker w
: workers
) {
1856 n
+= w
.completedTasks
;
1860 return n
+ workQueue
.size();
1867 * Returns the approximate total number of tasks that have
1868 * completed execution. Because the states of tasks and threads
1869 * may change dynamically during computation, the returned value
1870 * is only an approximation, but one that does not ever decrease
1871 * across successive calls.
1873 * @return the number of tasks
1875 public long getCompletedTaskCount() {
1876 final ReentrantLock mainLock
= this.mainLock
;
1879 long n
= completedTaskCount
;
1880 for (Worker w
: workers
)
1881 n
+= w
.completedTasks
;
1889 * Returns a string identifying this pool, as well as its state,
1890 * including indications of run state and estimated worker and
1893 * @return a string identifying this pool, as well as its state
1895 public String
toString() {
1897 int nworkers
, nactive
;
1898 final ReentrantLock mainLock
= this.mainLock
;
1901 ncompleted
= completedTaskCount
;
1903 nworkers
= workers
.size();
1904 for (Worker w
: workers
) {
1905 ncompleted
+= w
.completedTasks
;
1914 runStateLessThan(c
, SHUTDOWN
) ?
"Running" :
1915 runStateAtLeast(c
, TERMINATED
) ?
"Terminated" :
1917 return super.toString() +
1919 ", pool size = " + nworkers
+
1920 ", active threads = " + nactive
+
1921 ", queued tasks = " + workQueue
.size() +
1922 ", completed tasks = " + ncompleted
+
1926 /* Extension hooks */
1929 * Method invoked prior to executing the given Runnable in the
1930 * given thread. This method is invoked by thread {@code t} that
1931 * will execute task {@code r}, and may be used to re-initialize
1932 * ThreadLocals, or to perform logging.
1934 * <p>This implementation does nothing, but may be customized in
1935 * subclasses. Note: To properly nest multiple overridings, subclasses
1936 * should generally invoke {@code super.beforeExecute} at the end of
1939 * @param t the thread that will run task {@code r}
1940 * @param r the task that will be executed
1942 protected void beforeExecute(Thread t
, Runnable r
) { }
1945 * Method invoked upon completion of execution of the given Runnable.
1946 * This method is invoked by the thread that executed the task. If
1947 * non-null, the Throwable is the uncaught {@code RuntimeException}
1948 * or {@code Error} that caused execution to terminate abruptly.
1950 * <p>This implementation does nothing, but may be customized in
1951 * subclasses. Note: To properly nest multiple overridings, subclasses
1952 * should generally invoke {@code super.afterExecute} at the
1953 * beginning of this method.
1955 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1956 * {@link FutureTask}) either explicitly or via methods such as
1957 * {@code submit}, these task objects catch and maintain
1958 * computational exceptions, and so they do not cause abrupt
1959 * termination, and the internal exceptions are <em>not</em>
1960 * passed to this method. If you would like to trap both kinds of
1961 * failures in this method, you can further probe for such cases,
1962 * as in this sample subclass that prints either the direct cause
1963 * or the underlying exception if a task has been aborted:
1966 * class ExtendedExecutor extends ThreadPoolExecutor {
1968 * protected void afterExecute(Runnable r, Throwable t) {
1969 * super.afterExecute(r, t);
1971 * && r instanceof Future<?>
1972 * && ((Future<?>)r).isDone()) {
1974 * Object result = ((Future<?>) r).get();
1975 * } catch (CancellationException ce) {
1977 * } catch (ExecutionException ee) {
1978 * t = ee.getCause();
1979 * } catch (InterruptedException ie) {
1981 * Thread.currentThread().interrupt();
1985 * System.out.println(t);
1989 * @param r the runnable that has completed
1990 * @param t the exception that caused termination, or null if
1991 * execution completed normally
1993 protected void afterExecute(Runnable r
, Throwable t
) { }
1996 * Method invoked when the Executor has terminated. Default
1997 * implementation does nothing. Note: To properly nest multiple
1998 * overridings, subclasses should generally invoke
1999 * {@code super.terminated} within this method.
2001 protected void terminated() { }
2003 /* Predefined RejectedExecutionHandlers */
2006 * A handler for rejected tasks that runs the rejected task
2007 * directly in the calling thread of the {@code execute} method,
2008 * unless the executor has been shut down, in which case the task
2011 public static class CallerRunsPolicy
implements RejectedExecutionHandler
{
2013 * Creates a {@code CallerRunsPolicy}.
2015 public CallerRunsPolicy() { }
2018 * Executes task r in the caller's thread, unless the executor
2019 * has been shut down, in which case the task is discarded.
2021 * @param r the runnable task requested to be executed
2022 * @param e the executor attempting to execute this task
2024 public void rejectedExecution(Runnable r
, ThreadPoolExecutor e
) {
2025 if (!e
.isShutdown()) {
2032 * A handler for rejected tasks that throws a
2033 * {@code RejectedExecutionException}.
2035 public static class AbortPolicy
implements RejectedExecutionHandler
{
2037 * Creates an {@code AbortPolicy}.
2039 public AbortPolicy() { }
2042 * Always throws RejectedExecutionException.
2044 * @param r the runnable task requested to be executed
2045 * @param e the executor attempting to execute this task
2046 * @throws RejectedExecutionException always
2048 public void rejectedExecution(Runnable r
, ThreadPoolExecutor e
) {
2049 throw new RejectedExecutionException("Task " + r
.toString() +
2056 * A handler for rejected tasks that silently discards the
2059 public static class DiscardPolicy
implements RejectedExecutionHandler
{
2061 * Creates a {@code DiscardPolicy}.
2063 public DiscardPolicy() { }
2066 * Does nothing, which has the effect of discarding task r.
2068 * @param r the runnable task requested to be executed
2069 * @param e the executor attempting to execute this task
2071 public void rejectedExecution(Runnable r
, ThreadPoolExecutor e
) {
2076 * A handler for rejected tasks that discards the oldest unhandled
2077 * request and then retries {@code execute}, unless the executor
2078 * is shut down, in which case the task is discarded.
2080 public static class DiscardOldestPolicy
implements RejectedExecutionHandler
{
2082 * Creates a {@code DiscardOldestPolicy} for the given executor.
2084 public DiscardOldestPolicy() { }
2087 * Obtains and ignores the next task that the executor
2088 * would otherwise execute, if one is immediately available,
2089 * and then retries execution of task r, unless the executor
2090 * is shut down, in which case task r is instead discarded.
2092 * @param r the runnable task requested to be executed
2093 * @param e the executor attempting to execute this task
2095 public void rejectedExecution(Runnable r
, ThreadPoolExecutor e
) {
2096 if (!e
.isShutdown()) {
2097 e
.getQueue().poll();