ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.127
Committed: Thu Dec 22 23:30:40 2011 UTC (12 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.126: +4 -2 lines
Log Message:
fix imports

File Contents

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