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