ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.167
Committed: Thu Sep 1 00:06:20 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.166: +3 -0 lines
Log Message:
add TODO

File Contents

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