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