ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.116
Committed: Tue Jan 30 03:43:07 2007 UTC (17 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.115: +189 -180 lines
Log Message:
TPE/STPE review rework

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