Home | History | Annotate | Download | only in concurrent
      1 /*
      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/
      5  */
      6 
      7 package java.util.concurrent;
      8 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
      9 import java.util.concurrent.locks.Condition;
     10 import java.util.concurrent.locks.ReentrantLock;
     11 import java.util.concurrent.atomic.AtomicInteger;
     12 import java.util.*;
     13 
     14 // BEGIN android-note
     15 // removed security manager docs
     16 // END android-note
     17 
     18 /**
     19  * An {@link ExecutorService} that executes each submitted task using
     20  * one of possibly several pooled threads, normally configured
     21  * using {@link Executors} factory methods.
     22  *
     23  * <p>Thread pools address two different problems: they usually
     24  * provide improved performance when executing large numbers of
     25  * asynchronous tasks, due to reduced per-task invocation overhead,
     26  * and they provide a means of bounding and managing the resources,
     27  * including threads, consumed when executing a collection of tasks.
     28  * Each {@code ThreadPoolExecutor} also maintains some basic
     29  * statistics, such as the number of completed tasks.
     30  *
     31  * <p>To be useful across a wide range of contexts, this class
     32  * provides many adjustable parameters and extensibility
     33  * hooks. However, programmers are urged to use the more convenient
     34  * {@link Executors} factory methods {@link
     35  * Executors#newCachedThreadPool} (unbounded thread pool, with
     36  * automatic thread reclamation), {@link Executors#newFixedThreadPool}
     37  * (fixed size thread pool) and {@link
     38  * Executors#newSingleThreadExecutor} (single background thread), that
     39  * preconfigure settings for the most common usage
     40  * scenarios. Otherwise, use the following guide when manually
     41  * configuring and tuning this class:
     42  *
     43  * <dl>
     44  *
     45  * <dt>Core and maximum pool sizes</dt>
     46  *
     47  * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
     48  * pool size (see {@link #getPoolSize})
     49  * according to the bounds set by
     50  * corePoolSize (see {@link #getCorePoolSize}) and
     51  * maximumPoolSize (see {@link #getMaximumPoolSize}).
     52  *
     53  * When a new task is submitted in method {@link #execute(Runnable)},
     54  * and fewer than corePoolSize threads are running, a new thread is
     55  * created to handle the request, even if other worker threads are
     56  * idle.  If there are more than corePoolSize but less than
     57  * maximumPoolSize threads running, a new thread will be created only
     58  * if the queue is full.  By setting corePoolSize and maximumPoolSize
     59  * the same, you create a fixed-size thread pool. By setting
     60  * maximumPoolSize to an essentially unbounded value such as {@code
     61  * Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
     62  * number of concurrent tasks. Most typically, core and maximum pool
     63  * sizes are set only upon construction, but they may also be changed
     64  * dynamically using {@link #setCorePoolSize} and {@link
     65  * #setMaximumPoolSize}. </dd>
     66  *
     67  * <dt>On-demand construction</dt>
     68  *
     69  * <dd>By default, even core threads are initially created and
     70  * started only when new tasks arrive, but this can be overridden
     71  * dynamically using method {@link #prestartCoreThread} or {@link
     72  * #prestartAllCoreThreads}.  You probably want to prestart threads if
     73  * you construct the pool with a non-empty queue. </dd>
     74  *
     75  * <dt>Creating new threads</dt>
     76  *
     77  * <dd>New threads are created using a {@link ThreadFactory}.  If not
     78  * otherwise specified, a {@link Executors#defaultThreadFactory} is
     79  * used, that creates threads to all be in the same {@link
     80  * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
     81  * non-daemon status. By supplying a different ThreadFactory, you can
     82  * alter the thread's name, thread group, priority, daemon status,
     83  * etc. If a {@code ThreadFactory} fails to create a thread when asked
     84  * by returning null from {@code newThread}, the executor will
     85  * continue, but might not be able to execute any tasks.</dd>
     86  *
     87  * <dt>Keep-alive times</dt>
     88  *
     89  * <dd>If the pool currently has more than corePoolSize threads,
     90  * excess threads will be terminated if they have been idle for more
     91  * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
     92  * This provides a means of reducing resource consumption when the
     93  * pool is not being actively used. If the pool becomes more active
     94  * later, new threads will be constructed. This parameter can also be
     95  * changed dynamically using method {@link #setKeepAliveTime(long,
     96  * TimeUnit)}.  Using a value of {@code Long.MAX_VALUE} {@link
     97  * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
     98  * terminating prior to shut down. By default, the keep-alive policy
     99  * applies only when there are more than corePoolSize threads. But
    100  * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
    101  * apply this time-out policy to core threads as well, so long as the
    102  * keepAliveTime value is non-zero. </dd>
    103  *
    104  * <dt>Queuing</dt>
    105  *
    106  * <dd>Any {@link BlockingQueue} may be used to transfer and hold
    107  * submitted tasks.  The use of this queue interacts with pool sizing:
    108  *
    109  * <ul>
    110  *
    111  * <li> If fewer than corePoolSize threads are running, the Executor
    112  * always prefers adding a new thread
    113  * rather than queuing.</li>
    114  *
    115  * <li> If corePoolSize or more threads are running, the Executor
    116  * always prefers queuing a request rather than adding a new
    117  * thread.</li>
    118  *
    119  * <li> If a request cannot be queued, a new thread is created unless
    120  * this would exceed maximumPoolSize, in which case, the task will be
    121  * rejected.</li>
    122  *
    123  * </ul>
    124  *
    125  * There are three general strategies for queuing:
    126  * <ol>
    127  *
    128  * <li> <em> Direct handoffs.</em> A good default choice for a work
    129  * queue is a {@link SynchronousQueue} that hands off tasks to threads
    130  * without otherwise holding them. Here, an attempt to queue a task
    131  * will fail if no threads are immediately available to run it, so a
    132  * new thread will be constructed. This policy avoids lockups when
    133  * handling sets of requests that might have internal dependencies.
    134  * Direct handoffs generally require unbounded maximumPoolSizes to
    135  * avoid rejection of new submitted tasks. This in turn admits the
    136  * possibility of unbounded thread growth when commands continue to
    137  * arrive on average faster than they can be processed.  </li>
    138  *
    139  * <li><em> Unbounded queues.</em> Using an unbounded queue (for
    140  * example a {@link LinkedBlockingQueue} without a predefined
    141  * capacity) will cause new tasks to wait in the queue when all
    142  * corePoolSize threads are busy. Thus, no more than corePoolSize
    143  * threads will ever be created. (And the value of the maximumPoolSize
    144  * therefore doesn't have any effect.)  This may be appropriate when
    145  * each task is completely independent of others, so tasks cannot
    146  * affect each others execution; for example, in a web page server.
    147  * While this style of queuing can be useful in smoothing out
    148  * transient bursts of requests, it admits the possibility of
    149  * unbounded work queue growth when commands continue to arrive on
    150  * average faster than they can be processed.  </li>
    151  *
    152  * <li><em>Bounded queues.</em> A bounded queue (for example, an
    153  * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
    154  * used with finite maximumPoolSizes, but can be more difficult to
    155  * tune and control.  Queue sizes and maximum pool sizes may be traded
    156  * off for each other: Using large queues and small pools minimizes
    157  * CPU usage, OS resources, and context-switching overhead, but can
    158  * lead to artificially low throughput.  If tasks frequently block (for
    159  * example if they are I/O bound), a system may be able to schedule
    160  * time for more threads than you otherwise allow. Use of small queues
    161  * generally requires larger pool sizes, which keeps CPUs busier but
    162  * may encounter unacceptable scheduling overhead, which also
    163  * decreases throughput.  </li>
    164  *
    165  * </ol>
    166  *
    167  * </dd>
    168  *
    169  * <dt>Rejected tasks</dt>
    170  *
    171  * <dd>New tasks submitted in method {@link #execute(Runnable)} will be
    172  * <em>rejected</em> when the Executor has been shut down, and also when
    173  * the Executor uses finite bounds for both maximum threads and work queue
    174  * capacity, and is saturated.  In either case, the {@code execute} method
    175  * invokes the {@link
    176  * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
    177  * method of its {@link RejectedExecutionHandler}.  Four predefined handler
    178  * policies are provided:
    179  *
    180  * <ol>
    181  *
    182  * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the
    183  * handler throws a runtime {@link RejectedExecutionException} upon
    184  * rejection. </li>
    185  *
    186  * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
    187  * that invokes {@code execute} itself runs the task. This provides a
    188  * simple feedback control mechanism that will slow down the rate that
    189  * new tasks are submitted. </li>
    190  *
    191  * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
    192  * cannot be executed is simply dropped.  </li>
    193  *
    194  * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
    195  * executor is not shut down, the task at the head of the work queue
    196  * is dropped, and then execution is retried (which can fail again,
    197  * causing this to be repeated.) </li>
    198  *
    199  * </ol>
    200  *
    201  * It is possible to define and use other kinds of {@link
    202  * RejectedExecutionHandler} classes. Doing so requires some care
    203  * especially when policies are designed to work only under particular
    204  * capacity or queuing policies. </dd>
    205  *
    206  * <dt>Hook methods</dt>
    207  *
    208  * <dd>This class provides {@code protected} overridable
    209  * {@link #beforeExecute(Thread, Runnable)} and
    210  * {@link #afterExecute(Runnable, Throwable)} methods that are called
    211  * before and after execution of each task.  These can be used to
    212  * manipulate the execution environment; for example, reinitializing
    213  * ThreadLocals, gathering statistics, or adding log entries.
    214  * Additionally, method {@link #terminated} can be overridden to perform
    215  * any special processing that needs to be done once the Executor has
    216  * fully terminated.
    217  *
    218  * <p>If hook or callback methods throw exceptions, internal worker
    219  * threads may in turn fail and abruptly terminate.</dd>
    220  *
    221  * <dt>Queue maintenance</dt>
    222  *
    223  * <dd>Method {@link #getQueue()} allows access to the work queue
    224  * for purposes of monitoring and debugging.  Use of this method for
    225  * any other purpose is strongly discouraged.  Two supplied methods,
    226  * {@link #remove(Runnable)} and {@link #purge} are available to
    227  * assist in storage reclamation when large numbers of queued tasks
    228  * become cancelled.</dd>
    229  *
    230  * <dt>Finalization</dt>
    231  *
    232  * <dd>A pool that is no longer referenced in a program <em>AND</em>
    233  * has no remaining threads will be {@code shutdown} automatically. If
    234  * you would like to ensure that unreferenced pools are reclaimed even
    235  * if users forget to call {@link #shutdown}, then you must arrange
    236  * that unused threads eventually die, by setting appropriate
    237  * keep-alive times, using a lower bound of zero core threads and/or
    238  * setting {@link #allowCoreThreadTimeOut(boolean)}.  </dd>
    239  *
    240  * </dl>
    241  *
    242  * <p><b>Extension example</b>. Most extensions of this class
    243  * override one or more of the protected hook methods. For example,
    244  * here is a subclass that adds a simple pause/resume feature:
    245  *
    246  *  <pre> {@code
    247  * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
    248  *   private boolean isPaused;
    249  *   private ReentrantLock pauseLock = new ReentrantLock();
    250  *   private Condition unpaused = pauseLock.newCondition();
    251  *
    252  *   public PausableThreadPoolExecutor(...) { super(...); }
    253  *
    254  *   protected void beforeExecute(Thread t, Runnable r) {
    255  *     super.beforeExecute(t, r);
    256  *     pauseLock.lock();
    257  *     try {
    258  *       while (isPaused) unpaused.await();
    259  *     } catch (InterruptedException ie) {
    260  *       t.interrupt();
    261  *     } finally {
    262  *       pauseLock.unlock();
    263  *     }
    264  *   }
    265  *
    266  *   public void pause() {
    267  *     pauseLock.lock();
    268  *     try {
    269  *       isPaused = true;
    270  *     } finally {
    271  *       pauseLock.unlock();
    272  *     }
    273  *   }
    274  *
    275  *   public void resume() {
    276  *     pauseLock.lock();
    277  *     try {
    278  *       isPaused = false;
    279  *       unpaused.signalAll();
    280  *     } finally {
    281  *       pauseLock.unlock();
    282  *     }
    283  *   }
    284  * }}</pre>
    285  *
    286  * @since 1.5
    287  * @author Doug Lea
    288  */
    289 public class ThreadPoolExecutor extends AbstractExecutorService {
    290     /**
    291      * The main pool control state, ctl, is an atomic integer packing
    292      * two conceptual fields
    293      *   workerCount, indicating the effective number of threads
    294      *   runState,    indicating whether running, shutting down etc
    295      *
    296      * In order to pack them into one int, we limit workerCount to
    297      * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
    298      * billion) otherwise representable. If this is ever an issue in
    299      * the future, the variable can be changed to be an AtomicLong,
    300      * and the shift/mask constants below adjusted. But until the need
    301      * arises, this code is a bit faster and simpler using an int.
    302      *
    303      * The workerCount is the number of workers that have been
    304      * permitted to start and not permitted to stop.  The value may be
    305      * transiently different from the actual number of live threads,
    306      * for example when a ThreadFactory fails to create a thread when
    307      * asked, and when exiting threads are still performing
    308      * bookkeeping before terminating. The user-visible pool size is
    309      * reported as the current size of the workers set.
    310      *
    311      * The runState provides the main lifecycle control, taking on values:
    312      *
    313      *   RUNNING:  Accept new tasks and process queued tasks
    314      *   SHUTDOWN: Don't accept new tasks, but process queued tasks
    315      *   STOP:     Don't accept new tasks, don't process queued tasks,
    316      *             and interrupt in-progress tasks
    317      *   TIDYING:  All tasks have terminated, workerCount is zero,
    318      *             the thread transitioning to state TIDYING
    319      *             will run the terminated() hook method
    320      *   TERMINATED: terminated() has completed
    321      *
    322      * The numerical order among these values matters, to allow
    323      * ordered comparisons. The runState monotonically increases over
    324      * time, but need not hit each state. The transitions are:
    325      *
    326      * RUNNING -> SHUTDOWN
    327      *    On invocation of shutdown(), perhaps implicitly in finalize()
    328      * (RUNNING or SHUTDOWN) -> STOP
    329      *    On invocation of shutdownNow()
    330      * SHUTDOWN -> TIDYING
    331      *    When both queue and pool are empty
    332      * STOP -> TIDYING
    333      *    When pool is empty
    334      * TIDYING -> TERMINATED
    335      *    When the terminated() hook method has completed
    336      *
    337      * Threads waiting in awaitTermination() will return when the
    338      * state reaches TERMINATED.
    339      *
    340      * Detecting the transition from SHUTDOWN to TIDYING is less
    341      * straightforward than you'd like because the queue may become
    342      * empty after non-empty and vice versa during SHUTDOWN state, but
    343      * we can only terminate if, after seeing that it is empty, we see
    344      * that workerCount is 0 (which sometimes entails a recheck -- see
    345      * below).
    346      */
    347     private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    348     private static final int COUNT_BITS = Integer.SIZE - 3;
    349     private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
    350 
    351     // runState is stored in the high-order bits
    352     private static final int RUNNING    = -1 << COUNT_BITS;
    353     private static final int SHUTDOWN   =  0 << COUNT_BITS;
    354     private static final int STOP       =  1 << COUNT_BITS;
    355     private static final int TIDYING    =  2 << COUNT_BITS;
    356     private static final int TERMINATED =  3 << COUNT_BITS;
    357 
    358     // Packing and unpacking ctl
    359     private static int runStateOf(int c)     { return c & ~CAPACITY; }
    360     private static int workerCountOf(int c)  { return c & CAPACITY; }
    361     private static int ctlOf(int rs, int wc) { return rs | wc; }
    362 
    363     /*
    364      * Bit field accessors that don't require unpacking ctl.
    365      * These depend on the bit layout and on workerCount being never negative.
    366      */
    367 
    368     private static boolean runStateLessThan(int c, int s) {
    369         return c < s;
    370     }
    371 
    372     private static boolean runStateAtLeast(int c, int s) {
    373         return c >= s;
    374     }
    375 
    376     private static boolean isRunning(int c) {
    377         return c < SHUTDOWN;
    378     }
    379 
    380     /**
    381      * Attempts to CAS-increment the workerCount field of ctl.
    382      */
    383     private boolean compareAndIncrementWorkerCount(int expect) {
    384         return ctl.compareAndSet(expect, expect + 1);
    385     }
    386 
    387     /**
    388      * Attempts to CAS-decrement the workerCount field of ctl.
    389      */
    390     private boolean compareAndDecrementWorkerCount(int expect) {
    391         return ctl.compareAndSet(expect, expect - 1);
    392     }
    393 
    394     /**
    395      * Decrements the workerCount field of ctl. This is called only on
    396      * abrupt termination of a thread (see processWorkerExit). Other
    397      * decrements are performed within getTask.
    398      */
    399     private void decrementWorkerCount() {
    400         do {} while (! compareAndDecrementWorkerCount(ctl.get()));
    401     }
    402 
    403     /**
    404      * The queue used for holding tasks and handing off to worker
    405      * threads.  We do not require that workQueue.poll() returning
    406      * null necessarily means that workQueue.isEmpty(), so rely
    407      * solely on isEmpty to see if the queue is empty (which we must
    408      * do for example when deciding whether to transition from
    409      * SHUTDOWN to TIDYING).  This accommodates special-purpose
    410      * queues such as DelayQueues for which poll() is allowed to
    411      * return null even if it may later return non-null when delays
    412      * expire.
    413      */
    414     private final BlockingQueue<Runnable> workQueue;
    415 
    416     /**
    417      * Lock held on access to workers set and related bookkeeping.
    418      * While we could use a concurrent set of some sort, it turns out
    419      * to be generally preferable to use a lock. Among the reasons is
    420      * that this serializes interruptIdleWorkers, which avoids
    421      * unnecessary interrupt storms, especially during shutdown.
    422      * Otherwise exiting threads would concurrently interrupt those
    423      * that have not yet interrupted. It also simplifies some of the
    424      * associated statistics bookkeeping of largestPoolSize etc. We
    425      * also hold mainLock on shutdown and shutdownNow, for the sake of
    426      * ensuring workers set is stable while separately checking
    427      * permission to interrupt and actually interrupting.
    428      */
    429     private final ReentrantLock mainLock = new ReentrantLock();
    430 
    431     /**
    432      * Set containing all worker threads in pool. Accessed only when
    433      * holding mainLock.
    434      */
    435     private final HashSet<Worker> workers = new HashSet<Worker>();
    436 
    437     /**
    438      * Wait condition to support awaitTermination
    439      */
    440     private final Condition termination = mainLock.newCondition();
    441 
    442     /**
    443      * Tracks largest attained pool size. Accessed only under
    444      * mainLock.
    445      */
    446     private int largestPoolSize;
    447 
    448     /**
    449      * Counter for completed tasks. Updated only on termination of
    450      * worker threads. Accessed only under mainLock.
    451      */
    452     private long completedTaskCount;
    453 
    454     /*
    455      * All user control parameters are declared as volatiles so that
    456      * ongoing actions are based on freshest values, but without need
    457      * for locking, since no internal invariants depend on them
    458      * changing synchronously with respect to other actions.
    459      */
    460 
    461     /**
    462      * Factory for new threads. All threads are created using this
    463      * factory (via method addWorker).  All callers must be prepared
    464      * for addWorker to fail, which may reflect a system or user's
    465      * policy limiting the number of threads.  Even though it is not
    466      * treated as an error, failure to create threads may result in
    467      * new tasks being rejected or existing ones remaining stuck in
    468      * the queue.
    469      *
    470      * We go further and preserve pool invariants even in the face of
    471      * errors such as OutOfMemoryError, that might be thrown while
    472      * trying to create threads.  Such errors are rather common due to
    473      * the need to allocate a native stack in Thread.start, and users
    474      * will want to perform clean pool shutdown to clean up.  There
    475      * will likely be enough memory available for the cleanup code to
    476      * complete without encountering yet another OutOfMemoryError.
    477      */
    478     private volatile ThreadFactory threadFactory;
    479 
    480     /**
    481      * Handler called when saturated or shutdown in execute.
    482      */
    483     private volatile RejectedExecutionHandler handler;
    484 
    485     /**
    486      * Timeout in nanoseconds for idle threads waiting for work.
    487      * Threads use this timeout when there are more than corePoolSize
    488      * present or if allowCoreThreadTimeOut. Otherwise they wait
    489      * forever for new work.
    490      */
    491     private volatile long keepAliveTime;
    492 
    493     /**
    494      * If false (default), core threads stay alive even when idle.
    495      * If true, core threads use keepAliveTime to time out waiting
    496      * for work.
    497      */
    498     private volatile boolean allowCoreThreadTimeOut;
    499 
    500     /**
    501      * Core pool size is the minimum number of workers to keep alive
    502      * (and not allow to time out etc) unless allowCoreThreadTimeOut
    503      * is set, in which case the minimum is zero.
    504      */
    505     private volatile int corePoolSize;
    506 
    507     /**
    508      * Maximum pool size. Note that the actual maximum is internally
    509      * bounded by CAPACITY.
    510      */
    511     private volatile int maximumPoolSize;
    512 
    513     /**
    514      * The default rejected execution handler
    515      */
    516     private static final RejectedExecutionHandler defaultHandler =
    517         new AbortPolicy();
    518 
    519     /**
    520      * Permission required for callers of shutdown and shutdownNow.
    521      * We additionally require (see checkShutdownAccess) that callers
    522      * have permission to actually interrupt threads in the worker set
    523      * (as governed by Thread.interrupt, which relies on
    524      * ThreadGroup.checkAccess, which in turn relies on
    525      * SecurityManager.checkAccess). Shutdowns are attempted only if
    526      * these checks pass.
    527      *
    528      * All actual invocations of Thread.interrupt (see
    529      * interruptIdleWorkers and interruptWorkers) ignore
    530      * SecurityExceptions, meaning that the attempted interrupts
    531      * silently fail. In the case of shutdown, they should not fail
    532      * unless the SecurityManager has inconsistent policies, sometimes
    533      * allowing access to a thread and sometimes not. In such cases,
    534      * failure to actually interrupt threads may disable or delay full
    535      * termination. Other uses of interruptIdleWorkers are advisory,
    536      * and failure to actually interrupt will merely delay response to
    537      * configuration changes so is not handled exceptionally.
    538      */
    539     private static final RuntimePermission shutdownPerm =
    540         new RuntimePermission("modifyThread");
    541 
    542     /**
    543      * Class Worker mainly maintains interrupt control state for
    544      * threads running tasks, along with other minor bookkeeping.
    545      * This class opportunistically extends AbstractQueuedSynchronizer
    546      * to simplify acquiring and releasing a lock surrounding each
    547      * task execution.  This protects against interrupts that are
    548      * intended to wake up a worker thread waiting for a task from
    549      * instead interrupting a task being run.  We implement a simple
    550      * non-reentrant mutual exclusion lock rather than use
    551      * ReentrantLock because we do not want worker tasks to be able to
    552      * reacquire the lock when they invoke pool control methods like
    553      * setCorePoolSize.  Additionally, to suppress interrupts until
    554      * the thread actually starts running tasks, we initialize lock
    555      * state to a negative value, and clear it upon start (in
    556      * runWorker).
    557      */
    558     private final class Worker
    559         extends AbstractQueuedSynchronizer
    560         implements Runnable
    561     {
    562         /**
    563          * This class will never be serialized, but we provide a
    564          * serialVersionUID to suppress a javac warning.
    565          */
    566         private static final long serialVersionUID = 6138294804551838833L;
    567 
    568         /** Thread this worker is running in.  Null if factory fails. */
    569         final Thread thread;
    570         /** Initial task to run.  Possibly null. */
    571         Runnable firstTask;
    572         /** Per-thread task counter */
    573         volatile long completedTasks;
    574 
    575         /**
    576          * Creates with given first task and thread from ThreadFactory.
    577          * @param firstTask the first task (null if none)
    578          */
    579         Worker(Runnable firstTask) {
    580             setState(-1); // inhibit interrupts until runWorker
    581             this.firstTask = firstTask;
    582             this.thread = getThreadFactory().newThread(this);
    583         }
    584 
    585         /** Delegates main run loop to outer runWorker  */
    586         public void run() {
    587             runWorker(this);
    588         }
    589 
    590         // Lock methods
    591         //
    592         // The value 0 represents the unlocked state.
    593         // The value 1 represents the locked state.
    594 
    595         protected boolean isHeldExclusively() {
    596             return getState() != 0;
    597         }
    598 
    599         protected boolean tryAcquire(int unused) {
    600             if (compareAndSetState(0, 1)) {
    601                 setExclusiveOwnerThread(Thread.currentThread());
    602                 return true;
    603             }
    604             return false;
    605         }
    606 
    607         protected boolean tryRelease(int unused) {
    608             setExclusiveOwnerThread(null);
    609             setState(0);
    610             return true;
    611         }
    612 
    613         public void lock()        { acquire(1); }
    614         public boolean tryLock()  { return tryAcquire(1); }
    615         public void unlock()      { release(1); }
    616         public boolean isLocked() { return isHeldExclusively(); }
    617 
    618         void interruptIfStarted() {
    619             Thread t;
    620             if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
    621                 try {
    622                     t.interrupt();
    623                 } catch (SecurityException ignore) {
    624                 }
    625             }
    626         }
    627     }
    628 
    629     /*
    630      * Methods for setting control state
    631      */
    632 
    633     /**
    634      * Transitions runState to given target, or leaves it alone if
    635      * already at least the given target.
    636      *
    637      * @param targetState the desired state, either SHUTDOWN or STOP
    638      *        (but not TIDYING or TERMINATED -- use tryTerminate for that)
    639      */
    640     private void advanceRunState(int targetState) {
    641         for (;;) {
    642             int c = ctl.get();
    643             if (runStateAtLeast(c, targetState) ||
    644                 ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
    645                 break;
    646         }
    647     }
    648 
    649     /**
    650      * Transitions to TERMINATED state if either (SHUTDOWN and pool
    651      * and queue empty) or (STOP and pool empty).  If otherwise
    652      * eligible to terminate but workerCount is nonzero, interrupts an
    653      * idle worker to ensure that shutdown signals propagate. This
    654      * method must be called following any action that might make
    655      * termination possible -- reducing worker count or removing tasks
    656      * from the queue during shutdown. The method is non-private to
    657      * allow access from ScheduledThreadPoolExecutor.
    658      */
    659     final void tryTerminate() {
    660         for (;;) {
    661             int c = ctl.get();
    662             if (isRunning(c) ||
    663                 runStateAtLeast(c, TIDYING) ||
    664                 (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
    665                 return;
    666             if (workerCountOf(c) != 0) { // Eligible to terminate
    667                 interruptIdleWorkers(ONLY_ONE);
    668                 return;
    669             }
    670 
    671             final ReentrantLock mainLock = this.mainLock;
    672             mainLock.lock();
    673             try {
    674                 if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
    675                     try {
    676                         terminated();
    677                     } finally {
    678                         ctl.set(ctlOf(TERMINATED, 0));
    679                         termination.signalAll();
    680                     }
    681                     return;
    682                 }
    683             } finally {
    684                 mainLock.unlock();
    685             }
    686             // else retry on failed CAS
    687         }
    688     }
    689 
    690     /*
    691      * Methods for controlling interrupts to worker threads.
    692      */
    693 
    694     /**
    695      * If there is a security manager, makes sure caller has
    696      * permission to shut down threads in general (see shutdownPerm).
    697      * If this passes, additionally makes sure the caller is allowed
    698      * to interrupt each worker thread. This might not be true even if
    699      * first check passed, if the SecurityManager treats some threads
    700      * specially.
    701      */
    702     private void checkShutdownAccess() {
    703         SecurityManager security = System.getSecurityManager();
    704         if (security != null) {
    705             security.checkPermission(shutdownPerm);
    706             final ReentrantLock mainLock = this.mainLock;
    707             mainLock.lock();
    708             try {
    709                 for (Worker w : workers)
    710                     security.checkAccess(w.thread);
    711             } finally {
    712                 mainLock.unlock();
    713             }
    714         }
    715     }
    716 
    717     /**
    718      * Interrupts all threads, even if active. Ignores SecurityExceptions
    719      * (in which case some threads may remain uninterrupted).
    720      */
    721     private void interruptWorkers() {
    722         final ReentrantLock mainLock = this.mainLock;
    723         mainLock.lock();
    724         try {
    725             for (Worker w : workers)
    726                 w.interruptIfStarted();
    727         } finally {
    728             mainLock.unlock();
    729         }
    730     }
    731 
    732     /**
    733      * Interrupts threads that might be waiting for tasks (as
    734      * indicated by not being locked) so they can check for
    735      * termination or configuration changes. Ignores
    736      * SecurityExceptions (in which case some threads may remain
    737      * uninterrupted).
    738      *
    739      * @param onlyOne If true, interrupt at most one worker. This is
    740      * called only from tryTerminate when termination is otherwise
    741      * enabled but there are still other workers.  In this case, at
    742      * most one waiting worker is interrupted to propagate shutdown
    743      * signals in case all threads are currently waiting.
    744      * Interrupting any arbitrary thread ensures that newly arriving
    745      * workers since shutdown began will also eventually exit.
    746      * To guarantee eventual termination, it suffices to always
    747      * interrupt only one idle worker, but shutdown() interrupts all
    748      * idle workers so that redundant workers exit promptly, not
    749      * waiting for a straggler task to finish.
    750      */
    751     private void interruptIdleWorkers(boolean onlyOne) {
    752         final ReentrantLock mainLock = this.mainLock;
    753         mainLock.lock();
    754         try {
    755             for (Worker w : workers) {
    756                 Thread t = w.thread;
    757                 if (!t.isInterrupted() && w.tryLock()) {
    758                     try {
    759                         t.interrupt();
    760                     } catch (SecurityException ignore) {
    761                     } finally {
    762                         w.unlock();
    763                     }
    764                 }
    765                 if (onlyOne)
    766                     break;
    767             }
    768         } finally {
    769             mainLock.unlock();
    770         }
    771     }
    772 
    773     /**
    774      * Common form of interruptIdleWorkers, to avoid having to
    775      * remember what the boolean argument means.
    776      */
    777     private void interruptIdleWorkers() {
    778         interruptIdleWorkers(false);
    779     }
    780 
    781     private static final boolean ONLY_ONE = true;
    782 
    783     /*
    784      * Misc utilities, most of which are also exported to
    785      * ScheduledThreadPoolExecutor
    786      */
    787 
    788     /**
    789      * Invokes the rejected execution handler for the given command.
    790      * Package-protected for use by ScheduledThreadPoolExecutor.
    791      */
    792     final void reject(Runnable command) {
    793         handler.rejectedExecution(command, this);
    794     }
    795 
    796     /**
    797      * Performs any further cleanup following run state transition on
    798      * invocation of shutdown.  A no-op here, but used by
    799      * ScheduledThreadPoolExecutor to cancel delayed tasks.
    800      */
    801     void onShutdown() {
    802     }
    803 
    804     /**
    805      * State check needed by ScheduledThreadPoolExecutor to
    806      * enable running tasks during shutdown.
    807      *
    808      * @param shutdownOK true if should return true if SHUTDOWN
    809      */
    810     final boolean isRunningOrShutdown(boolean shutdownOK) {
    811         int rs = runStateOf(ctl.get());
    812         return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
    813     }
    814 
    815     /**
    816      * Drains the task queue into a new list, normally using
    817      * drainTo. But if the queue is a DelayQueue or any other kind of
    818      * queue for which poll or drainTo may fail to remove some
    819      * elements, it deletes them one by one.
    820      */
    821     private List<Runnable> drainQueue() {
    822         BlockingQueue<Runnable> q = workQueue;
    823         ArrayList<Runnable> taskList = new ArrayList<Runnable>();
    824         q.drainTo(taskList);
    825         if (!q.isEmpty()) {
    826             for (Runnable r : q.toArray(new Runnable[0])) {
    827                 if (q.remove(r))
    828                     taskList.add(r);
    829             }
    830         }
    831         return taskList;
    832     }
    833 
    834     /*
    835      * Methods for creating, running and cleaning up after workers
    836      */
    837 
    838     /**
    839      * Checks if a new worker can be added with respect to current
    840      * pool state and the given bound (either core or maximum). If so,
    841      * the worker count is adjusted accordingly, and, if possible, a
    842      * new worker is created and started, running firstTask as its
    843      * first task. This method returns false if the pool is stopped or
    844      * eligible to shut down. It also returns false if the thread
    845      * factory fails to create a thread when asked.  If the thread
    846      * creation fails, either due to the thread factory returning
    847      * null, or due to an exception (typically OutOfMemoryError in
    848      * Thread.start()), we roll back cleanly.
    849      *
    850      * @param firstTask the task the new thread should run first (or
    851      * null if none). Workers are created with an initial first task
    852      * (in method execute()) to bypass queuing when there are fewer
    853      * than corePoolSize threads (in which case we always start one),
    854      * or when the queue is full (in which case we must bypass queue).
    855      * Initially idle threads are usually created via
    856      * prestartCoreThread or to replace other dying workers.
    857      *
    858      * @param core if true use corePoolSize as bound, else
    859      * maximumPoolSize. (A boolean indicator is used here rather than a
    860      * value to ensure reads of fresh values after checking other pool
    861      * state).
    862      * @return true if successful
    863      */
    864     private boolean addWorker(Runnable firstTask, boolean core) {
    865         retry:
    866         for (;;) {
    867             int c = ctl.get();
    868             int rs = runStateOf(c);
    869 
    870             // Check if queue empty only if necessary.
    871             if (rs >= SHUTDOWN &&
    872                 ! (rs == SHUTDOWN &&
    873                    firstTask == null &&
    874                    ! workQueue.isEmpty()))
    875                 return false;
    876 
    877             for (;;) {
    878                 int wc = workerCountOf(c);
    879                 if (wc >= CAPACITY ||
    880                     wc >= (core ? corePoolSize : maximumPoolSize))
    881                     return false;
    882                 if (compareAndIncrementWorkerCount(c))
    883                     break retry;
    884                 c = ctl.get();  // Re-read ctl
    885                 if (runStateOf(c) != rs)
    886                     continue retry;
    887                 // else CAS failed due to workerCount change; retry inner loop
    888             }
    889         }
    890 
    891         boolean workerStarted = false;
    892         boolean workerAdded = false;
    893         Worker w = null;
    894         try {
    895             w = new Worker(firstTask);
    896             final Thread t = w.thread;
    897             if (t != null) {
    898                 final ReentrantLock mainLock = this.mainLock;
    899                 mainLock.lock();
    900                 try {
    901                     // Recheck while holding lock.
    902                     // Back out on ThreadFactory failure or if
    903                     // shut down before lock acquired.
    904                     int rs = runStateOf(ctl.get());
    905 
    906                     if (rs < SHUTDOWN ||
    907                         (rs == SHUTDOWN && firstTask == null)) {
    908                         if (t.isAlive()) // precheck that t is startable
    909                             throw new IllegalThreadStateException();
    910                         workers.add(w);
    911                         int s = workers.size();
    912                         if (s > largestPoolSize)
    913                             largestPoolSize = s;
    914                         workerAdded = true;
    915                     }
    916                 } finally {
    917                     mainLock.unlock();
    918                 }
    919                 if (workerAdded) {
    920                     t.start();
    921                     workerStarted = true;
    922                 }
    923             }
    924         } finally {
    925             if (! workerStarted)
    926                 addWorkerFailed(w);
    927         }
    928         return workerStarted;
    929     }
    930 
    931     /**
    932      * Rolls back the worker thread creation.
    933      * - removes worker from workers, if present
    934      * - decrements worker count
    935      * - rechecks for termination, in case the existence of this
    936      *   worker was holding up termination
    937      */
    938     private void addWorkerFailed(Worker w) {
    939         final ReentrantLock mainLock = this.mainLock;
    940         mainLock.lock();
    941         try {
    942             if (w != null)
    943                 workers.remove(w);
    944             decrementWorkerCount();
    945             tryTerminate();
    946         } finally {
    947             mainLock.unlock();
    948         }
    949     }
    950 
    951     /**
    952      * Performs cleanup and bookkeeping for a dying worker. Called
    953      * only from worker threads. Unless completedAbruptly is set,
    954      * assumes that workerCount has already been adjusted to account
    955      * for exit.  This method removes thread from worker set, and
    956      * possibly terminates the pool or replaces the worker if either
    957      * it exited due to user task exception or if fewer than
    958      * corePoolSize workers are running or queue is non-empty but
    959      * there are no workers.
    960      *
    961      * @param w the worker
    962      * @param completedAbruptly if the worker died due to user exception
    963      */
    964     private void processWorkerExit(Worker w, boolean completedAbruptly) {
    965         if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
    966             decrementWorkerCount();
    967 
    968         final ReentrantLock mainLock = this.mainLock;
    969         mainLock.lock();
    970         try {
    971             completedTaskCount += w.completedTasks;
    972             workers.remove(w);
    973         } finally {
    974             mainLock.unlock();
    975         }
    976 
    977         tryTerminate();
    978 
    979         int c = ctl.get();
    980         if (runStateLessThan(c, STOP)) {
    981             if (!completedAbruptly) {
    982                 int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
    983                 if (min == 0 && ! workQueue.isEmpty())
    984                     min = 1;
    985                 if (workerCountOf(c) >= min)
    986                     return; // replacement not needed
    987             }
    988             addWorker(null, false);
    989         }
    990     }
    991 
    992     /**
    993      * Performs blocking or timed wait for a task, depending on
    994      * current configuration settings, or returns null if this worker
    995      * must exit because of any of:
    996      * 1. There are more than maximumPoolSize workers (due to
    997      *    a call to setMaximumPoolSize).
    998      * 2. The pool is stopped.
    999      * 3. The pool is shutdown and the queue is empty.
   1000      * 4. This worker timed out waiting for a task, and timed-out
   1001      *    workers are subject to termination (that is,
   1002      *    {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
   1003      *    both before and after the timed wait, and if the queue is
   1004      *    non-empty, this worker is not the last thread in the pool.
   1005      *
   1006      * @return task, or null if the worker must exit, in which case
   1007      *         workerCount is decremented
   1008      */
   1009     private Runnable getTask() {
   1010         boolean timedOut = false; // Did the last poll() time out?
   1011 
   1012         for (;;) {
   1013             int c = ctl.get();
   1014             int rs = runStateOf(c);
   1015 
   1016             // Check if queue empty only if necessary.
   1017             if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
   1018                 decrementWorkerCount();
   1019                 return null;
   1020             }
   1021 
   1022             int wc = workerCountOf(c);
   1023 
   1024             // Are workers subject to culling?
   1025             boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
   1026 
   1027             if ((wc > maximumPoolSize || (timed && timedOut))
   1028                 && (wc > 1 || workQueue.isEmpty())) {
   1029                 if (compareAndDecrementWorkerCount(c))
   1030                     return null;
   1031                 continue;
   1032             }
   1033 
   1034             try {
   1035                 Runnable r = timed ?
   1036                     workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
   1037                     workQueue.take();
   1038                 if (r != null)
   1039                     return r;
   1040                 timedOut = true;
   1041             } catch (InterruptedException retry) {
   1042                 timedOut = false;
   1043             }
   1044         }
   1045     }
   1046 
   1047     /**
   1048      * Main worker run loop.  Repeatedly gets tasks from queue and
   1049      * executes them, while coping with a number of issues:
   1050      *
   1051      * 1. We may start out with an initial task, in which case we
   1052      * don't need to get the first one. Otherwise, as long as pool is
   1053      * running, we get tasks from getTask. If it returns null then the
   1054      * worker exits due to changed pool state or configuration
   1055      * parameters.  Other exits result from exception throws in
   1056      * external code, in which case completedAbruptly holds, which
   1057      * usually leads processWorkerExit to replace this thread.
   1058      *
   1059      * 2. Before running any task, the lock is acquired to prevent
   1060      * other pool interrupts while the task is executing, and then we
   1061      * ensure that unless pool is stopping, this thread does not have
   1062      * its interrupt set.
   1063      *
   1064      * 3. Each task run is preceded by a call to beforeExecute, which
   1065      * might throw an exception, in which case we cause thread to die
   1066      * (breaking loop with completedAbruptly true) without processing
   1067      * the task.
   1068      *
   1069      * 4. Assuming beforeExecute completes normally, we run the task,
   1070      * gathering any of its thrown exceptions to send to afterExecute.
   1071      * We separately handle RuntimeException, Error (both of which the
   1072      * specs guarantee that we trap) and arbitrary Throwables.
   1073      * Because we cannot rethrow Throwables within Runnable.run, we
   1074      * wrap them within Errors on the way out (to the thread's
   1075      * UncaughtExceptionHandler).  Any thrown exception also
   1076      * conservatively causes thread to die.
   1077      *
   1078      * 5. After task.run completes, we call afterExecute, which may
   1079      * also throw an exception, which will also cause thread to
   1080      * die. According to JLS Sec 14.20, this exception is the one that
   1081      * will be in effect even if task.run throws.
   1082      *
   1083      * The net effect of the exception mechanics is that afterExecute
   1084      * and the thread's UncaughtExceptionHandler have as accurate
   1085      * information as we can provide about any problems encountered by
   1086      * user code.
   1087      *
   1088      * @param w the worker
   1089      */
   1090     final void runWorker(Worker w) {
   1091         Thread wt = Thread.currentThread();
   1092         Runnable task = w.firstTask;
   1093         w.firstTask = null;
   1094         w.unlock(); // allow interrupts
   1095         boolean completedAbruptly = true;
   1096         try {
   1097             while (task != null || (task = getTask()) != null) {
   1098                 w.lock();
   1099                 // If pool is stopping, ensure thread is interrupted;
   1100                 // if not, ensure thread is not interrupted.  This
   1101                 // requires a recheck in second case to deal with
   1102                 // shutdownNow race while clearing interrupt
   1103                 if ((runStateAtLeast(ctl.get(), STOP) ||
   1104                      (Thread.interrupted() &&
   1105                       runStateAtLeast(ctl.get(), STOP))) &&
   1106                     !wt.isInterrupted())
   1107                     wt.interrupt();
   1108                 try {
   1109                     beforeExecute(wt, task);
   1110                     Throwable thrown = null;
   1111                     try {
   1112                         task.run();
   1113                     } catch (RuntimeException x) {
   1114                         thrown = x; throw x;
   1115                     } catch (Error x) {
   1116                         thrown = x; throw x;
   1117                     } catch (Throwable x) {
   1118                         thrown = x; throw new Error(x);
   1119                     } finally {
   1120                         afterExecute(task, thrown);
   1121                     }
   1122                 } finally {
   1123                     task = null;
   1124                     w.completedTasks++;
   1125                     w.unlock();
   1126                 }
   1127             }
   1128             completedAbruptly = false;
   1129         } finally {
   1130             processWorkerExit(w, completedAbruptly);
   1131         }
   1132     }
   1133 
   1134     // Public constructors and methods
   1135 
   1136     /**
   1137      * Creates a new {@code ThreadPoolExecutor} with the given initial
   1138      * parameters and default thread factory and rejected execution handler.
   1139      * It may be more convenient to use one of the {@link Executors} factory
   1140      * methods instead of this general purpose constructor.
   1141      *
   1142      * @param corePoolSize the number of threads to keep in the pool, even
   1143      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
   1144      * @param maximumPoolSize the maximum number of threads to allow in the
   1145      *        pool
   1146      * @param keepAliveTime when the number of threads is greater than
   1147      *        the core, this is the maximum time that excess idle threads
   1148      *        will wait for new tasks before terminating.
   1149      * @param unit the time unit for the {@code keepAliveTime} argument
   1150      * @param workQueue the queue to use for holding tasks before they are
   1151      *        executed.  This queue will hold only the {@code Runnable}
   1152      *        tasks submitted by the {@code execute} method.
   1153      * @throws IllegalArgumentException if one of the following holds:<br>
   1154      *         {@code corePoolSize < 0}<br>
   1155      *         {@code keepAliveTime < 0}<br>
   1156      *         {@code maximumPoolSize <= 0}<br>
   1157      *         {@code maximumPoolSize < corePoolSize}
   1158      * @throws NullPointerException if {@code workQueue} is null
   1159      */
   1160     public ThreadPoolExecutor(int corePoolSize,
   1161                               int maximumPoolSize,
   1162                               long keepAliveTime,
   1163                               TimeUnit unit,
   1164                               BlockingQueue<Runnable> workQueue) {
   1165         this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
   1166              Executors.defaultThreadFactory(), defaultHandler);
   1167     }
   1168 
   1169     /**
   1170      * Creates a new {@code ThreadPoolExecutor} with the given initial
   1171      * parameters and default rejected execution handler.
   1172      *
   1173      * @param corePoolSize the number of threads to keep in the pool, even
   1174      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
   1175      * @param maximumPoolSize the maximum number of threads to allow in the
   1176      *        pool
   1177      * @param keepAliveTime when the number of threads is greater than
   1178      *        the core, this is the maximum time that excess idle threads
   1179      *        will wait for new tasks before terminating.
   1180      * @param unit the time unit for the {@code keepAliveTime} argument
   1181      * @param workQueue the queue to use for holding tasks before they are
   1182      *        executed.  This queue will hold only the {@code Runnable}
   1183      *        tasks submitted by the {@code execute} method.
   1184      * @param threadFactory the factory to use when the executor
   1185      *        creates a new thread
   1186      * @throws IllegalArgumentException if one of the following holds:<br>
   1187      *         {@code corePoolSize < 0}<br>
   1188      *         {@code keepAliveTime < 0}<br>
   1189      *         {@code maximumPoolSize <= 0}<br>
   1190      *         {@code maximumPoolSize < corePoolSize}
   1191      * @throws NullPointerException if {@code workQueue}
   1192      *         or {@code threadFactory} is null
   1193      */
   1194     public ThreadPoolExecutor(int corePoolSize,
   1195                               int maximumPoolSize,
   1196                               long keepAliveTime,
   1197                               TimeUnit unit,
   1198                               BlockingQueue<Runnable> workQueue,
   1199                               ThreadFactory threadFactory) {
   1200         this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
   1201              threadFactory, defaultHandler);
   1202     }
   1203 
   1204     /**
   1205      * Creates a new {@code ThreadPoolExecutor} with the given initial
   1206      * parameters and default thread factory.
   1207      *
   1208      * @param corePoolSize the number of threads to keep in the pool, even
   1209      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
   1210      * @param maximumPoolSize the maximum number of threads to allow in the
   1211      *        pool
   1212      * @param keepAliveTime when the number of threads is greater than
   1213      *        the core, this is the maximum time that excess idle threads
   1214      *        will wait for new tasks before terminating.
   1215      * @param unit the time unit for the {@code keepAliveTime} argument
   1216      * @param workQueue the queue to use for holding tasks before they are
   1217      *        executed.  This queue will hold only the {@code Runnable}
   1218      *        tasks submitted by the {@code execute} method.
   1219      * @param handler the handler to use when execution is blocked
   1220      *        because the thread bounds and queue capacities are reached
   1221      * @throws IllegalArgumentException if one of the following holds:<br>
   1222      *         {@code corePoolSize < 0}<br>
   1223      *         {@code keepAliveTime < 0}<br>
   1224      *         {@code maximumPoolSize <= 0}<br>
   1225      *         {@code maximumPoolSize < corePoolSize}
   1226      * @throws NullPointerException if {@code workQueue}
   1227      *         or {@code handler} is null
   1228      */
   1229     public ThreadPoolExecutor(int corePoolSize,
   1230                               int maximumPoolSize,
   1231                               long keepAliveTime,
   1232                               TimeUnit unit,
   1233                               BlockingQueue<Runnable> workQueue,
   1234                               RejectedExecutionHandler handler) {
   1235         this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
   1236              Executors.defaultThreadFactory(), handler);
   1237     }
   1238 
   1239     /**
   1240      * Creates a new {@code ThreadPoolExecutor} with the given initial
   1241      * parameters.
   1242      *
   1243      * @param corePoolSize the number of threads to keep in the pool, even
   1244      *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
   1245      * @param maximumPoolSize the maximum number of threads to allow in the
   1246      *        pool
   1247      * @param keepAliveTime when the number of threads is greater than
   1248      *        the core, this is the maximum time that excess idle threads
   1249      *        will wait for new tasks before terminating.
   1250      * @param unit the time unit for the {@code keepAliveTime} argument
   1251      * @param workQueue the queue to use for holding tasks before they are
   1252      *        executed.  This queue will hold only the {@code Runnable}
   1253      *        tasks submitted by the {@code execute} method.
   1254      * @param threadFactory the factory to use when the executor
   1255      *        creates a new thread
   1256      * @param handler the handler to use when execution is blocked
   1257      *        because the thread bounds and queue capacities are reached
   1258      * @throws IllegalArgumentException if one of the following holds:<br>
   1259      *         {@code corePoolSize < 0}<br>
   1260      *         {@code keepAliveTime < 0}<br>
   1261      *         {@code maximumPoolSize <= 0}<br>
   1262      *         {@code maximumPoolSize < corePoolSize}
   1263      * @throws NullPointerException if {@code workQueue}
   1264      *         or {@code threadFactory} or {@code handler} is null
   1265      */
   1266     public ThreadPoolExecutor(int corePoolSize,
   1267                               int maximumPoolSize,
   1268                               long keepAliveTime,
   1269                               TimeUnit unit,
   1270                               BlockingQueue<Runnable> workQueue,
   1271                               ThreadFactory threadFactory,
   1272                               RejectedExecutionHandler handler) {
   1273         if (corePoolSize < 0 ||
   1274             maximumPoolSize <= 0 ||
   1275             maximumPoolSize < corePoolSize ||
   1276             keepAliveTime < 0)
   1277             throw new IllegalArgumentException();
   1278         if (workQueue == null || threadFactory == null || handler == null)
   1279             throw new NullPointerException();
   1280         this.corePoolSize = corePoolSize;
   1281         this.maximumPoolSize = maximumPoolSize;
   1282         this.workQueue = workQueue;
   1283         this.keepAliveTime = unit.toNanos(keepAliveTime);
   1284         this.threadFactory = threadFactory;
   1285         this.handler = handler;
   1286     }
   1287 
   1288     /**
   1289      * Executes the given task sometime in the future.  The task
   1290      * may execute in a new thread or in an existing pooled thread.
   1291      *
   1292      * If the task cannot be submitted for execution, either because this
   1293      * executor has been shutdown or because its capacity has been reached,
   1294      * the task is handled by the current {@code RejectedExecutionHandler}.
   1295      *
   1296      * @param command the task to execute
   1297      * @throws RejectedExecutionException at discretion of
   1298      *         {@code RejectedExecutionHandler}, if the task
   1299      *         cannot be accepted for execution
   1300      * @throws NullPointerException if {@code command} is null
   1301      */
   1302     public void execute(Runnable command) {
   1303         if (command == null)
   1304             throw new NullPointerException();
   1305         /*
   1306          * Proceed in 3 steps:
   1307          *
   1308          * 1. If fewer than corePoolSize threads are running, try to
   1309          * start a new thread with the given command as its first
   1310          * task.  The call to addWorker atomically checks runState and
   1311          * workerCount, and so prevents false alarms that would add
   1312          * threads when it shouldn't, by returning false.
   1313          *
   1314          * 2. If a task can be successfully queued, then we still need
   1315          * to double-check whether we should have added a thread
   1316          * (because existing ones died since last checking) or that
   1317          * the pool shut down since entry into this method. So we
   1318          * recheck state and if necessary roll back the enqueuing if
   1319          * stopped, or start a new thread if there are none.
   1320          *
   1321          * 3. If we cannot queue task, then we try to add a new
   1322          * thread.  If it fails, we know we are shut down or saturated
   1323          * and so reject the task.
   1324          */
   1325         int c = ctl.get();
   1326         if (workerCountOf(c) < corePoolSize) {
   1327             if (addWorker(command, true))
   1328                 return;
   1329             c = ctl.get();
   1330         }
   1331         if (isRunning(c) && workQueue.offer(command)) {
   1332             int recheck = ctl.get();
   1333             if (! isRunning(recheck) && remove(command))
   1334                 reject(command);
   1335             else if (workerCountOf(recheck) == 0)
   1336                 addWorker(null, false);
   1337         }
   1338         else if (!addWorker(command, false))
   1339             reject(command);
   1340     }
   1341 
   1342     /**
   1343      * Initiates an orderly shutdown in which previously submitted
   1344      * tasks are executed, but no new tasks will be accepted.
   1345      * Invocation has no additional effect if already shut down.
   1346      *
   1347      * <p>This method does not wait for previously submitted tasks to
   1348      * complete execution.  Use {@link #awaitTermination awaitTermination}
   1349      * to do that.
   1350      */
   1351     public void shutdown() {
   1352         final ReentrantLock mainLock = this.mainLock;
   1353         mainLock.lock();
   1354         try {
   1355             checkShutdownAccess();
   1356             advanceRunState(SHUTDOWN);
   1357             interruptIdleWorkers();
   1358             onShutdown(); // hook for ScheduledThreadPoolExecutor
   1359         } finally {
   1360             mainLock.unlock();
   1361         }
   1362         tryTerminate();
   1363     }
   1364 
   1365     /**
   1366      * Attempts to stop all actively executing tasks, halts the
   1367      * processing of waiting tasks, and returns a list of the tasks
   1368      * that were awaiting execution. These tasks are drained (removed)
   1369      * from the task queue upon return from this method.
   1370      *
   1371      * <p>This method does not wait for actively executing tasks to
   1372      * terminate.  Use {@link #awaitTermination awaitTermination} to
   1373      * do that.
   1374      *
   1375      * <p>There are no guarantees beyond best-effort attempts to stop
   1376      * processing actively executing tasks.  This implementation
   1377      * cancels tasks via {@link Thread#interrupt}, so any task that
   1378      * fails to respond to interrupts may never terminate.
   1379      */
   1380     public List<Runnable> shutdownNow() {
   1381         List<Runnable> tasks;
   1382         final ReentrantLock mainLock = this.mainLock;
   1383         mainLock.lock();
   1384         try {
   1385             checkShutdownAccess();
   1386             advanceRunState(STOP);
   1387             interruptWorkers();
   1388             tasks = drainQueue();
   1389         } finally {
   1390             mainLock.unlock();
   1391         }
   1392         tryTerminate();
   1393         return tasks;
   1394     }
   1395 
   1396     public boolean isShutdown() {
   1397         return ! isRunning(ctl.get());
   1398     }
   1399 
   1400     /**
   1401      * Returns true if this executor is in the process of terminating
   1402      * after {@link #shutdown} or {@link #shutdownNow} but has not
   1403      * completely terminated.  This method may be useful for
   1404      * debugging. A return of {@code true} reported a sufficient
   1405      * period after shutdown may indicate that submitted tasks have
   1406      * ignored or suppressed interruption, causing this executor not
   1407      * to properly terminate.
   1408      *
   1409      * @return {@code true} if terminating but not yet terminated
   1410      */
   1411     public boolean isTerminating() {
   1412         int c = ctl.get();
   1413         return ! isRunning(c) && runStateLessThan(c, TERMINATED);
   1414     }
   1415 
   1416     public boolean isTerminated() {
   1417         return runStateAtLeast(ctl.get(), TERMINATED);
   1418     }
   1419 
   1420     public boolean awaitTermination(long timeout, TimeUnit unit)
   1421         throws InterruptedException {
   1422         long nanos = unit.toNanos(timeout);
   1423         final ReentrantLock mainLock = this.mainLock;
   1424         mainLock.lock();
   1425         try {
   1426             for (;;) {
   1427                 if (runStateAtLeast(ctl.get(), TERMINATED))
   1428                     return true;
   1429                 if (nanos <= 0)
   1430                     return false;
   1431                 nanos = termination.awaitNanos(nanos);
   1432             }
   1433         } finally {
   1434             mainLock.unlock();
   1435         }
   1436     }
   1437 
   1438     /**
   1439      * Invokes {@code shutdown} when this executor is no longer
   1440      * referenced and it has no threads.
   1441      */
   1442     protected void finalize() {
   1443         shutdown();
   1444     }
   1445 
   1446     /**
   1447      * Sets the thread factory used to create new threads.
   1448      *
   1449      * @param threadFactory the new thread factory
   1450      * @throws NullPointerException if threadFactory is null
   1451      * @see #getThreadFactory
   1452      */
   1453     public void setThreadFactory(ThreadFactory threadFactory) {
   1454         if (threadFactory == null)
   1455             throw new NullPointerException();
   1456         this.threadFactory = threadFactory;
   1457     }
   1458 
   1459     /**
   1460      * Returns the thread factory used to create new threads.
   1461      *
   1462      * @return the current thread factory
   1463      * @see #setThreadFactory(ThreadFactory)
   1464      */
   1465     public ThreadFactory getThreadFactory() {
   1466         return threadFactory;
   1467     }
   1468 
   1469     /**
   1470      * Sets a new handler for unexecutable tasks.
   1471      *
   1472      * @param handler the new handler
   1473      * @throws NullPointerException if handler is null
   1474      * @see #getRejectedExecutionHandler
   1475      */
   1476     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
   1477         if (handler == null)
   1478             throw new NullPointerException();
   1479         this.handler = handler;
   1480     }
   1481 
   1482     /**
   1483      * Returns the current handler for unexecutable tasks.
   1484      *
   1485      * @return the current handler
   1486      * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
   1487      */
   1488     public RejectedExecutionHandler getRejectedExecutionHandler() {
   1489         return handler;
   1490     }
   1491 
   1492     /**
   1493      * Sets the core number of threads.  This overrides any value set
   1494      * in the constructor.  If the new value is smaller than the
   1495      * current value, excess existing threads will be terminated when
   1496      * they next become idle.  If larger, new threads will, if needed,
   1497      * be started to execute any queued tasks.
   1498      *
   1499      * @param corePoolSize the new core size
   1500      * @throws IllegalArgumentException if {@code corePoolSize < 0}
   1501      * @see #getCorePoolSize
   1502      */
   1503     public void setCorePoolSize(int corePoolSize) {
   1504         if (corePoolSize < 0)
   1505             throw new IllegalArgumentException();
   1506         int delta = corePoolSize - this.corePoolSize;
   1507         this.corePoolSize = corePoolSize;
   1508         if (workerCountOf(ctl.get()) > corePoolSize)
   1509             interruptIdleWorkers();
   1510         else if (delta > 0) {
   1511             // We don't really know how many new threads are "needed".
   1512             // As a heuristic, prestart enough new workers (up to new
   1513             // core size) to handle the current number of tasks in
   1514             // queue, but stop if queue becomes empty while doing so.
   1515             int k = Math.min(delta, workQueue.size());
   1516             while (k-- > 0 && addWorker(null, true)) {
   1517                 if (workQueue.isEmpty())
   1518                     break;
   1519             }
   1520         }
   1521     }
   1522 
   1523     /**
   1524      * Returns the core number of threads.
   1525      *
   1526      * @return the core number of threads
   1527      * @see #setCorePoolSize
   1528      */
   1529     public int getCorePoolSize() {
   1530         return corePoolSize;
   1531     }
   1532 
   1533     /**
   1534      * Starts a core thread, causing it to idly wait for work. This
   1535      * overrides the default policy of starting core threads only when
   1536      * new tasks are executed. This method will return {@code false}
   1537      * if all core threads have already been started.
   1538      *
   1539      * @return {@code true} if a thread was started
   1540      */
   1541     public boolean prestartCoreThread() {
   1542         return workerCountOf(ctl.get()) < corePoolSize &&
   1543             addWorker(null, true);
   1544     }
   1545 
   1546     /**
   1547      * Same as prestartCoreThread except arranges that at least one
   1548      * thread is started even if corePoolSize is 0.
   1549      */
   1550     void ensurePrestart() {
   1551         int wc = workerCountOf(ctl.get());
   1552         if (wc < corePoolSize)
   1553             addWorker(null, true);
   1554         else if (wc == 0)
   1555             addWorker(null, false);
   1556     }
   1557 
   1558     /**
   1559      * Starts all core threads, causing them to idly wait for work. This
   1560      * overrides the default policy of starting core threads only when
   1561      * new tasks are executed.
   1562      *
   1563      * @return the number of threads started
   1564      */
   1565     public int prestartAllCoreThreads() {
   1566         int n = 0;
   1567         while (addWorker(null, true))
   1568             ++n;
   1569         return n;
   1570     }
   1571 
   1572     /**
   1573      * Returns true if this pool allows core threads to time out and
   1574      * terminate if no tasks arrive within the keepAlive time, being
   1575      * replaced if needed when new tasks arrive. When true, the same
   1576      * keep-alive policy applying to non-core threads applies also to
   1577      * core threads. When false (the default), core threads are never
   1578      * terminated due to lack of incoming tasks.
   1579      *
   1580      * @return {@code true} if core threads are allowed to time out,
   1581      *         else {@code false}
   1582      *
   1583      * @since 1.6
   1584      */
   1585     public boolean allowsCoreThreadTimeOut() {
   1586         return allowCoreThreadTimeOut;
   1587     }
   1588 
   1589     /**
   1590      * Sets the policy governing whether core threads may time out and
   1591      * terminate if no tasks arrive within the keep-alive time, being
   1592      * replaced if needed when new tasks arrive. When false, core
   1593      * threads are never terminated due to lack of incoming
   1594      * tasks. When true, the same keep-alive policy applying to
   1595      * non-core threads applies also to core threads. To avoid
   1596      * continual thread replacement, the keep-alive time must be
   1597      * greater than zero when setting {@code true}. This method
   1598      * should in general be called before the pool is actively used.
   1599      *
   1600      * @param value {@code true} if should time out, else {@code false}
   1601      * @throws IllegalArgumentException if value is {@code true}
   1602      *         and the current keep-alive time is not greater than zero
   1603      *
   1604      * @since 1.6
   1605      */
   1606     public void allowCoreThreadTimeOut(boolean value) {
   1607         if (value && keepAliveTime <= 0)
   1608             throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
   1609         if (value != allowCoreThreadTimeOut) {
   1610             allowCoreThreadTimeOut = value;
   1611             if (value)
   1612                 interruptIdleWorkers();
   1613         }
   1614     }
   1615 
   1616     /**
   1617      * Sets the maximum allowed number of threads. This overrides any
   1618      * value set in the constructor. If the new value is smaller than
   1619      * the current value, excess existing threads will be
   1620      * terminated when they next become idle.
   1621      *
   1622      * @param maximumPoolSize the new maximum
   1623      * @throws IllegalArgumentException if the new maximum is
   1624      *         less than or equal to zero, or
   1625      *         less than the {@linkplain #getCorePoolSize core pool size}
   1626      * @see #getMaximumPoolSize
   1627      */
   1628     public void setMaximumPoolSize(int maximumPoolSize) {
   1629         if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
   1630             throw new IllegalArgumentException();
   1631         this.maximumPoolSize = maximumPoolSize;
   1632         if (workerCountOf(ctl.get()) > maximumPoolSize)
   1633             interruptIdleWorkers();
   1634     }
   1635 
   1636     /**
   1637      * Returns the maximum allowed number of threads.
   1638      *
   1639      * @return the maximum allowed number of threads
   1640      * @see #setMaximumPoolSize
   1641      */
   1642     public int getMaximumPoolSize() {
   1643         return maximumPoolSize;
   1644     }
   1645 
   1646     /**
   1647      * Sets the time limit for which threads may remain idle before
   1648      * being terminated.  If there are more than the core number of
   1649      * threads currently in the pool, after waiting this amount of
   1650      * time without processing a task, excess threads will be
   1651      * terminated.  This overrides any value set in the constructor.
   1652      *
   1653      * @param time the time to wait.  A time value of zero will cause
   1654      *        excess threads to terminate immediately after executing tasks.
   1655      * @param unit the time unit of the {@code time} argument
   1656      * @throws IllegalArgumentException if {@code time} less than zero or
   1657      *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
   1658      * @see #getKeepAliveTime(TimeUnit)
   1659      */
   1660     public void setKeepAliveTime(long time, TimeUnit unit) {
   1661         if (time < 0)
   1662             throw new IllegalArgumentException();
   1663         if (time == 0 && allowsCoreThreadTimeOut())
   1664             throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
   1665         long keepAliveTime = unit.toNanos(time);
   1666         long delta = keepAliveTime - this.keepAliveTime;
   1667         this.keepAliveTime = keepAliveTime;
   1668         if (delta < 0)
   1669             interruptIdleWorkers();
   1670     }
   1671 
   1672     /**
   1673      * Returns the thread keep-alive time, which is the amount of time
   1674      * that threads in excess of the core pool size may remain
   1675      * idle before being terminated.
   1676      *
   1677      * @param unit the desired time unit of the result
   1678      * @return the time limit
   1679      * @see #setKeepAliveTime(long, TimeUnit)
   1680      */
   1681     public long getKeepAliveTime(TimeUnit unit) {
   1682         return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
   1683     }
   1684 
   1685     /* User-level queue utilities */
   1686 
   1687     /**
   1688      * Returns the task queue used by this executor. Access to the
   1689      * task queue is intended primarily for debugging and monitoring.
   1690      * This queue may be in active use.  Retrieving the task queue
   1691      * does not prevent queued tasks from executing.
   1692      *
   1693      * @return the task queue
   1694      */
   1695     public BlockingQueue<Runnable> getQueue() {
   1696         return workQueue;
   1697     }
   1698 
   1699     /**
   1700      * Removes this task from the executor's internal queue if it is
   1701      * present, thus causing it not to be run if it has not already
   1702      * started.
   1703      *
   1704      * <p>This method may be useful as one part of a cancellation
   1705      * scheme.  It may fail to remove tasks that have been converted
   1706      * into other forms before being placed on the internal queue. For
   1707      * example, a task entered using {@code submit} might be
   1708      * converted into a form that maintains {@code Future} status.
   1709      * However, in such cases, method {@link #purge} may be used to
   1710      * remove those Futures that have been cancelled.
   1711      *
   1712      * @param task the task to remove
   1713      * @return {@code true} if the task was removed
   1714      */
   1715     public boolean remove(Runnable task) {
   1716         boolean removed = workQueue.remove(task);
   1717         tryTerminate(); // In case SHUTDOWN and now empty
   1718         return removed;
   1719     }
   1720 
   1721     /**
   1722      * Tries to remove from the work queue all {@link Future}
   1723      * tasks that have been cancelled. This method can be useful as a
   1724      * storage reclamation operation, that has no other impact on
   1725      * functionality. Cancelled tasks are never executed, but may
   1726      * accumulate in work queues until worker threads can actively
   1727      * remove them. Invoking this method instead tries to remove them now.
   1728      * However, this method may fail to remove tasks in
   1729      * the presence of interference by other threads.
   1730      */
   1731     public void purge() {
   1732         final BlockingQueue<Runnable> q = workQueue;
   1733         try {
   1734             Iterator<Runnable> it = q.iterator();
   1735             while (it.hasNext()) {
   1736                 Runnable r = it.next();
   1737                 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
   1738                     it.remove();
   1739             }
   1740         } catch (ConcurrentModificationException fallThrough) {
   1741             // Take slow path if we encounter interference during traversal.
   1742             // Make copy for traversal and call remove for cancelled entries.
   1743             // The slow path is more likely to be O(N*N).
   1744             for (Object r : q.toArray())
   1745                 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
   1746                     q.remove(r);
   1747         }
   1748 
   1749         tryTerminate(); // In case SHUTDOWN and now empty
   1750     }
   1751 
   1752     /* Statistics */
   1753 
   1754     /**
   1755      * Returns the current number of threads in the pool.
   1756      *
   1757      * @return the number of threads
   1758      */
   1759     public int getPoolSize() {
   1760         final ReentrantLock mainLock = this.mainLock;
   1761         mainLock.lock();
   1762         try {
   1763             // Remove rare and surprising possibility of
   1764             // isTerminated() && getPoolSize() > 0
   1765             return runStateAtLeast(ctl.get(), TIDYING) ? 0
   1766                 : workers.size();
   1767         } finally {
   1768             mainLock.unlock();
   1769         }
   1770     }
   1771 
   1772     /**
   1773      * Returns the approximate number of threads that are actively
   1774      * executing tasks.
   1775      *
   1776      * @return the number of threads
   1777      */
   1778     public int getActiveCount() {
   1779         final ReentrantLock mainLock = this.mainLock;
   1780         mainLock.lock();
   1781         try {
   1782             int n = 0;
   1783             for (Worker w : workers)
   1784                 if (w.isLocked())
   1785                     ++n;
   1786             return n;
   1787         } finally {
   1788             mainLock.unlock();
   1789         }
   1790     }
   1791 
   1792     /**
   1793      * Returns the largest number of threads that have ever
   1794      * simultaneously been in the pool.
   1795      *
   1796      * @return the number of threads
   1797      */
   1798     public int getLargestPoolSize() {
   1799         final ReentrantLock mainLock = this.mainLock;
   1800         mainLock.lock();
   1801         try {
   1802             return largestPoolSize;
   1803         } finally {
   1804             mainLock.unlock();
   1805         }
   1806     }
   1807 
   1808     /**
   1809      * Returns the approximate total number of tasks that have ever been
   1810      * scheduled for execution. Because the states of tasks and
   1811      * threads may change dynamically during computation, the returned
   1812      * value is only an approximation.
   1813      *
   1814      * @return the number of tasks
   1815      */
   1816     public long getTaskCount() {
   1817         final ReentrantLock mainLock = this.mainLock;
   1818         mainLock.lock();
   1819         try {
   1820             long n = completedTaskCount;
   1821             for (Worker w : workers) {
   1822                 n += w.completedTasks;
   1823                 if (w.isLocked())
   1824                     ++n;
   1825             }
   1826             return n + workQueue.size();
   1827         } finally {
   1828             mainLock.unlock();
   1829         }
   1830     }
   1831 
   1832     /**
   1833      * Returns the approximate total number of tasks that have
   1834      * completed execution. Because the states of tasks and threads
   1835      * may change dynamically during computation, the returned value
   1836      * is only an approximation, but one that does not ever decrease
   1837      * across successive calls.
   1838      *
   1839      * @return the number of tasks
   1840      */
   1841     public long getCompletedTaskCount() {
   1842         final ReentrantLock mainLock = this.mainLock;
   1843         mainLock.lock();
   1844         try {
   1845             long n = completedTaskCount;
   1846             for (Worker w : workers)
   1847                 n += w.completedTasks;
   1848             return n;
   1849         } finally {
   1850             mainLock.unlock();
   1851         }
   1852     }
   1853 
   1854     /**
   1855      * Returns a string identifying this pool, as well as its state,
   1856      * including indications of run state and estimated worker and
   1857      * task counts.
   1858      *
   1859      * @return a string identifying this pool, as well as its state
   1860      */
   1861     public String toString() {
   1862         long ncompleted;
   1863         int nworkers, nactive;
   1864         final ReentrantLock mainLock = this.mainLock;
   1865         mainLock.lock();
   1866         try {
   1867             ncompleted = completedTaskCount;
   1868             nactive = 0;
   1869             nworkers = workers.size();
   1870             for (Worker w : workers) {
   1871                 ncompleted += w.completedTasks;
   1872                 if (w.isLocked())
   1873                     ++nactive;
   1874             }
   1875         } finally {
   1876             mainLock.unlock();
   1877         }
   1878         int c = ctl.get();
   1879         String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
   1880                      (runStateAtLeast(c, TERMINATED) ? "Terminated" :
   1881                       "Shutting down"));
   1882         return super.toString() +
   1883             "[" + rs +
   1884             ", pool size = " + nworkers +
   1885             ", active threads = " + nactive +
   1886             ", queued tasks = " + workQueue.size() +
   1887             ", completed tasks = " + ncompleted +
   1888             "]";
   1889     }
   1890 
   1891     /* Extension hooks */
   1892 
   1893     /**
   1894      * Method invoked prior to executing the given Runnable in the
   1895      * given thread.  This method is invoked by thread {@code t} that
   1896      * will execute task {@code r}, and may be used to re-initialize
   1897      * ThreadLocals, or to perform logging.
   1898      *
   1899      * <p>This implementation does nothing, but may be customized in
   1900      * subclasses. Note: To properly nest multiple overridings, subclasses
   1901      * should generally invoke {@code super.beforeExecute} at the end of
   1902      * this method.
   1903      *
   1904      * @param t the thread that will run task {@code r}
   1905      * @param r the task that will be executed
   1906      */
   1907     protected void beforeExecute(Thread t, Runnable r) { }
   1908 
   1909     /**
   1910      * Method invoked upon completion of execution of the given Runnable.
   1911      * This method is invoked by the thread that executed the task. If
   1912      * non-null, the Throwable is the uncaught {@code RuntimeException}
   1913      * or {@code Error} that caused execution to terminate abruptly.
   1914      *
   1915      * <p>This implementation does nothing, but may be customized in
   1916      * subclasses. Note: To properly nest multiple overridings, subclasses
   1917      * should generally invoke {@code super.afterExecute} at the
   1918      * beginning of this method.
   1919      *
   1920      * <p><b>Note:</b> When actions are enclosed in tasks (such as
   1921      * {@link FutureTask}) either explicitly or via methods such as
   1922      * {@code submit}, these task objects catch and maintain
   1923      * computational exceptions, and so they do not cause abrupt
   1924      * termination, and the internal exceptions are <em>not</em>
   1925      * passed to this method. If you would like to trap both kinds of
   1926      * failures in this method, you can further probe for such cases,
   1927      * as in this sample subclass that prints either the direct cause
   1928      * or the underlying exception if a task has been aborted:
   1929      *
   1930      *  <pre> {@code
   1931      * class ExtendedExecutor extends ThreadPoolExecutor {
   1932      *   // ...
   1933      *   protected void afterExecute(Runnable r, Throwable t) {
   1934      *     super.afterExecute(r, t);
   1935      *     if (t == null && r instanceof Future<?>) {
   1936      *       try {
   1937      *         Object result = ((Future<?>) r).get();
   1938      *       } catch (CancellationException ce) {
   1939      *           t = ce;
   1940      *       } catch (ExecutionException ee) {
   1941      *           t = ee.getCause();
   1942      *       } catch (InterruptedException ie) {
   1943      *           Thread.currentThread().interrupt(); // ignore/reset
   1944      *       }
   1945      *     }
   1946      *     if (t != null)
   1947      *       System.out.println(t);
   1948      *   }
   1949      * }}</pre>
   1950      *
   1951      * @param r the runnable that has completed
   1952      * @param t the exception that caused termination, or null if
   1953      * execution completed normally
   1954      */
   1955     protected void afterExecute(Runnable r, Throwable t) { }
   1956 
   1957     /**
   1958      * Method invoked when the Executor has terminated.  Default
   1959      * implementation does nothing. Note: To properly nest multiple
   1960      * overridings, subclasses should generally invoke
   1961      * {@code super.terminated} within this method.
   1962      */
   1963     protected void terminated() { }
   1964 
   1965     /* Predefined RejectedExecutionHandlers */
   1966 
   1967     /**
   1968      * A handler for rejected tasks that runs the rejected task
   1969      * directly in the calling thread of the {@code execute} method,
   1970      * unless the executor has been shut down, in which case the task
   1971      * is discarded.
   1972      */
   1973     public static class CallerRunsPolicy implements RejectedExecutionHandler {
   1974         /**
   1975          * Creates a {@code CallerRunsPolicy}.
   1976          */
   1977         public CallerRunsPolicy() { }
   1978 
   1979         /**
   1980          * Executes task r in the caller's thread, unless the executor
   1981          * has been shut down, in which case the task is discarded.
   1982          *
   1983          * @param r the runnable task requested to be executed
   1984          * @param e the executor attempting to execute this task
   1985          */
   1986         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
   1987             if (!e.isShutdown()) {
   1988                 r.run();
   1989             }
   1990         }
   1991     }
   1992 
   1993     /**
   1994      * A handler for rejected tasks that throws a
   1995      * {@code RejectedExecutionException}.
   1996      */
   1997     public static class AbortPolicy implements RejectedExecutionHandler {
   1998         /**
   1999          * Creates an {@code AbortPolicy}.
   2000          */
   2001         public AbortPolicy() { }
   2002 
   2003         /**
   2004          * Always throws RejectedExecutionException.
   2005          *
   2006          * @param r the runnable task requested to be executed
   2007          * @param e the executor attempting to execute this task
   2008          * @throws RejectedExecutionException always
   2009          */
   2010         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
   2011             throw new RejectedExecutionException("Task " + r.toString() +
   2012                                                  " rejected from " +
   2013                                                  e.toString());
   2014         }
   2015     }
   2016 
   2017     /**
   2018      * A handler for rejected tasks that silently discards the
   2019      * rejected task.
   2020      */
   2021     public static class DiscardPolicy implements RejectedExecutionHandler {
   2022         /**
   2023          * Creates a {@code DiscardPolicy}.
   2024          */
   2025         public DiscardPolicy() { }
   2026 
   2027         /**
   2028          * Does nothing, which has the effect of discarding task r.
   2029          *
   2030          * @param r the runnable task requested to be executed
   2031          * @param e the executor attempting to execute this task
   2032          */
   2033         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
   2034         }
   2035     }
   2036 
   2037     /**
   2038      * A handler for rejected tasks that discards the oldest unhandled
   2039      * request and then retries {@code execute}, unless the executor
   2040      * is shut down, in which case the task is discarded.
   2041      */
   2042     public static class DiscardOldestPolicy implements RejectedExecutionHandler {
   2043         /**
   2044          * Creates a {@code DiscardOldestPolicy} for the given executor.
   2045          */
   2046         public DiscardOldestPolicy() { }
   2047 
   2048         /**
   2049          * Obtains and ignores the next task that the executor
   2050          * would otherwise execute, if one is immediately available,
   2051          * and then retries execution of task r, unless the executor
   2052          * is shut down, in which case task r is instead discarded.
   2053          *
   2054          * @param r the runnable task requested to be executed
   2055          * @param e the executor attempting to execute this task
   2056          */
   2057         public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
   2058             if (!e.isShutdown()) {
   2059                 e.getQueue().poll();
   2060                 e.execute(r);
   2061             }
   2062         }
   2063     }
   2064 }
   2065