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