2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
37 import java.util.concurrent.locks.*;
38 import java.util.concurrent.atomic.*;
42 * An {@link ExecutorService} that executes each submitted task using
43 * one of possibly several pooled threads, normally configured
44 * using {@link Executors} factory methods.
46 * <p>Thread pools address two different problems: they usually
47 * provide improved performance when executing large numbers of
48 * asynchronous tasks, due to reduced per-task invocation overhead,
49 * and they provide a means of bounding and managing the resources,
50 * including threads, consumed when executing a collection of tasks.
51 * Each {@code ThreadPoolExecutor} also maintains some basic
52 * statistics, such as the number of completed tasks.
54 * <p>To be useful across a wide range of contexts, this class
55 * provides many adjustable parameters and extensibility
56 * hooks. However, programmers are urged to use the more convenient
57 * {@link Executors} factory methods {@link
58 * Executors#newCachedThreadPool} (unbounded thread pool, with
59 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
60 * (fixed size thread pool) and {@link
61 * Executors#newSingleThreadExecutor} (single background thread), that
62 * preconfigure settings for the most common usage
63 * scenarios. Otherwise, use the following guide when manually
64 * configuring and tuning this class:
68 * <dt>Core and maximum pool sizes</dt>
70 * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
71 * pool size (see {@link #getPoolSize})
72 * according to the bounds set by
73 * corePoolSize (see {@link #getCorePoolSize}) and
74 * maximumPoolSize (see {@link #getMaximumPoolSize}).
76 * When a new task is submitted in method {@link #execute}, and fewer
77 * than corePoolSize threads are running, a new thread is created to
78 * handle the request, even if other worker threads are idle. If
79 * there are more than corePoolSize but less than maximumPoolSize
80 * threads running, a new thread will be created only if the queue is
81 * full. By setting corePoolSize and maximumPoolSize the same, you
82 * create a fixed-size thread pool. By setting maximumPoolSize to an
83 * essentially unbounded value such as {@code Integer.MAX_VALUE}, you
84 * allow the pool to accommodate an arbitrary number of concurrent
85 * tasks. Most typically, core and maximum pool sizes are set only
86 * upon construction, but they may also be changed dynamically using
87 * {@link #setCorePoolSize} and {@link #setMaximumPoolSize}. </dd>
89 * <dt>On-demand construction</dt>
91 * <dd> By default, even core threads are initially created and
92 * started only when new tasks arrive, but this can be overridden
93 * dynamically using method {@link #prestartCoreThread} or {@link
94 * #prestartAllCoreThreads}. You probably want to prestart threads if
95 * you construct the pool with a non-empty queue. </dd>
97 * <dt>Creating new threads</dt>
99 * <dd>New threads are created using a {@link ThreadFactory}. If not
100 * otherwise specified, a {@link Executors#defaultThreadFactory} is
101 * used, that creates threads to all be in the same {@link
102 * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
103 * non-daemon status. By supplying a different ThreadFactory, you can
104 * alter the thread's name, thread group, priority, daemon status,
105 * etc. If a {@code ThreadFactory} fails to create a thread when asked
106 * by returning null from {@code newThread}, the executor will
107 * continue, but might not be able to execute any tasks. Threads
108 * should possess the "modifyThread" {@code RuntimePermission}. If
109 * worker threads or other threads using the pool do not possess this
110 * permission, service may be degraded: configuration changes may not
111 * take effect in a timely manner, and a shutdown pool may remain in a
112 * state in which termination is possible but not completed.</dd>
114 * <dt>Keep-alive times</dt>
116 * <dd>If the pool currently has more than corePoolSize threads,
117 * excess threads will be terminated if they have been idle for more
118 * than the keepAliveTime (see {@link #getKeepAliveTime}). This
119 * provides a means of reducing resource consumption when the pool is
120 * not being actively used. If the pool becomes more active later, new
121 * threads will be constructed. This parameter can also be changed
122 * dynamically using method {@link #setKeepAliveTime}. Using a value
123 * of {@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS} effectively
124 * disables idle threads from ever terminating prior to shut down. By
125 * default, the keep-alive policy applies only when there are more
126 * than corePoolSizeThreads. But method {@link
127 * #allowCoreThreadTimeOut(boolean)} can be used to apply this
128 * time-out policy to core threads as well, so long as the
129 * keepAliveTime value is non-zero. </dd>
133 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
134 * submitted tasks. The use of this queue interacts with pool sizing:
138 * <li> If fewer than corePoolSize threads are running, the Executor
139 * always prefers adding a new thread
140 * rather than queuing.</li>
142 * <li> If corePoolSize or more threads are running, the Executor
143 * always prefers queuing a request rather than adding a new
146 * <li> If a request cannot be queued, a new thread is created unless
147 * this would exceed maximumPoolSize, in which case, the task will be
152 * There are three general strategies for queuing:
155 * <li> <em> Direct handoffs.</em> A good default choice for a work
156 * queue is a {@link SynchronousQueue} that hands off tasks to threads
157 * without otherwise holding them. Here, an attempt to queue a task
158 * will fail if no threads are immediately available to run it, so a
159 * new thread will be constructed. This policy avoids lockups when
160 * handling sets of requests that might have internal dependencies.
161 * Direct handoffs generally require unbounded maximumPoolSizes to
162 * avoid rejection of new submitted tasks. This in turn admits the
163 * possibility of unbounded thread growth when commands continue to
164 * arrive on average faster than they can be processed. </li>
166 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
167 * example a {@link LinkedBlockingQueue} without a predefined
168 * capacity) will cause new tasks to wait in the queue when all
169 * corePoolSize threads are busy. Thus, no more than corePoolSize
170 * threads will ever be created. (And the value of the maximumPoolSize
171 * therefore doesn't have any effect.) This may be appropriate when
172 * each task is completely independent of others, so tasks cannot
173 * affect each others execution; for example, in a web page server.
174 * While this style of queuing can be useful in smoothing out
175 * transient bursts of requests, it admits the possibility of
176 * unbounded work queue growth when commands continue to arrive on
177 * average faster than they can be processed. </li>
179 * <li><em>Bounded queues.</em> A bounded queue (for example, an
180 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
181 * used with finite maximumPoolSizes, but can be more difficult to
182 * tune and control. Queue sizes and maximum pool sizes may be traded
183 * off for each other: Using large queues and small pools minimizes
184 * CPU usage, OS resources, and context-switching overhead, but can
185 * lead to artificially low throughput. If tasks frequently block (for
186 * example if they are I/O bound), a system may be able to schedule
187 * time for more threads than you otherwise allow. Use of small queues
188 * generally requires larger pool sizes, which keeps CPUs busier but
189 * may encounter unacceptable scheduling overhead, which also
190 * decreases throughput. </li>
196 * <dt>Rejected tasks</dt>
198 * <dd> New tasks submitted in method {@link #execute} will be
199 * <em>rejected</em> when the Executor has been shut down, and also
200 * when the Executor uses finite bounds for both maximum threads and
201 * work queue capacity, and is saturated. In either case, the {@code
202 * execute} method invokes the {@link
203 * RejectedExecutionHandler#rejectedExecution} method of its {@link
204 * RejectedExecutionHandler}. Four predefined handler policies are
209 * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the
210 * handler throws a runtime {@link RejectedExecutionException} upon
213 * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
214 * that invokes {@code execute} itself runs the task. This provides a
215 * simple feedback control mechanism that will slow down the rate that
216 * new tasks are submitted. </li>
218 * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
219 * cannot be executed is simply dropped. </li>
221 * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
222 * executor is not shut down, the task at the head of the work queue
223 * is dropped, and then execution is retried (which can fail again,
224 * causing this to be repeated.) </li>
228 * It is possible to define and use other kinds of {@link
229 * RejectedExecutionHandler} classes. Doing so requires some care
230 * especially when policies are designed to work only under particular
231 * capacity or queuing policies. </dd>
233 * <dt>Hook methods</dt>
235 * <dd>This class provides {@code protected} overridable {@link
236 * #beforeExecute} and {@link #afterExecute} methods that are called
237 * before and after execution of each task. These can be used to
238 * manipulate the execution environment; for example, reinitializing
239 * ThreadLocals, gathering statistics, or adding log
240 * entries. Additionally, method {@link #terminated} can be overridden
241 * to perform any special processing that needs to be done once the
242 * Executor has fully terminated.
244 * <p>If hook or callback methods throw exceptions, internal worker
245 * threads may in turn fail and abruptly terminate.</dd>
247 * <dt>Queue maintenance</dt>
249 * <dd> Method {@link #getQueue} allows access to the work queue for
250 * purposes of monitoring and debugging. Use of this method for any
251 * other purpose is strongly discouraged. Two supplied methods,
252 * {@link #remove} and {@link #purge} are available to assist in
253 * storage reclamation when large numbers of queued tasks become
256 * <dt>Finalization</dt>
258 * <dd> A pool that is no longer referenced in a program <em>AND</em>
259 * has no remaining threads will be {@code shutdown} automatically. If
260 * you would like to ensure that unreferenced pools are reclaimed even
261 * if users forget to call {@link #shutdown}, then you must arrange
262 * that unused threads eventually die, by setting appropriate
263 * keep-alive times, using a lower bound of zero core threads and/or
264 * setting {@link #allowCoreThreadTimeOut(boolean)}. </dd>
268 * <p> <b>Extension example</b>. Most extensions of this class
269 * override one or more of the protected hook methods. For example,
270 * here is a subclass that adds a simple pause/resume feature:
273 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
274 * private boolean isPaused;
275 * private ReentrantLock pauseLock = new ReentrantLock();
276 * private Condition unpaused = pauseLock.newCondition();
278 * public PausableThreadPoolExecutor(...) { super(...); }
280 * protected void beforeExecute(Thread t, Runnable r) {
281 * super.beforeExecute(t, r);
284 * while (isPaused) unpaused.await();
285 * } catch (InterruptedException ie) {
288 * pauseLock.unlock();
292 * public void pause() {
297 * pauseLock.unlock();
301 * public void resume() {
305 * unpaused.signalAll();
307 * pauseLock.unlock();
315 public class ThreadPoolExecutor extends AbstractExecutorService {
317 * The main pool control state, ctl, is an atomic integer packing
318 * two conceptual fields
319 * workerCount, indicating the effective number of threads
320 * runState, indicating whether running, shutting down etc
322 * In order to pack them into one int, we limit workerCount to
323 * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
324 * billion) otherwise representable. If this is ever an issue in
325 * the future, the variable can be changed to be an AtomicLong,
326 * and the shift/mask constants below adjusted. But until the need
327 * arises, this code is a bit faster and simpler using an int.
329 * The workerCount is the number of workers that have been
330 * permitted to start and not permitted to stop. The value may be
331 * transiently different from the actual number of live threads,
332 * for example when a ThreadFactory fails to create a thread when
333 * asked, and when exiting threads are still performing
334 * bookkeeping before terminating. The user-visible pool size is
335 * reported as the current size of the workers set.
337 * The runState provides the main lifecyle control, taking on values:
339 * RUNNING: Accept new tasks and process queued tasks
340 * SHUTDOWN: Don't accept new tasks, but process queued tasks
341 * STOP: Don't accept new tasks, don't process queued tasks,
342 * and interrupt in-progress tasks
343 * TIDYING: All tasks have terminated, workerCount is zero,
344 * the thread transitioning to state TIDYING
345 * will run the terminated() hook method
346 * TERMINATED: terminated() has completed
348 * The numerical order among these values matters, to allow
349 * ordered comparisons. The runState monotonically increases over
350 * time, but need not hit each state. The transitions are:
352 * RUNNING -> SHUTDOWN
353 * On invocation of shutdown(), perhaps implicitly in finalize()
354 * (RUNNING or SHUTDOWN) -> STOP
355 * On invocation of shutdownNow()
356 * SHUTDOWN -> TIDYING
357 * When both queue and pool are empty
360 * TIDYING -> TERMINATED
361 * When the terminated() hook method has completed
363 * Threads waiting in awaitTermination() will return when the
364 * state reaches TERMINATED.
366 * Detecting the transition from SHUTDOWN to TIDYING is less
367 * straightforward than you'd like because the queue may become
368 * empty after non-empty and vice versa during SHUTDOWN state, but
369 * we can only terminate if, after seeing that it is empty, we see
370 * that workerCount is 0 (which sometimes entails a recheck -- see
373 private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
374 private static final int COUNT_BITS = Integer.SIZE - 3;
375 private static final int CAPACITY = (1 << COUNT_BITS) - 1;
377 // runState is stored in the high-order bits
378 private static final int RUNNING = -1 << COUNT_BITS;
379 private static final int SHUTDOWN = 0 << COUNT_BITS;
380 private static final int STOP = 1 << COUNT_BITS;
381 private static final int TIDYING = 2 << COUNT_BITS;
382 private static final int TERMINATED = 3 << COUNT_BITS;
384 // Packing and unpacking ctl
385 private static int runStateOf(int c) { return c & ~CAPACITY; }
386 private static int workerCountOf(int c) { return c & CAPACITY; }
387 private static int ctlOf(int rs, int wc) { return rs | wc; }
390 * Bit field accessors that don't require unpacking ctl.
391 * These depend on the bit layout and on workerCount being never negative.
394 private static boolean runStateLessThan(int c, int s) {
398 private static boolean runStateAtLeast(int c, int s) {
402 private static boolean isRunning(int c) {
407 * Attempt to CAS-increment the workerCount field of ctl.
409 private boolean compareAndIncrementWorkerCount(int expect) {
410 return ctl.compareAndSet(expect, expect + 1);
414 * Attempt to CAS-decrement the workerCount field of ctl.
416 private boolean compareAndDecrementWorkerCount(int expect) {
417 return ctl.compareAndSet(expect, expect - 1);
421 * Decrements the workerCount field of ctl. This is called only on
422 * abrupt termination of a thread (see processWorkerExit). Other
423 * decrements are performed within getTask.
425 private void decrementWorkerCount() {
426 do {} while (! compareAndDecrementWorkerCount(ctl.get()));
430 * The queue used for holding tasks and handing off to worker
431 * threads. We do not require that workQueue.poll() returning
432 * null necessarily means that workQueue.isEmpty(), so rely
433 * solely on isEmpty to see if the queue is empty (which we must
434 * do for example when deciding whether to transition from
435 * SHUTDOWN to TIDYING). This accommodates special-purpose
436 * queues such as DelayQueues for which poll() is allowed to
437 * return null even if it may later return non-null when delays
440 private final BlockingQueue<Runnable> workQueue;
443 * Lock held on access to workers set and related bookkeeping.
444 * While we could use a concurrent set of some sort, it turns out
445 * to be generally preferable to use a lock. Among the reasons is
446 * that this serializes interruptIdleWorkers, which avoids
447 * unnecessary interrupt storms, especially during shutdown.
448 * Otherwise exiting threads would concurrently interrupt those
449 * that have not yet interrupted. It also simplifies some of the
450 * associated statistics bookkeeping of largestPoolSize etc. We
451 * also hold mainLock on shutdown and shutdownNow, for the sake of
452 * ensuring workers set is stable while separately checking
453 * permission to interrupt and actually interrupting.
455 private final ReentrantLock mainLock = new ReentrantLock();
458 * Set containing all worker threads in pool. Accessed only when
461 private final HashSet<Worker> workers = new HashSet<Worker>();
464 * Wait condition to support awaitTermination
466 private final Condition termination = mainLock.newCondition();
469 * Tracks largest attained pool size. Accessed only under
472 private int largestPoolSize;
475 * Counter for completed tasks. Updated only on termination of
476 * worker threads. Accessed only under mainLock.
478 private long completedTaskCount;
481 * All user control parameters are declared as volatiles so that
482 * ongoing actions are based on freshest values, but without need
483 * for locking, since no internal invariants depend on them
484 * changing synchronously with respect to other actions.
488 * Factory for new threads. All threads are created using this
489 * factory (via method addWorker). All callers must be prepared
490 * for addWorker to fail, which may reflect a system or user's
491 * policy limiting the number of threads. Even though it is not
492 * treated as an error, failure to create threads may result in
493 * new tasks being rejected or existing ones remaining stuck in
494 * the queue. On the other hand, no special precautions exist to
495 * handle OutOfMemoryErrors that might be thrown while trying to
496 * create threads, since there is generally no recourse from
499 private volatile ThreadFactory threadFactory;
502 * Handler called when saturated or shutdown in execute.
504 private volatile RejectedExecutionHandler handler;
507 * Timeout in nanoseconds for idle threads waiting for work.
508 * Threads use this timeout when there are more than corePoolSize
509 * present or if allowCoreThreadTimeOut. Otherwise they wait
510 * forever for new work.
512 private volatile long keepAliveTime;
515 * If false (default), core threads stay alive even when idle.
516 * If true, core threads use keepAliveTime to time out waiting
519 private volatile boolean allowCoreThreadTimeOut;
522 * Core pool size is the minimum number of workers to keep alive
523 * (and not allow to time out etc) unless allowCoreThreadTimeOut
524 * is set, in which case the minimum is zero.
526 private volatile int corePoolSize;
529 * Maximum pool size. Note that the actual maximum is internally
530 * bounded by CAPACITY.
532 private volatile int maximumPoolSize;
535 * The default rejected execution handler
537 private static final RejectedExecutionHandler defaultHandler =
541 * Permission required for callers of shutdown and shutdownNow.
542 * We additionally require (see checkShutdownAccess) that callers
543 * have permission to actually interrupt threads in the worker set
544 * (as governed by Thread.interrupt, which relies on
545 * ThreadGroup.checkAccess, which in turn relies on
546 * SecurityManager.checkAccess). Shutdowns are attempted only if
549 * All actual invocations of Thread.interrupt (see
550 * interruptIdleWorkers and interruptWorkers) ignore
551 * SecurityExceptions, meaning that the attempted interrupts
552 * silently fail. In the case of shutdown, they should not fail
553 * unless the SecurityManager has inconsistent policies, sometimes
554 * allowing access to a thread and sometimes not. In such cases,
555 * failure to actually interrupt threads may disable or delay full
556 * termination. Other uses of interruptIdleWorkers are advisory,
557 * and failure to actually interrupt will merely delay response to
558 * configuration changes so is not handled exceptionally.
560 // private static final RuntimePermission shutdownPerm =
561 // new RuntimePermission("modifyThread");
564 * Class Worker mainly maintains interrupt control state for
565 * threads running tasks, along with other minor bookkeeping.
566 * This class opportunistically extends AbstractQueuedSynchronizer
567 * to simplify acquiring and releasing a lock surrounding each
568 * task execution. This protects against interrupts that are
569 * intended to wake up a worker thread waiting for a task from
570 * instead interrupting a task being run. We implement a simple
571 * non-reentrant mutual exclusion lock rather than use ReentrantLock
572 * because we do not want worker tasks to be able to reacquire the
573 * lock when they invoke pool control methods like setCorePoolSize.
575 private final class Worker
576 extends AbstractQueuedSynchronizer
580 * This class will never be serialized, but we provide a
581 * serialVersionUID to suppress a javac warning.
583 private static final long serialVersionUID = 6138294804551838833L;
585 /** Thread this worker is running in. Null if factory fails. */
587 /** Initial task to run. Possibly null. */
589 /** Per-thread task counter */
590 volatile long completedTasks;
593 * Creates with given first task and thread from ThreadFactory.
594 * @param firstTask the first task (null if none)
596 Worker(Runnable firstTask) {
597 this.firstTask = firstTask;
598 this.thread = getThreadFactory().newThread(this);
601 /** Delegates main run loop to outer runWorker */
608 // The value 0 represents the unlocked state.
609 // The value 1 represents the locked state.
611 protected boolean isHeldExclusively() {
612 return getState() == 1;
615 protected boolean tryAcquire(int unused) {
616 if (compareAndSetState(0, 1)) {
617 setExclusiveOwnerThread(Thread.currentThread());
623 protected boolean tryRelease(int unused) {
624 setExclusiveOwnerThread(null);
629 public void lock() { acquire(1); }
630 public boolean tryLock() { return tryAcquire(1); }
631 public void unlock() { release(1); }
632 public boolean isLocked() { return isHeldExclusively(); }
636 * Methods for setting control state
640 * Transitions runState to given target, or leaves it alone if
641 * already at least the given target.
643 * @param targetState the desired state, either SHUTDOWN or STOP
644 * (but not TIDYING or TERMINATED -- use tryTerminate for that)
646 private void advanceRunState(int targetState) {
649 if (runStateAtLeast(c, targetState) ||
650 ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
656 * Transitions to TERMINATED state if either (SHUTDOWN and pool
657 * and queue empty) or (STOP and pool empty). If otherwise
658 * eligible to terminate but workerCount is nonzero, interrupts an
659 * idle worker to ensure that shutdown signals propagate. This
660 * method must be called following any action that might make
661 * termination possible -- reducing worker count or removing tasks
662 * from the queue during shutdown. The method is non-private to
663 * allow access from ScheduledThreadPoolExecutor.
665 final void tryTerminate() {
669 runStateAtLeast(c, TIDYING) ||
670 (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
672 if (workerCountOf(c) != 0) { // Eligible to terminate
673 interruptIdleWorkers(ONLY_ONE);
677 final ReentrantLock mainLock = this.mainLock;
680 if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
684 ctl.set(ctlOf(TERMINATED, 0));
685 termination.signalAll();
692 // else retry on failed CAS
697 * Methods for controlling interrupts to worker threads.
701 * If there is a security manager, makes sure caller has
702 * permission to shut down threads in general (see shutdownPerm).
703 * If this passes, additionally makes sure the caller is allowed
704 * to interrupt each worker thread. This might not be true even if
705 * first check passed, if the SecurityManager treats some threads
708 private void checkShutdownAccess() {
709 // SecurityManager security = System.getSecurityManager();
710 // if (security != null) {
711 // security.checkPermission(shutdownPerm);
712 // final ReentrantLock mainLock = this.mainLock;
715 // for (Worker w : workers)
716 // security.checkAccess(w.thread);
718 // mainLock.unlock();
724 * Interrupts all threads, even if active. Ignores SecurityExceptions
725 * (in which case some threads may remain uninterrupted).
727 private void interruptWorkers() {
728 final ReentrantLock mainLock = this.mainLock;
731 for (Worker w : workers) {
733 w.thread.interrupt();
734 } catch (SecurityException ignore) {
743 * Interrupts threads that might be waiting for tasks (as
744 * indicated by not being locked) so they can check for
745 * termination or configuration changes. Ignores
746 * SecurityExceptions (in which case some threads may remain
749 * @param onlyOne If true, interrupt at most one worker. This is
750 * called only from tryTerminate when termination is otherwise
751 * enabled but there are still other workers. In this case, at
752 * most one waiting worker is interrupted to propagate shutdown
753 * signals in case all threads are currently waiting.
754 * Interrupting any arbitrary thread ensures that newly arriving
755 * workers since shutdown began will also eventually exit.
756 * To guarantee eventual termination, it suffices to always
757 * interrupt only one idle worker, but shutdown() interrupts all
758 * idle workers so that redundant workers exit promptly, not
759 * waiting for a straggler task to finish.
761 private void interruptIdleWorkers(boolean onlyOne) {
762 final ReentrantLock mainLock = this.mainLock;
765 for (Worker w : workers) {
767 if (!t.isInterrupted() && w.tryLock()) {
770 } catch (SecurityException ignore) {
784 * Common form of interruptIdleWorkers, to avoid having to
785 * remember what the boolean argument means.
787 private void interruptIdleWorkers() {
788 interruptIdleWorkers(false);
791 private static final boolean ONLY_ONE = true;
794 * Ensures that unless the pool is stopping, the current thread
795 * does not have its interrupt set. This requires a double-check
796 * of state in case the interrupt was cleared concurrently with a
797 * shutdownNow -- if so, the interrupt is re-enabled.
799 private void clearInterruptsForTaskRun() {
800 if (runStateLessThan(ctl.get(), STOP) &&
801 Thread.interrupted() &&
802 runStateAtLeast(ctl.get(), STOP))
803 Thread.currentThread().interrupt();
807 * Misc utilities, most of which are also exported to
808 * ScheduledThreadPoolExecutor
812 * Invokes the rejected execution handler for the given command.
813 * Package-protected for use by ScheduledThreadPoolExecutor.
815 final void reject(Runnable command) {
816 handler.rejectedExecution(command, this);
820 * Performs any further cleanup following run state transition on
821 * invocation of shutdown. A no-op here, but used by
822 * ScheduledThreadPoolExecutor to cancel delayed tasks.
828 * State check needed by ScheduledThreadPoolExecutor to
829 * enable running tasks during shutdown.
831 * @param shutdownOK true if should return true if SHUTDOWN
833 final boolean isRunningOrShutdown(boolean shutdownOK) {
834 int rs = runStateOf(ctl.get());
835 return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
839 * Drains the task queue into a new list, normally using
840 * drainTo. But if the queue is a DelayQueue or any other kind of
841 * queue for which poll or drainTo may fail to remove some
842 * elements, it deletes them one by one.
844 private List<Runnable> drainQueue() {
845 BlockingQueue<Runnable> q = workQueue;
846 List<Runnable> taskList = new ArrayList<Runnable>();
849 for (Runnable r : q.toArray(new Runnable[0])) {
858 * Methods for creating, running and cleaning up after workers
862 * Checks if a new worker can be added with respect to current
863 * pool state and the given bound (either core or maximum). If so,
864 * the worker count is adjusted accordingly, and, if possible, a
865 * new worker is created and started running firstTask as its
866 * first task. This method returns false if the pool is stopped or
867 * eligible to shut down. It also returns false if the thread
868 * factory fails to create a thread when asked, which requires a
869 * backout of workerCount, and a recheck for termination, in case
870 * the existence of this worker was holding up termination.
872 * @param firstTask the task the new thread should run first (or
873 * null if none). Workers are created with an initial first task
874 * (in method execute()) to bypass queuing when there are fewer
875 * than corePoolSize threads (in which case we always start one),
876 * or when the queue is full (in which case we must bypass queue).
877 * Initially idle threads are usually created via
878 * prestartCoreThread or to replace other dying workers.
880 * @param core if true use corePoolSize as bound, else
881 * maximumPoolSize. (A boolean indicator is used here rather than a
882 * value to ensure reads of fresh values after checking other pool
884 * @return true if successful
886 private boolean addWorker(Runnable firstTask, boolean core) {
890 int rs = runStateOf(c);
892 // Check if queue empty only if necessary.
893 if (rs >= SHUTDOWN &&
896 ! workQueue.isEmpty()))
900 int wc = workerCountOf(c);
901 if (wc >= CAPACITY ||
902 wc >= (core ? corePoolSize : maximumPoolSize))
904 if (compareAndIncrementWorkerCount(c))
906 c = ctl.get(); // Re-read ctl
907 if (runStateOf(c) != rs)
909 // else CAS failed due to workerCount change; retry inner loop
913 Worker w = new Worker(firstTask);
916 final ReentrantLock mainLock = this.mainLock;
919 // Recheck while holding lock.
920 // Back out on ThreadFactory failure or if
921 // shut down before lock acquired.
923 int rs = runStateOf(c);
928 firstTask == null))) {
929 decrementWorkerCount();
936 int s = workers.size();
937 if (s > largestPoolSize)
944 // It is possible (but unlikely) for a thread to have been
945 // added to workers, but not yet started, during transition to
946 // STOP, which could result in a rare missed interrupt,
947 // because Thread.interrupt is not guaranteed to have any effect
948 // on a non-yet-started Thread (see Thread#interrupt).
949 if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted())
956 * Performs cleanup and bookkeeping for a dying worker. Called
957 * only from worker threads. Unless completedAbruptly is set,
958 * assumes that workerCount has already been adjusted to account
959 * for exit. This method removes thread from worker set, and
960 * possibly terminates the pool or replaces the worker if either
961 * it exited due to user task exception or if fewer than
962 * corePoolSize workers are running or queue is non-empty but
963 * there are no workers.
965 * @param w the worker
966 * @param completedAbruptly if the worker died due to user exception
968 private void processWorkerExit(Worker w, boolean completedAbruptly) {
969 if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
970 decrementWorkerCount();
972 final ReentrantLock mainLock = this.mainLock;
975 completedTaskCount += w.completedTasks;
984 if (runStateLessThan(c, STOP)) {
985 if (!completedAbruptly) {
986 int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
987 if (min == 0 && ! workQueue.isEmpty())
989 if (workerCountOf(c) >= min)
990 return; // replacement not needed
992 addWorker(null, false);
997 * Performs blocking or timed wait for a task, depending on
998 * current configuration settings, or returns null if this worker
999 * must exit because of any of:
1000 * 1. There are more than maximumPoolSize workers (due to
1001 * a call to setMaximumPoolSize).
1002 * 2. The pool is stopped.
1003 * 3. The pool is shutdown and the queue is empty.
1004 * 4. This worker timed out waiting for a task, and timed-out
1005 * workers are subject to termination (that is,
1006 * {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
1007 * both before and after the timed wait.
1009 * @return task, or null if the worker must exit, in which case
1010 * workerCount is decremented
1012 private Runnable getTask() {
1013 boolean timedOut = false; // Did the last poll() time out?
1018 int rs = runStateOf(c);
1020 // Check if queue empty only if necessary.
1021 if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
1022 decrementWorkerCount();
1026 boolean timed; // Are workers subject to culling?
1029 int wc = workerCountOf(c);
1030 timed = allowCoreThreadTimeOut || wc > corePoolSize;
1032 if (wc <= maximumPoolSize && ! (timedOut && timed))
1034 if (compareAndDecrementWorkerCount(c))
1036 c = ctl.get(); // Re-read ctl
1037 if (runStateOf(c) != rs)
1039 // else CAS failed due to workerCount change; retry inner loop
1043 Runnable r = timed ?
1044 workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
1049 } catch (InterruptedException retry) {
1056 * Main worker run loop. Repeatedly gets tasks from queue and
1057 * executes them, while coping with a number of issues:
1059 * 1. We may start out with an initial task, in which case we
1060 * don't need to get the first one. Otherwise, as long as pool is
1061 * running, we get tasks from getTask. If it returns null then the
1062 * worker exits due to changed pool state or configuration
1063 * parameters. Other exits result from exception throws in
1064 * external code, in which case completedAbruptly holds, which
1065 * usually leads processWorkerExit to replace this thread.
1067 * 2. Before running any task, the lock is acquired to prevent
1068 * other pool interrupts while the task is executing, and
1069 * clearInterruptsForTaskRun called to ensure that unless pool is
1070 * stopping, this thread does not have its interrupt set.
1072 * 3. Each task run is preceded by a call to beforeExecute, which
1073 * might throw an exception, in which case we cause thread to die
1074 * (breaking loop with completedAbruptly true) without processing
1077 * 4. Assuming beforeExecute completes normally, we run the task,
1078 * gathering any of its thrown exceptions to send to
1079 * afterExecute. We separately handle RuntimeException, Error
1080 * (both of which the specs guarantee that we trap) and arbitrary
1081 * Throwables. Because we cannot rethrow Throwables within
1082 * Runnable.run, we wrap them within Errors on the way out (to the
1083 * thread's UncaughtExceptionHandler). Any thrown exception also
1084 * conservatively causes thread to die.
1086 * 5. After task.run completes, we call afterExecute, which may
1087 * also throw an exception, which will also cause thread to
1088 * die. According to JLS Sec 14.20, this exception is the one that
1089 * will be in effect even if task.run throws.
1091 * The net effect of the exception mechanics is that afterExecute
1092 * and the thread's UncaughtExceptionHandler have as accurate
1093 * information as we can provide about any problems encountered by
1096 * @param w the worker
1098 final void runWorker(Worker w) {
1099 Runnable task = w.firstTask;
1101 boolean completedAbruptly = true;
1103 while (task != null || (task = getTask()) != null) {
1105 clearInterruptsForTaskRun();
1107 beforeExecute(w.thread, task);
1108 Throwable thrown = null;
1111 } catch (RuntimeException x) {
1112 thrown = x; throw x;
1114 thrown = x; throw x;
1115 } catch (Throwable x) {
1116 thrown = x; throw new Error(x);
1118 afterExecute(task, thrown);
1126 completedAbruptly = false;
1128 processWorkerExit(w, completedAbruptly);
1132 // Public constructors and methods
1135 * Creates a new {@code ThreadPoolExecutor} with the given initial
1136 * parameters and default thread factory and rejected execution handler.
1137 * It may be more convenient to use one of the {@link Executors} factory
1138 * methods instead of this general purpose constructor.
1140 * @param corePoolSize the number of threads to keep in the pool, even
1141 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1142 * @param maximumPoolSize the maximum number of threads to allow in the
1144 * @param keepAliveTime when the number of threads is greater than
1145 * the core, this is the maximum time that excess idle threads
1146 * will wait for new tasks before terminating.
1147 * @param unit the time unit for the {@code keepAliveTime} argument
1148 * @param workQueue the queue to use for holding tasks before they are
1149 * executed. This queue will hold only the {@code Runnable}
1150 * tasks submitted by the {@code execute} method.
1151 * @throws IllegalArgumentException if one of the following holds:<br>
1152 * {@code corePoolSize < 0}<br>
1153 * {@code keepAliveTime < 0}<br>
1154 * {@code maximumPoolSize <= 0}<br>
1155 * {@code maximumPoolSize < corePoolSize}
1156 * @throws NullPointerException if {@code workQueue} is null
1158 public ThreadPoolExecutor(int corePoolSize,
1159 int maximumPoolSize,
1162 BlockingQueue<Runnable> workQueue) {
1163 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1164 Executors.defaultThreadFactory(), defaultHandler);
1168 * Creates a new {@code ThreadPoolExecutor} with the given initial
1169 * parameters and default rejected execution handler.
1171 * @param corePoolSize the number of threads to keep in the pool, even
1172 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1173 * @param maximumPoolSize the maximum number of threads to allow in the
1175 * @param keepAliveTime when the number of threads is greater than
1176 * the core, this is the maximum time that excess idle threads
1177 * will wait for new tasks before terminating.
1178 * @param unit the time unit for the {@code keepAliveTime} argument
1179 * @param workQueue the queue to use for holding tasks before they are
1180 * executed. This queue will hold only the {@code Runnable}
1181 * tasks submitted by the {@code execute} method.
1182 * @param threadFactory the factory to use when the executor
1183 * creates a new thread
1184 * @throws IllegalArgumentException if one of the following holds:<br>
1185 * {@code corePoolSize < 0}<br>
1186 * {@code keepAliveTime < 0}<br>
1187 * {@code maximumPoolSize <= 0}<br>
1188 * {@code maximumPoolSize < corePoolSize}
1189 * @throws NullPointerException if {@code workQueue}
1190 * or {@code threadFactory} is null
1192 public ThreadPoolExecutor(int corePoolSize,
1193 int maximumPoolSize,
1196 BlockingQueue<Runnable> workQueue,
1197 ThreadFactory threadFactory) {
1198 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1199 threadFactory, defaultHandler);
1203 * Creates a new {@code ThreadPoolExecutor} with the given initial
1204 * parameters and default thread factory.
1206 * @param corePoolSize the number of threads to keep in the pool, even
1207 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1208 * @param maximumPoolSize the maximum number of threads to allow in the
1210 * @param keepAliveTime when the number of threads is greater than
1211 * the core, this is the maximum time that excess idle threads
1212 * will wait for new tasks before terminating.
1213 * @param unit the time unit for the {@code keepAliveTime} argument
1214 * @param workQueue the queue to use for holding tasks before they are
1215 * executed. This queue will hold only the {@code Runnable}
1216 * tasks submitted by the {@code execute} method.
1217 * @param handler the handler to use when execution is blocked
1218 * because the thread bounds and queue capacities are reached
1219 * @throws IllegalArgumentException if one of the following holds:<br>
1220 * {@code corePoolSize < 0}<br>
1221 * {@code keepAliveTime < 0}<br>
1222 * {@code maximumPoolSize <= 0}<br>
1223 * {@code maximumPoolSize < corePoolSize}
1224 * @throws NullPointerException if {@code workQueue}
1225 * or {@code handler} is null
1227 public ThreadPoolExecutor(int corePoolSize,
1228 int maximumPoolSize,
1231 BlockingQueue<Runnable> workQueue,
1232 RejectedExecutionHandler handler) {
1233 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1234 Executors.defaultThreadFactory(), handler);
1238 * Creates a new {@code ThreadPoolExecutor} with the given initial
1241 * @param corePoolSize the number of threads to keep in the pool, even
1242 * if they are idle, unless {@code allowCoreThreadTimeOut} is set
1243 * @param maximumPoolSize the maximum number of threads to allow in the
1245 * @param keepAliveTime when the number of threads is greater than
1246 * the core, this is the maximum time that excess idle threads
1247 * will wait for new tasks before terminating.
1248 * @param unit the time unit for the {@code keepAliveTime} argument
1249 * @param workQueue the queue to use for holding tasks before they are
1250 * executed. This queue will hold only the {@code Runnable}
1251 * tasks submitted by the {@code execute} method.
1252 * @param threadFactory the factory to use when the executor
1253 * creates a new thread
1254 * @param handler the handler to use when execution is blocked
1255 * because the thread bounds and queue capacities are reached
1256 * @throws IllegalArgumentException if one of the following holds:<br>
1257 * {@code corePoolSize < 0}<br>
1258 * {@code keepAliveTime < 0}<br>
1259 * {@code maximumPoolSize <= 0}<br>
1260 * {@code maximumPoolSize < corePoolSize}
1261 * @throws NullPointerException if {@code workQueue}
1262 * or {@code threadFactory} or {@code handler} is null
1264 public ThreadPoolExecutor(int corePoolSize,
1265 int maximumPoolSize,
1268 BlockingQueue<Runnable> workQueue,
1269 ThreadFactory threadFactory,
1270 RejectedExecutionHandler handler) {
1271 if (corePoolSize < 0 ||
1272 maximumPoolSize <= 0 ||
1273 maximumPoolSize < corePoolSize ||
1275 throw new IllegalArgumentException();
1276 if (workQueue == null || threadFactory == null || handler == null)
1277 throw new NullPointerException();
1278 this.corePoolSize = corePoolSize;
1279 this.maximumPoolSize = maximumPoolSize;
1280 this.workQueue = workQueue;
1281 this.keepAliveTime = unit.toNanos(keepAliveTime);
1282 this.threadFactory = threadFactory;
1283 this.handler = handler;
1287 * Executes the given task sometime in the future. The task
1288 * may execute in a new thread or in an existing pooled thread.
1290 * If the task cannot be submitted for execution, either because this
1291 * executor has been shutdown or because its capacity has been reached,
1292 * the task is handled by the current {@code RejectedExecutionHandler}.
1294 * @param command the task to execute
1295 * @throws RejectedExecutionException at discretion of
1296 * {@code RejectedExecutionHandler}, if the task
1297 * cannot be accepted for execution
1298 * @throws NullPointerException if {@code command} is null
1300 public void execute(Runnable command) {
1301 if (command == null)
1302 throw new NullPointerException();
1304 * Proceed in 3 steps:
1306 * 1. If fewer than corePoolSize threads are running, try to
1307 * start a new thread with the given command as its first
1308 * task. The call to addWorker atomically checks runState and
1309 * workerCount, and so prevents false alarms that would add
1310 * threads when it shouldn't, by returning false.
1312 * 2. If a task can be successfully queued, then we still need
1313 * to double-check whether we should have added a thread
1314 * (because existing ones died since last checking) or that
1315 * the pool shut down since entry into this method. So we
1316 * recheck state and if necessary roll back the enqueuing if
1317 * stopped, or start a new thread if there are none.
1319 * 3. If we cannot queue task, then we try to add a new
1320 * thread. If it fails, we know we are shut down or saturated
1321 * and so reject the task.
1324 if (workerCountOf(c) < corePoolSize) {
1325 if (addWorker(command, true))
1329 if (isRunning(c) && workQueue.offer(command)) {
1330 int recheck = ctl.get();
1331 if (! isRunning(recheck) && remove(command))
1333 else if (workerCountOf(recheck) == 0)
1334 addWorker(null, false);
1336 else if (!addWorker(command, false))
1341 * Initiates an orderly shutdown in which previously submitted
1342 * tasks are executed, but no new tasks will be accepted.
1343 * Invocation has no additional effect if already shut down.
1345 * <p>This method does not wait for previously submitted tasks to
1346 * complete execution. Use {@link #awaitTermination awaitTermination}
1349 * @throws SecurityException {@inheritDoc}
1351 public void shutdown() {
1352 final ReentrantLock mainLock = this.mainLock;
1355 checkShutdownAccess();
1356 advanceRunState(SHUTDOWN);
1357 interruptIdleWorkers();
1358 onShutdown(); // hook for ScheduledThreadPoolExecutor
1366 * Attempts to stop all actively executing tasks, halts the
1367 * processing of waiting tasks, and returns a list of the tasks
1368 * that were awaiting execution. These tasks are drained (removed)
1369 * from the task queue upon return from this method.
1371 * <p>This method does not wait for actively executing tasks to
1372 * terminate. Use {@link #awaitTermination awaitTermination} to
1375 * <p>There are no guarantees beyond best-effort attempts to stop
1376 * processing actively executing tasks. This implementation
1377 * cancels tasks via {@link Thread#interrupt}, so any task that
1378 * fails to respond to interrupts may never terminate.
1380 * @throws SecurityException {@inheritDoc}
1382 public List<Runnable> shutdownNow() {
1383 List<Runnable> tasks;
1384 final ReentrantLock mainLock = this.mainLock;
1387 checkShutdownAccess();
1388 advanceRunState(STOP);
1390 tasks = drainQueue();
1398 public boolean isShutdown() {
1399 return ! isRunning(ctl.get());
1403 * Returns true if this executor is in the process of terminating
1404 * after {@link #shutdown} or {@link #shutdownNow} but has not
1405 * completely terminated. This method may be useful for
1406 * debugging. A return of {@code true} reported a sufficient
1407 * period after shutdown may indicate that submitted tasks have
1408 * ignored or suppressed interruption, causing this executor not
1409 * to properly terminate.
1411 * @return true if terminating but not yet terminated
1413 public boolean isTerminating() {
1415 return ! isRunning(c) && runStateLessThan(c, TERMINATED);
1418 public boolean isTerminated() {
1419 return runStateAtLeast(ctl.get(), TERMINATED);
1422 public boolean awaitTermination(long timeout, TimeUnit unit)
1423 throws InterruptedException {
1424 long nanos = unit.toNanos(timeout);
1425 final ReentrantLock mainLock = this.mainLock;
1429 if (runStateAtLeast(ctl.get(), TERMINATED))
1433 nanos = termination.awaitNanos(nanos);
1441 * Invokes {@code shutdown} when this executor is no longer
1442 * referenced and it has no threads.
1444 protected void finalize() {
1449 * Sets the thread factory used to create new threads.
1451 * @param threadFactory the new thread factory
1452 * @throws NullPointerException if threadFactory is null
1453 * @see #getThreadFactory
1455 public void setThreadFactory(ThreadFactory threadFactory) {
1456 if (threadFactory == null)
1457 throw new NullPointerException();
1458 this.threadFactory = threadFactory;
1462 * Returns the thread factory used to create new threads.
1464 * @return the current thread factory
1465 * @see #setThreadFactory
1467 public ThreadFactory getThreadFactory() {
1468 return threadFactory;
1472 * Sets a new handler for unexecutable tasks.
1474 * @param handler the new handler
1475 * @throws NullPointerException if handler is null
1476 * @see #getRejectedExecutionHandler
1478 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1479 if (handler == null)
1480 throw new NullPointerException();
1481 this.handler = handler;
1485 * Returns the current handler for unexecutable tasks.
1487 * @return the current handler
1488 * @see #setRejectedExecutionHandler
1490 public RejectedExecutionHandler getRejectedExecutionHandler() {
1495 * Sets the core number of threads. This overrides any value set
1496 * in the constructor. If the new value is smaller than the
1497 * current value, excess existing threads will be terminated when
1498 * they next become idle. If larger, new threads will, if needed,
1499 * be started to execute any queued tasks.
1501 * @param corePoolSize the new core size
1502 * @throws IllegalArgumentException if {@code corePoolSize < 0}
1503 * @see #getCorePoolSize
1505 public void setCorePoolSize(int corePoolSize) {
1506 if (corePoolSize < 0)
1507 throw new IllegalArgumentException();
1508 int delta = corePoolSize - this.corePoolSize;
1509 this.corePoolSize = corePoolSize;
1510 if (workerCountOf(ctl.get()) > corePoolSize)
1511 interruptIdleWorkers();
1512 else if (delta > 0) {
1513 // We don't really know how many new threads are "needed".
1514 // As a heuristic, prestart enough new workers (up to new
1515 // core size) to handle the current number of tasks in
1516 // queue, but stop if queue becomes empty while doing so.
1517 int k = Math.min(delta, workQueue.size());
1518 while (k-- > 0 && addWorker(null, true)) {
1519 if (workQueue.isEmpty())
1526 * Returns the core number of threads.
1528 * @return the core number of threads
1529 * @see #setCorePoolSize
1531 public int getCorePoolSize() {
1532 return corePoolSize;
1536 * Starts a core thread, causing it to idly wait for work. This
1537 * overrides the default policy of starting core threads only when
1538 * new tasks are executed. This method will return {@code false}
1539 * if all core threads have already been started.
1541 * @return {@code true} if a thread was started
1543 public boolean prestartCoreThread() {
1544 return workerCountOf(ctl.get()) < corePoolSize &&
1545 addWorker(null, true);
1549 * Starts all core threads, causing them to idly wait for work. This
1550 * overrides the default policy of starting core threads only when
1551 * new tasks are executed.
1553 * @return the number of threads started
1555 public int prestartAllCoreThreads() {
1557 while (addWorker(null, true))
1563 * Returns true if this pool allows core threads to time out and
1564 * terminate if no tasks arrive within the keepAlive time, being
1565 * replaced if needed when new tasks arrive. When true, the same
1566 * keep-alive policy applying to non-core threads applies also to
1567 * core threads. When false (the default), core threads are never
1568 * terminated due to lack of incoming tasks.
1570 * @return {@code true} if core threads are allowed to time out,
1571 * else {@code false}
1575 public boolean allowsCoreThreadTimeOut() {
1576 return allowCoreThreadTimeOut;
1580 * Sets the policy governing whether core threads may time out and
1581 * terminate if no tasks arrive within the keep-alive time, being
1582 * replaced if needed when new tasks arrive. When false, core
1583 * threads are never terminated due to lack of incoming
1584 * tasks. When true, the same keep-alive policy applying to
1585 * non-core threads applies also to core threads. To avoid
1586 * continual thread replacement, the keep-alive time must be
1587 * greater than zero when setting {@code true}. This method
1588 * should in general be called before the pool is actively used.
1590 * @param value {@code true} if should time out, else {@code false}
1591 * @throws IllegalArgumentException if value is {@code true}
1592 * and the current keep-alive time is not greater than zero
1596 public void allowCoreThreadTimeOut(boolean value) {
1597 if (value && keepAliveTime <= 0)
1598 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1599 if (value != allowCoreThreadTimeOut) {
1600 allowCoreThreadTimeOut = value;
1602 interruptIdleWorkers();
1607 * Sets the maximum allowed number of threads. This overrides any
1608 * value set in the constructor. If the new value is smaller than
1609 * the current value, excess existing threads will be
1610 * terminated when they next become idle.
1612 * @param maximumPoolSize the new maximum
1613 * @throws IllegalArgumentException if the new maximum is
1614 * less than or equal to zero, or
1615 * less than the {@linkplain #getCorePoolSize core pool size}
1616 * @see #getMaximumPoolSize
1618 public void setMaximumPoolSize(int maximumPoolSize) {
1619 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1620 throw new IllegalArgumentException();
1621 this.maximumPoolSize = maximumPoolSize;
1622 if (workerCountOf(ctl.get()) > maximumPoolSize)
1623 interruptIdleWorkers();
1627 * Returns the maximum allowed number of threads.
1629 * @return the maximum allowed number of threads
1630 * @see #setMaximumPoolSize
1632 public int getMaximumPoolSize() {
1633 return maximumPoolSize;
1637 * Sets the time limit for which threads may remain idle before
1638 * being terminated. If there are more than the core number of
1639 * threads currently in the pool, after waiting this amount of
1640 * time without processing a task, excess threads will be
1641 * terminated. This overrides any value set in the constructor.
1643 * @param time the time to wait. A time value of zero will cause
1644 * excess threads to terminate immediately after executing tasks.
1645 * @param unit the time unit of the {@code time} argument
1646 * @throws IllegalArgumentException if {@code time} less than zero or
1647 * if {@code time} is zero and {@code allowsCoreThreadTimeOut}
1648 * @see #getKeepAliveTime
1650 public void setKeepAliveTime(long time, TimeUnit unit) {
1652 throw new IllegalArgumentException();
1653 if (time == 0 && allowsCoreThreadTimeOut())
1654 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1655 long keepAliveTime = unit.toNanos(time);
1656 long delta = keepAliveTime - this.keepAliveTime;
1657 this.keepAliveTime = keepAliveTime;
1659 interruptIdleWorkers();
1663 * Returns the thread keep-alive time, which is the amount of time
1664 * that threads in excess of the core pool size may remain
1665 * idle before being terminated.
1667 * @param unit the desired time unit of the result
1668 * @return the time limit
1669 * @see #setKeepAliveTime
1671 public long getKeepAliveTime(TimeUnit unit) {
1672 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1675 /* User-level queue utilities */
1678 * Returns the task queue used by this executor. Access to the
1679 * task queue is intended primarily for debugging and monitoring.
1680 * This queue may be in active use. Retrieving the task queue
1681 * does not prevent queued tasks from executing.
1683 * @return the task queue
1685 public BlockingQueue<Runnable> getQueue() {
1690 * Removes this task from the executor's internal queue if it is
1691 * present, thus causing it not to be run if it has not already
1694 * <p> This method may be useful as one part of a cancellation
1695 * scheme. It may fail to remove tasks that have been converted
1696 * into other forms before being placed on the internal queue. For
1697 * example, a task entered using {@code submit} might be
1698 * converted into a form that maintains {@code Future} status.
1699 * However, in such cases, method {@link #purge} may be used to
1700 * remove those Futures that have been cancelled.
1702 * @param task the task to remove
1703 * @return true if the task was removed
1705 public boolean remove(Runnable task) {
1706 boolean removed = workQueue.remove(task);
1707 tryTerminate(); // In case SHUTDOWN and now empty
1712 * Tries to remove from the work queue all {@link Future}
1713 * tasks that have been cancelled. This method can be useful as a
1714 * storage reclamation operation, that has no other impact on
1715 * functionality. Cancelled tasks are never executed, but may
1716 * accumulate in work queues until worker threads can actively
1717 * remove them. Invoking this method instead tries to remove them now.
1718 * However, this method may fail to remove tasks in
1719 * the presence of interference by other threads.
1721 public void purge() {
1722 final BlockingQueue<Runnable> q = workQueue;
1724 Iterator<Runnable> it = q.iterator();
1725 while (it.hasNext()) {
1726 Runnable r = it.next();
1727 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1730 } catch (ConcurrentModificationException fallThrough) {
1731 // Take slow path if we encounter interference during traversal.
1732 // Make copy for traversal and call remove for cancelled entries.
1733 // The slow path is more likely to be O(N*N).
1734 for (Object r : q.toArray())
1735 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1739 tryTerminate(); // In case SHUTDOWN and now empty
1745 * Returns the current number of threads in the pool.
1747 * @return the number of threads
1749 public int getPoolSize() {
1750 final ReentrantLock mainLock = this.mainLock;
1753 // Remove rare and surprising possibility of
1754 // isTerminated() && getPoolSize() > 0
1755 return runStateAtLeast(ctl.get(), TIDYING) ? 0
1763 * Returns the approximate number of threads that are actively
1766 * @return the number of threads
1768 public int getActiveCount() {
1769 final ReentrantLock mainLock = this.mainLock;
1773 for (Worker w : workers)
1783 * Returns the largest number of threads that have ever
1784 * simultaneously been in the pool.
1786 * @return the number of threads
1788 public int getLargestPoolSize() {
1789 final ReentrantLock mainLock = this.mainLock;
1792 return largestPoolSize;
1799 * Returns the approximate total number of tasks that have ever been
1800 * scheduled for execution. Because the states of tasks and
1801 * threads may change dynamically during computation, the returned
1802 * value is only an approximation.
1804 * @return the number of tasks
1806 public long getTaskCount() {
1807 final ReentrantLock mainLock = this.mainLock;
1810 long n = completedTaskCount;
1811 for (Worker w : workers) {
1812 n += w.completedTasks;
1816 return n + workQueue.size();
1823 * Returns the approximate total number of tasks that have
1824 * completed execution. Because the states of tasks and threads
1825 * may change dynamically during computation, the returned value
1826 * is only an approximation, but one that does not ever decrease
1827 * across successive calls.
1829 * @return the number of tasks
1831 public long getCompletedTaskCount() {
1832 final ReentrantLock mainLock = this.mainLock;
1835 long n = completedTaskCount;
1836 for (Worker w : workers)
1837 n += w.completedTasks;
1845 * Returns a string identifying this pool, as well as its state,
1846 * including indications of run state and estimated worker and
1849 * @return a string identifying this pool, as well as its state
1851 public String toString() {
1853 int nworkers, nactive;
1854 final ReentrantLock mainLock = this.mainLock;
1857 ncompleted = completedTaskCount;
1859 nworkers = workers.size();
1860 for (Worker w : workers) {
1861 ncompleted += w.completedTasks;
1869 String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
1870 (runStateAtLeast(c, TERMINATED) ? "Terminated" :
1872 return super.toString() +
1874 ", pool size = " + nworkers +
1875 ", active threads = " + nactive +
1876 ", queued tasks = " + workQueue.size() +
1877 ", completed tasks = " + ncompleted +
1881 /* Extension hooks */
1884 * Method invoked prior to executing the given Runnable in the
1885 * given thread. This method is invoked by thread {@code t} that
1886 * will execute task {@code r}, and may be used to re-initialize
1887 * ThreadLocals, or to perform logging.
1889 * <p>This implementation does nothing, but may be customized in
1890 * subclasses. Note: To properly nest multiple overridings, subclasses
1891 * should generally invoke {@code super.beforeExecute} at the end of
1894 * @param t the thread that will run task {@code r}
1895 * @param r the task that will be executed
1897 protected void beforeExecute(Thread t, Runnable r) { }
1900 * Method invoked upon completion of execution of the given Runnable.
1901 * This method is invoked by the thread that executed the task. If
1902 * non-null, the Throwable is the uncaught {@code RuntimeException}
1903 * or {@code Error} that caused execution to terminate abruptly.
1905 * <p>This implementation does nothing, but may be customized in
1906 * subclasses. Note: To properly nest multiple overridings, subclasses
1907 * should generally invoke {@code super.afterExecute} at the
1908 * beginning of this method.
1910 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1911 * {@link FutureTask}) either explicitly or via methods such as
1912 * {@code submit}, these task objects catch and maintain
1913 * computational exceptions, and so they do not cause abrupt
1914 * termination, and the internal exceptions are <em>not</em>
1915 * passed to this method. If you would like to trap both kinds of
1916 * failures in this method, you can further probe for such cases,
1917 * as in this sample subclass that prints either the direct cause
1918 * or the underlying exception if a task has been aborted:
1921 * class ExtendedExecutor extends ThreadPoolExecutor {
1923 * protected void afterExecute(Runnable r, Throwable t) {
1924 * super.afterExecute(r, t);
1925 * if (t == null && r instanceof Future<?>) {
1927 * Object result = ((Future<?>) r).get();
1928 * } catch (CancellationException ce) {
1930 * } catch (ExecutionException ee) {
1931 * t = ee.getCause();
1932 * } catch (InterruptedException ie) {
1933 * Thread.currentThread().interrupt(); // ignore/reset
1937 * System.out.println(t);
1941 * @param r the runnable that has completed
1942 * @param t the exception that caused termination, or null if
1943 * execution completed normally
1945 protected void afterExecute(Runnable r, Throwable t) { }
1948 * Method invoked when the Executor has terminated. Default
1949 * implementation does nothing. Note: To properly nest multiple
1950 * overridings, subclasses should generally invoke
1951 * {@code super.terminated} within this method.
1953 protected void terminated() { }
1955 /* Predefined RejectedExecutionHandlers */
1958 * A handler for rejected tasks that runs the rejected task
1959 * directly in the calling thread of the {@code execute} method,
1960 * unless the executor has been shut down, in which case the task
1963 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1965 * Creates a {@code CallerRunsPolicy}.
1967 public CallerRunsPolicy() { }
1970 * Executes task r in the caller's thread, unless the executor
1971 * has been shut down, in which case the task is discarded.
1973 * @param r the runnable task requested to be executed
1974 * @param e the executor attempting to execute this task
1976 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1977 if (!e.isShutdown()) {
1984 * A handler for rejected tasks that throws a
1985 * {@code RejectedExecutionException}.
1987 public static class AbortPolicy implements RejectedExecutionHandler {
1989 * Creates an {@code AbortPolicy}.
1991 public AbortPolicy() { }
1994 * Always throws RejectedExecutionException.
1996 * @param r the runnable task requested to be executed
1997 * @param e the executor attempting to execute this task
1998 * @throws RejectedExecutionException always.
2000 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
2001 throw new RejectedExecutionException("Task " + r.toString() +
2008 * A handler for rejected tasks that silently discards the
2011 public static class DiscardPolicy implements RejectedExecutionHandler {
2013 * Creates a {@code DiscardPolicy}.
2015 public DiscardPolicy() { }
2018 * Does nothing, which has the effect of discarding task r.
2020 * @param r the runnable task requested to be executed
2021 * @param e the executor attempting to execute this task
2023 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
2028 * A handler for rejected tasks that discards the oldest unhandled
2029 * request and then retries {@code execute}, unless the executor
2030 * is shut down, in which case the task is discarded.
2032 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
2034 * Creates a {@code DiscardOldestPolicy} for the given executor.
2036 public DiscardOldestPolicy() { }
2039 * Obtains and ignores the next task that the executor
2040 * would otherwise execute, if one is immediately available,
2041 * and then retries execution of task r, unless the executor
2042 * is shut down, in which case task r is instead discarded.
2044 * @param r the runnable task requested to be executed
2045 * @param e the executor attempting to execute this task
2047 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
2048 if (!e.isShutdown()) {
2049 e.getQueue().poll();