ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.198
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.197: +3 -1 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

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