ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.155
Committed: Thu Oct 9 17:29:59 2014 UTC (9 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.154: +1 -0 lines
Log Message:
add assert comment

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