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