ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.158
Committed: Fri Jan 30 12:49:21 2015 UTC (9 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.157: +4 -3 lines
Log Message:
Documentation improvements

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