ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.164
Committed: Sun Sep 20 17:03:23 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.163: +2 -2 lines
Log Message:
Terminate javadoc with a period.

File Contents

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