ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.111
Committed: Mon Sep 4 06:57:50 2006 UTC (17 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.110: +10 -23 lines
Log Message:
purge

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     * http://creativecommons.org/licenses/publicdomain
5 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.9 import java.util.concurrent.locks.*;
9 dl 1.107 import java.util.concurrent.atomic.*;
10 dl 1.2 import java.util.*;
11 tim 1.1
12     /**
13 dl 1.17 * An {@link ExecutorService} that executes each submitted task using
14 dl 1.28 * one of possibly several pooled threads, normally configured
15     * using {@link Executors} factory methods.
16 tim 1.1 *
17 dl 1.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 dl 1.20 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
23 dl 1.22 * statistics, such as the number of completed tasks.
24 dl 1.17 *
25 tim 1.1 * <p>To be useful across a wide range of contexts, this class
26 dl 1.24 * provides many adjustable parameters and extensibility
27     * hooks. However, programmers are urged to use the more convenient
28 dl 1.20 * {@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 dl 1.22 * preconfigure settings for the most common usage
34     * scenarios. Otherwise, use the following guide when manually
35 dl 1.24 * configuring and tuning this class:
36 dl 1.17 *
37 tim 1.1 * <dl>
38 dl 1.2 *
39 dl 1.21 * <dt>Core and maximum pool sizes</dt>
40 dl 1.2 *
41 dl 1.19 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
42 jsr166 1.66 * pool size
43 dl 1.21 * (see {@link ThreadPoolExecutor#getPoolSize})
44 jsr166 1.66 * according to the bounds set by corePoolSize
45 dl 1.21 * (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 <tt>Integer.MAX_VALUE</tt>, you allow the pool to
58 dl 1.27 * accommodate an arbitrary number of concurrent tasks. Most typically,
59 dl 1.21 * 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 jsr166 1.93 * ThreadPoolExecutor#setMaximumPoolSize}. </dd>
63 dl 1.2 *
64 jsr166 1.93 * <dt>On-demand construction</dt>
65 dl 1.2 *
66 dl 1.21 * <dd> By default, even core threads are initially created and
67 dl 1.69 * started only when new tasks arrive, but this can be overridden
68 dl 1.21 * dynamically using method {@link
69     * ThreadPoolExecutor#prestartCoreThread} or
70 dl 1.64 * {@link ThreadPoolExecutor#prestartAllCoreThreads}.
71     * You probably want to prestart threads if you construct the
72     * pool with a non-empty queue. </dd>
73 dl 1.2 *
74 tim 1.1 * <dt>Creating new threads</dt>
75 dl 1.2 *
76 dl 1.33 * <dd>New threads are created using a {@link
77     * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
78 dl 1.107 * {@link Executors#defaultThreadFactory} is used, that creates
79     * threads to all be in the same {@link ThreadGroup} and with the same
80 dl 1.33 * <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying
81     * a different ThreadFactory, you can alter the thread's name, thread
82 dl 1.107 * group, priority, daemon status, etc. If a <tt>ThreadFactory</tt>
83     * fails to create a thread when asked by returning null from
84     * <tt>newThread</tt>, the executor will continue, but might not be
85     * able to execute any tasks. Threads should possess the
86     * "modifyThread" <tt>RuntimePermission</tt>. 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 dl 1.2 *
92 dl 1.21 * <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 dl 1.62 * constructed. This parameter can also be changed dynamically using
101     * method {@link ThreadPoolExecutor#setKeepAliveTime}. Using a value
102     * of <tt>Long.MAX_VALUE</tt> {@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} can be used to apply
107 dl 1.64 * this time-out policy to core threads as well, so long as
108     * the keepAliveTime value is non-zero. </dd>
109 dl 1.21 *
110 dl 1.48 * <dt>Queuing</dt>
111 dl 1.21 *
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 dl 1.2 *
115 dl 1.21 * <ul>
116     *
117 dl 1.23 * <li> If fewer than corePoolSize threads are running, the Executor
118     * always prefers adding a new thread
119 dl 1.48 * rather than queuing.</li>
120 dl 1.21 *
121 dl 1.23 * <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 jsr166 1.66 *
125 dl 1.21 * <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 dl 1.24 * avoid rejection of new submitted tasks. This in turn admits the
142 dl 1.21 * 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 dl 1.69 * capacity) will cause new tasks to wait in the queue when all
148 dl 1.22 * 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 dl 1.21 *
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 dl 1.27 * lead to artificially low throughput. If tasks frequently block (for
165 dl 1.21 * 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 dl 1.24 * generally requires larger pool sizes, which keeps CPUs busier but
168     * may encounter unacceptable scheduling overhead, which also
169     * decreases throughput. </li>
170 dl 1.21 *
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 dl 1.22 * saturated. In either case, the <tt>execute</tt> method invokes the
182     * {@link RejectedExecutionHandler#rejectedExecution} method of its
183     * {@link RejectedExecutionHandler}. Four predefined handler policies
184     * are provided:
185 dl 1.21 *
186     * <ol>
187     *
188     * <li> In the
189     * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
190     * runtime {@link RejectedExecutionException} upon rejection. </li>
191 jsr166 1.66 *
192 dl 1.21 * <li> In {@link
193     * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
194     * <tt>execute</tt> 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 dl 1.48 * capacity or queuing policies. </dd>
213 dl 1.21 *
214     * <dt>Hook methods</dt>
215     *
216 dl 1.23 * <dd>This class provides <tt>protected</tt> overridable {@link
217 dl 1.21 * ThreadPoolExecutor#beforeExecute} and {@link
218     * ThreadPoolExecutor#afterExecute} methods that are called before and
219 dl 1.19 * after execution of each task. These can be used to manipulate the
220 dl 1.59 * execution environment; for example, reinitializing ThreadLocals,
221 dl 1.21 * 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 jsr166 1.66 * fully terminated.
225 dl 1.57 *
226 jsr166 1.66 * <p>If hook or callback methods throw
227 dl 1.57 * exceptions, internal worker threads may in turn fail and
228 jsr166 1.66 * abruptly terminate.</dd>
229 dl 1.2 *
230 dl 1.21 * <dt>Queue maintenance</dt>
231 dl 1.2 *
232 dl 1.24 * <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 jsr166 1.80 * cancelled.</dd>
239 dl 1.79 *
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 <tt>shutdown</tt>
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}. </dd> </dl>
250 tim 1.1 *
251 dl 1.43 * <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>
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 jsr166 1.66 *
263 dl 1.43 * protected void beforeExecute(Thread t, Runnable r) {
264     * super.beforeExecute(t, r);
265     * pauseLock.lock();
266     * try {
267     * while (isPaused) unpaused.await();
268 jsr166 1.66 * } catch (InterruptedException ie) {
269 dl 1.53 * t.interrupt();
270 dl 1.43 * } finally {
271 dl 1.53 * pauseLock.unlock();
272 dl 1.43 * }
273     * }
274 jsr166 1.66 *
275 dl 1.43 * public void pause() {
276     * pauseLock.lock();
277     * try {
278     * isPaused = true;
279     * } finally {
280 dl 1.53 * pauseLock.unlock();
281 dl 1.43 * }
282     * }
283 jsr166 1.66 *
284 dl 1.43 * public void resume() {
285     * pauseLock.lock();
286     * try {
287     * isPaused = false;
288     * unpaused.signalAll();
289     * } finally {
290 dl 1.53 * pauseLock.unlock();
291 dl 1.43 * }
292     * }
293     * }
294     * </pre>
295 tim 1.1 * @since 1.5
296 dl 1.8 * @author Doug Lea
297 tim 1.1 */
298 tim 1.38 public class ThreadPoolExecutor extends AbstractExecutorService {
299 dl 1.86 /**
300 dl 1.107 * 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 jsr166 1.110 * transiently different from the actual number of live threads,
315 dl 1.107 * 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 dl 1.86 *
322 dl 1.85 * RUNNING: Accept new tasks and process queued tasks
323     * SHUTDOWN: Don't accept new tasks, but process queued tasks
324 jsr166 1.91 * STOP: Don't accept new tasks, don't process queued tasks,
325 dl 1.85 * and interrupt in-progress tasks
326 jsr166 1.91 * TERMINATED: Same as STOP, plus all threads have terminated
327 dl 1.86 *
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 jsr166 1.87 *
332     * RUNNING -> SHUTDOWN
333 jsr166 1.88 * On invocation of shutdown(), perhaps implicitly in finalize()
334 jsr166 1.87 * (RUNNING or SHUTDOWN) -> STOP
335 dl 1.86 * On invocation of shutdownNow()
336     * SHUTDOWN -> TERMINATED
337     * When both queue and pool are empty
338     * STOP -> TERMINATED
339     * When pool is empty
340 dl 1.107 *
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 tim 1.41
363     /**
364 dl 1.86 * The queue used for holding tasks and handing off to worker
365 dl 1.107 * threads. We do not require that workQueue.poll() returning
366 jsr166 1.109 * null necessarily means that workQueue.isEmpty(), so rely
367 dl 1.107 * 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 tim 1.10 */
374 dl 1.2 private final BlockingQueue<Runnable> workQueue;
375    
376     /**
377 dl 1.107 * 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 tim 1.10 */
389 dl 1.2 private final ReentrantLock mainLock = new ReentrantLock();
390    
391     /**
392 dl 1.107 * 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 dl 1.2 * Wait condition to support awaitTermination
399 tim 1.10 */
400 dl 1.46 private final Condition termination = mainLock.newCondition();
401 dl 1.2
402     /**
403 dl 1.107 * 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 tim 1.10 */
438 dl 1.107 private volatile RejectedExecutionHandler handler;
439 dl 1.2
440     /**
441 dl 1.35 * Timeout in nanoseconds for idle threads waiting for work.
442 dl 1.86 * Threads use this timeout when there are more than corePoolSize
443     * present or if allowCoreThreadTimeOut. Otherwise they wait
444     * forever for new work.
445 tim 1.10 */
446 dl 1.107 private volatile long keepAliveTime;
447 dl 1.2
448     /**
449 jsr166 1.101 * 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 dl 1.62 */
453 dl 1.82 private volatile boolean allowCoreThreadTimeOut;
454 dl 1.62
455     /**
456 dl 1.107 * Core pool size is the minimum number of workers to keep alive
457     * (and not allow to time out etc) unless allowCoreThreadTimeOut
458 jsr166 1.109 * is set, in which case the minimum is zero.
459 dl 1.107 */
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 jsr166 1.108 * Class Worker mainly maintains interrupt control state for
499 dl 1.107 * 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 jsr166 1.108 /** Thread this worker is running in. Null if factory fails. */
508 dl 1.107 final Thread thread;
509 jsr166 1.108 /** Initial task to run. Possibly null. */
510 dl 1.107 Runnable firstTask;
511     /** Per-thread task counter */
512     volatile long completedTasks;
513    
514     /**
515 jsr166 1.108 * Creates with given first task and thread from ThreadFactory.
516     * @param firstTask the first task (null if none)
517 dl 1.107 */
518     Worker(Runnable firstTask) {
519     this.firstTask = firstTask;
520     this.thread = getThreadFactory().newThread(this);
521     }
522    
523     /** Delegates main run loop to outer runWorker */
524     public void run() {
525     runWorker(this);
526     }
527     }
528    
529     /*
530     * Methods for setting control state
531     */
532    
533     /**
534     * Transitions runState to given target, or leaves it alone if
535     * already at least the given target.
536     * @param targetState the desired state (not TERMINATED -- use
537     * tryTerminate)
538     */
539     private void advanceRunState(int targetState) {
540     for (;;) {
541     int c = ctl.get();
542     if (runStateOf(c) >= targetState ||
543     ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
544     break;
545     }
546     }
547    
548     /**
549     * Transitions to TERMINATED state if either (SHUTDOWN and pool
550     * and queue empty) or (STOP and pool empty). If otherwise
551     * eligible to terminate but workerCount is nonzero, interrupts an
552     * idle worker to ensure that shutdown signals propagate. This
553     * method must be called following any action that might make
554     * termination possible -- reducing worker count or removing tasks
555     * from the queue during shutdown. The method is non-private to
556 jsr166 1.110 * allow access from ScheduledThreadPoolExecutor.
557 dl 1.107 */
558     final void tryTerminate() {
559     for (;;) {
560     int c = ctl.get();
561     int rs = runStateOf(c);
562     if (rs < SHUTDOWN || rs == TERMINATED ||
563     (rs == SHUTDOWN && !workQueue.isEmpty()))
564     return;
565     if (workerCountOf(c) != 0) { // Eligible to terminate
566     interruptIdleWorkers(true);
567     return;
568     }
569     if (ctl.compareAndSet(c, ctlOf(TERMINATED, 0))) {
570     mainLock.lock();
571     try {
572     termination.signalAll();
573     } finally {
574     mainLock.unlock();
575     }
576     terminated();
577     return;
578     }
579     // else retry on failed CAS
580     }
581     }
582    
583     /**
584     * Decrements the workerCount field of ctl. This is called only on
585     * abrupt termination of a thread (see processWorkerExit). Other
586     * decrements are performed within getTask.
587     */
588     private void decrementWorkerCount() {
589     for (;;) {
590     int c = ctl.get();
591     if (ctl.compareAndSet(c, ctlOf(runStateOf(c), workerCountOf(c)-1)))
592     break;
593     }
594     }
595    
596     /*
597     * Methods for controlling interrupts to worker threads.
598     */
599    
600     /**
601     * If there is a security manager, makes sure caller has
602     * permission to shut down threads in general (see shutdownPerm).
603     * If this passes, additionally makes sure the caller is allowed
604     * to interrupt each worker thread. This might not be true even if
605     * first check passed, if the SecurityManager treats some threads
606     * specially.
607     */
608     private void checkShutdownAccess() {
609     SecurityManager security = System.getSecurityManager();
610     if (security != null) {
611     security.checkPermission(shutdownPerm);
612     final ReentrantLock mainLock = this.mainLock;
613     mainLock.lock();
614     try {
615     for (Worker w : workers)
616     security.checkAccess(w.thread);
617     } finally {
618     mainLock.unlock();
619     }
620     }
621     }
622    
623     /**
624     * Interrupts up all threads, even if active. Ignores
625     * SecurityExceptions (in which case some threads may remain
626     * uninterrupted).
627     */
628     private void interruptWorkers() {
629     final ReentrantLock mainLock = this.mainLock;
630     mainLock.lock();
631     try {
632     for (Worker w: workers) {
633     try {
634     w.thread.interrupt();
635     } catch (SecurityException ignore) {
636     }
637     }
638     } finally {
639     mainLock.unlock();
640     }
641     }
642    
643     /**
644     * Interrupts threads that might be waiting for tasks (as
645     * indicated by not being locked) so they can check for
646     * termination or configuration changes. Ignores
647     * SecurityExceptions (in which case some threads may remain
648     * uninterrupted).
649     *
650     * @param onlyOne If true, interrupt at most one worker. This is
651     * called only from tryTerminate when termination is otherwise
652     * enabled but there are still other workers. In this case, at
653     * most one waiting worker is interrupted to propagate shutdown
654     * signals in case all threads are currently waiting. This
655     * suffices because all waiting workers existing at point of a
656     * shutdown() call must have already been interrupted.
657     * Interrupting any arbitrary thread ensures that newly arriving
658     * workers since shutdown began will also eventually exit.
659 tim 1.10 */
660 dl 1.107 private void interruptIdleWorkers(boolean onlyOne) {
661     final ReentrantLock mainLock = this.mainLock;
662     mainLock.lock();
663     try {
664     Iterator<Worker> it = workers.iterator();
665     while (it.hasNext()) {
666     Worker w = it.next();
667     Thread t = w.thread;
668     if (!t.isInterrupted() && w.tryLock()) {
669     try {
670     t.interrupt();
671     } catch (SecurityException ignore) {
672     } finally {
673     w.unlock();
674     }
675     }
676     if (onlyOne)
677     break;
678     }
679     } finally {
680     mainLock.unlock();
681     }
682     }
683    
684     /**
685     * Ensures that unless the pool is stopping, the current thread
686     * does not have its interrupt set. This requires a double-check
687     * of state in case the interrupt was cleared concurrently with a
688     * shutdownNow -- if so, the interrupt is re-enabled.
689     */
690     private void clearInterruptsForTaskRun() {
691     if (runStateOf(ctl.get()) < STOP &&
692     Thread.interrupted() &&
693     runStateOf(ctl.get()) >= STOP)
694     Thread.currentThread().interrupt();
695     }
696    
697     /*
698     * Misc utilities, most of which are also exported to
699     * ScheduledThreadPoolExecutor
700     */
701    
702     /**
703     * Invokes the rejected execution handler for the given command.
704     * Package-protected for use by ScheduledThreadPoolExecutor.
705     */
706     final void reject(Runnable command) {
707     handler.rejectedExecution(command, this);
708     }
709 dl 1.2
710     /**
711 dl 1.107 * Performs any further cleanup following run state transition on
712     * invocation of shutdown. A no-op here, but used by
713     * ScheduledThreadPoolExecutor to cancel delayed tasks.
714 tim 1.10 */
715 dl 1.107 void onShutdown() {
716     }
717 dl 1.2
718     /**
719 dl 1.107 * State check needed by ScheduledThreadPoolExecutor to
720     * enable running tasks during shutdown;
721     * @param shutdownOK true if should return true if SHUTDOWN
722 tim 1.10 */
723 dl 1.107 final boolean isRunningOrShutdown(boolean shutdownOK) {
724     int rs = runStateOf(ctl.get());
725     return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
726     }
727 dl 1.2
728     /**
729 dl 1.107 * Drains the task queue into a new list, normally using
730     * drainTo. But if the queue is a DelayQueue or any other kind of
731     * queue for which poll or drainTo may fail to remove some
732     * elements, it deletes them one by one.
733     */
734     private List<Runnable> drainQueue() {
735     BlockingQueue<Runnable> q = workQueue;
736     List<Runnable> taskList = new ArrayList<Runnable>();
737     q.drainTo(taskList);
738     if (!q.isEmpty()) {
739     for (Runnable r : q.toArray(new Runnable[0])) {
740     if (q.remove(r))
741     taskList.add(r);
742     }
743     }
744     return taskList;
745     }
746    
747     /*
748     * Methods for creating, running and cleaning up after workers
749 tim 1.10 */
750 dl 1.2
751     /**
752 dl 1.107 * Checks if a new worker can be added with respect to current
753     * pool state and the given bound (either core or maximum). If so
754     * the worker count is adjusted accordingly, and, if possible, a
755     * new worker is created and started running firstTask as its
756     * first task, This method returns false if the pool is stopped or
757     * eligible to shut down. It also returns false if the thread
758     * factory fails to create a thread when asked, which requires a
759     * backout of workerCount, and a recheck for termination, in case
760     * the existence of this worker was holding up termination.
761     *
762     * @param firstTask the task the new thread should run first (or
763     * null if none). Workers are created with an initial first task
764     * (in method execute()) to bypass queuing when there are fewer
765     * than corePoolSize threads (in which case we always start one),
766 jsr166 1.110 * or when the queue is full (in which case we must bypass queue).
767 dl 1.107 * Initially idle threads are usually created via
768     * prestartCoreThread or to replace other dying workers.
769     *
770     * @param core if true use corePoolSize as bound, else
771 jsr166 1.110 * maximumPoolSize. (A boolean indicator is used here rather than a
772 dl 1.107 * value to ensure reads of fresh values after checking other pool
773     * state).
774     * @return true if successful
775 tim 1.10 */
776 dl 1.107 private boolean addWorker(Runnable firstTask, boolean core) {
777     for (;;) {
778     int c = ctl.get();
779     int rs = runStateOf(c);
780     // Check if queue empty only if necessary, and re-read ctl
781     // after this call to check if still same run state
782     if (rs == SHUTDOWN) {
783     if (workQueue.isEmpty())
784     return false;
785     if (runStateOf(c = ctl.get()) != rs)
786     continue;
787     }
788     int wc = workerCountOf(c);
789     if (rs > SHUTDOWN ||
790     wc >= CAPACITY ||
791 jsr166 1.110 wc >= (core ? corePoolSize : maximumPoolSize))
792 dl 1.107 return false;
793     if (ctl.compareAndSet(c, ctlOf(rs, wc+1)))
794     break;
795     }
796    
797     Worker w = new Worker(firstTask);
798     Thread t = w.thread;
799 jsr166 1.109 if (t == null) { // Back out on ThreadFactory failure
800 dl 1.107 decrementWorkerCount();
801     tryTerminate();
802     return false;
803     }
804    
805     final ReentrantLock mainLock = this.mainLock;
806     mainLock.lock();
807     try {
808     workers.add(w);
809     int s = workers.size();
810     if (s > largestPoolSize)
811     largestPoolSize = s;
812     } finally {
813     mainLock.unlock();
814     }
815    
816     t.start();
817     return true;
818     }
819 dl 1.2
820     /**
821 dl 1.107 * Performs cleanup and bookkeeping for a dying worker. Called
822     * only from worker threads. Unless completedAbruptly is set,
823     * assumes that workerCount has already been adjusted to account
824     * for exit. This method removes thread from worker set, and
825     * possibly terminates the pool or replaces the worker if either
826     * it exited due to user task exception or if fewer than
827     * corePoolSize workers are running or queue is non-empty but
828     * there are no workers.
829     *
830     * @param w the worker
831     * @param completedAbruptly if the worker died due to user exception
832 tim 1.10 */
833 dl 1.107 private void processWorkerExit(Worker w, boolean completedAbruptly) {
834     if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
835     decrementWorkerCount();
836    
837     final ReentrantLock mainLock = this.mainLock;
838     mainLock.lock();
839     try {
840     completedTaskCount += w.completedTasks;
841     workers.remove(w);
842     } finally {
843     mainLock.unlock();
844     }
845    
846     tryTerminate();
847    
848     if (!completedAbruptly) {
849 jsr166 1.110 int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
850 dl 1.107 if (min == 0 && !workQueue.isEmpty())
851     min = 1;
852     int c = ctl.get();
853     if (workerCountOf(c) >= min || runStateOf(c) >= STOP)
854     return; // replacement not needed
855     }
856     addWorker(null, false);
857     }
858 dl 1.2
859     /**
860 dl 1.107 * Performs blocking or timed wait for a task, depending on
861     * current configuration settings, or returns null if this worker
862     * must exit because of any of:
863     * 1. There are more than maximumPoolSize workers (due to
864     * a call to setMaximumPoolSize).
865 jsr166 1.110 * 2. The pool is stopped.
866 dl 1.107 * 3. The queue is empty, and either the pool is shutdown,
867     * or the thread has already timed out at least once
868     * waiting for a task, and would otherwise enter another
869     * timed wait.
870     *
871     * @return task, or null if the worker must exit, in which case
872     * workerCount is decremented
873 tim 1.10 */
874 dl 1.107 private Runnable getTask() {
875     /*
876     * Variable "empty" tracks whether the queue appears to be
877     * empty in case we need to know to check exit. This is set
878     * true on time-out from timed poll as an indicator of likely
879     * emptiness, in which case it is rechecked explicitly via
880     * isEmpty when deciding whether to exit. Emptiness must also
881     * be checked in state SHUTDOWN. The variable is initialized
882     * false to indicate lack of prior timeout, and left false
883     * until otherwise required to check.
884     */
885     boolean empty = false;
886     for (;;) {
887     int c = ctl.get();
888     int rs = runStateOf(c);
889     if (rs == SHUTDOWN || empty) {
890     empty = workQueue.isEmpty();
891     if (runStateOf(c = ctl.get()) != rs)
892     continue; // retry if state changed
893     }
894    
895     int wc = workerCountOf(c);
896     boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
897    
898     // Try to exit if too many threads, shutting down, and/or timed out
899     if (wc > maximumPoolSize || rs > SHUTDOWN ||
900     (empty && (timed || rs == SHUTDOWN))) {
901     if (ctl.compareAndSet(c, ctlOf(rs, wc-1)))
902     return null;
903     else
904     continue; // retry on CAS failure
905     }
906    
907     try {
908 jsr166 1.110 Runnable r = timed ?
909 dl 1.107 workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
910     workQueue.take();
911     if (r != null)
912     return r;
913     empty = true; // queue probably empty; recheck above
914 jsr166 1.108 } catch (InterruptedException retry) {
915 dl 1.107 }
916     }
917     }
918 jsr166 1.66
919 dl 1.8 /**
920 dl 1.107 * Main worker run loop. Repeatedly gets tasks from queue and
921     * executes them, while coping with a number of issues:
922     *
923     * 1. We may start out with an initial task, in which case we
924     * don't need to get the first one. Otherwise, as long as pool is
925     * running, we get tasks from getTask. If it returns null then the
926     * worker exits due to changed pool state or configuration
927     * parameters. Other exits result from exception throws in
928     * external code, in which case completedAbruptly holds, which
929     * usually leads processWorkerExit to replace this thread.
930     *
931     * 2. Before running any task, the lock is acquired to prevent
932 jsr166 1.108 * other pool interrupts while the task is executing, and
933 dl 1.107 * clearInterruptsForTaskRun called to ensure that unless pool is
934     * stopping, this thread does not have its interrupt set.
935     *
936     * 3. Each task run is preceded by a call to beforeExecute, which
937     * might throw an exception, in which case we cause thread to die
938     * (breaking loop with completedAbruptly true) without processing
939     * the task.
940     *
941     * 4. Assuming beforeExecute completes normally, we run the task,
942     * gathering any of its thrown exceptions to send to
943     * afterExecute. We separately handle RuntimeException, Error
944     * (both of which the specs guarantee that we trap) and arbitrary
945     * Throwables. Because we cannot rethrow Throwables within
946     * Runnable.run, we wrap them within Errors on the way out (to the
947     * thread's UncaughtExceptionHandler). Any thrown exception also
948     * conservatively causes thread to die.
949     *
950     * 5. After task.run completes, we call afterExecute, which may
951     * also throw an exception, which will also cause thread to
952     * die. According to JLS Sec 14.20, this exception is the one that
953     * will be in effect even if task.run throws.
954     *
955     * The net effect of the exception mechanics is that afterExecute
956     * and the thread's UncaughtExceptionHandler have as accurate
957     * information as we can provide about any problems encountered by
958     * user code.
959     *
960     * @param w the worker
961 dl 1.8 */
962 dl 1.107 final void runWorker(Worker w) {
963     Runnable task = w.firstTask;
964     w.firstTask = null;
965     boolean completedAbruptly = true;
966     try {
967     while (task != null || (task = getTask()) != null) {
968     w.lock();
969     clearInterruptsForTaskRun();
970     try {
971     beforeExecute(w.thread, task);
972     Throwable thrown = null;
973     try {
974     task.run();
975     } catch (RuntimeException x) {
976     thrown = x; throw x;
977     } catch (Error x) {
978     thrown = x; throw x;
979     } catch (Throwable x) {
980     thrown = x; throw new Error(x);
981     } finally {
982     afterExecute(task, thrown);
983     }
984     } finally {
985     task = null;
986     w.completedTasks++;
987     w.unlock();
988     }
989     }
990     completedAbruptly = false;
991     } finally {
992     processWorkerExit(w, completedAbruptly);
993     }
994     }
995 dl 1.2
996 dl 1.107 // Public constructors and methods
997 dl 1.86
998 dl 1.2 /**
999 dl 1.86 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1000     * parameters and default thread factory and rejected execution handler.
1001     * It may be more convenient to use one of the {@link Executors} factory
1002     * methods instead of this general purpose constructor.
1003     *
1004     * @param corePoolSize the number of threads to keep in the
1005     * pool, even if they are idle.
1006     * @param maximumPoolSize the maximum number of threads to allow in the
1007     * pool.
1008     * @param keepAliveTime when the number of threads is greater than
1009     * the core, this is the maximum time that excess idle threads
1010     * will wait for new tasks before terminating.
1011     * @param unit the time unit for the keepAliveTime
1012     * argument.
1013     * @param workQueue the queue to use for holding tasks before they
1014     * are executed. This queue will hold only the <tt>Runnable</tt>
1015     * tasks submitted by the <tt>execute</tt> method.
1016 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1017 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1018     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1019     * @throws NullPointerException if <tt>workQueue</tt> is null
1020     */
1021     public ThreadPoolExecutor(int corePoolSize,
1022     int maximumPoolSize,
1023     long keepAliveTime,
1024     TimeUnit unit,
1025     BlockingQueue<Runnable> workQueue) {
1026     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1027     Executors.defaultThreadFactory(), defaultHandler);
1028     }
1029    
1030     /**
1031     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1032     * parameters and default rejected execution handler.
1033     *
1034     * @param corePoolSize the number of threads to keep in the
1035     * pool, even if they are idle.
1036     * @param maximumPoolSize the maximum number of threads to allow in the
1037     * pool.
1038     * @param keepAliveTime when the number of threads is greater than
1039     * the core, this is the maximum time that excess idle threads
1040     * will wait for new tasks before terminating.
1041     * @param unit the time unit for the keepAliveTime
1042     * argument.
1043     * @param workQueue the queue to use for holding tasks before they
1044     * are executed. This queue will hold only the <tt>Runnable</tt>
1045     * tasks submitted by the <tt>execute</tt> method.
1046     * @param threadFactory the factory to use when the executor
1047     * creates a new thread.
1048 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1049 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1050     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1051     * @throws NullPointerException if <tt>workQueue</tt>
1052     * or <tt>threadFactory</tt> are null.
1053     */
1054     public ThreadPoolExecutor(int corePoolSize,
1055     int maximumPoolSize,
1056     long keepAliveTime,
1057     TimeUnit unit,
1058     BlockingQueue<Runnable> workQueue,
1059     ThreadFactory threadFactory) {
1060     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1061     threadFactory, defaultHandler);
1062     }
1063    
1064     /**
1065     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1066     * parameters and default thread factory.
1067     *
1068     * @param corePoolSize the number of threads to keep in the
1069     * pool, even if they are idle.
1070     * @param maximumPoolSize the maximum number of threads to allow in the
1071     * pool.
1072     * @param keepAliveTime when the number of threads is greater than
1073     * the core, this is the maximum time that excess idle threads
1074     * will wait for new tasks before terminating.
1075     * @param unit the time unit for the keepAliveTime
1076     * argument.
1077     * @param workQueue the queue to use for holding tasks before they
1078     * are executed. This queue will hold only the <tt>Runnable</tt>
1079     * tasks submitted by the <tt>execute</tt> method.
1080     * @param handler the handler to use when execution is blocked
1081     * because the thread bounds and queue capacities are reached.
1082 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1083 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1084     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1085     * @throws NullPointerException if <tt>workQueue</tt>
1086     * or <tt>handler</tt> are null.
1087     */
1088     public ThreadPoolExecutor(int corePoolSize,
1089     int maximumPoolSize,
1090     long keepAliveTime,
1091     TimeUnit unit,
1092     BlockingQueue<Runnable> workQueue,
1093     RejectedExecutionHandler handler) {
1094     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1095     Executors.defaultThreadFactory(), handler);
1096     }
1097    
1098     /**
1099     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1100     * parameters.
1101     *
1102     * @param corePoolSize the number of threads to keep in the
1103     * pool, even if they are idle.
1104     * @param maximumPoolSize the maximum number of threads to allow in the
1105     * pool.
1106     * @param keepAliveTime when the number of threads is greater than
1107     * the core, this is the maximum time that excess idle threads
1108     * will wait for new tasks before terminating.
1109     * @param unit the time unit for the keepAliveTime
1110     * argument.
1111     * @param workQueue the queue to use for holding tasks before they
1112     * are executed. This queue will hold only the <tt>Runnable</tt>
1113     * tasks submitted by the <tt>execute</tt> method.
1114     * @param threadFactory the factory to use when the executor
1115     * creates a new thread.
1116     * @param handler the handler to use when execution is blocked
1117     * because the thread bounds and queue capacities are reached.
1118 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1119 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1120     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1121     * @throws NullPointerException if <tt>workQueue</tt>
1122     * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
1123     */
1124     public ThreadPoolExecutor(int corePoolSize,
1125     int maximumPoolSize,
1126     long keepAliveTime,
1127     TimeUnit unit,
1128     BlockingQueue<Runnable> workQueue,
1129     ThreadFactory threadFactory,
1130     RejectedExecutionHandler handler) {
1131     if (corePoolSize < 0 ||
1132     maximumPoolSize <= 0 ||
1133     maximumPoolSize < corePoolSize ||
1134     keepAliveTime < 0)
1135     throw new IllegalArgumentException();
1136     if (workQueue == null || threadFactory == null || handler == null)
1137     throw new NullPointerException();
1138     this.corePoolSize = corePoolSize;
1139     this.maximumPoolSize = maximumPoolSize;
1140     this.workQueue = workQueue;
1141     this.keepAliveTime = unit.toNanos(keepAliveTime);
1142     this.threadFactory = threadFactory;
1143     this.handler = handler;
1144     }
1145    
1146     /**
1147     * Executes the given task sometime in the future. The task
1148     * may execute in a new thread or in an existing pooled thread.
1149     *
1150     * If the task cannot be submitted for execution, either because this
1151     * executor has been shutdown or because its capacity has been reached,
1152     * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
1153     *
1154     * @param command the task to execute
1155     * @throws RejectedExecutionException at discretion of
1156     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
1157     * for execution
1158     * @throws NullPointerException if command is null
1159 dl 1.13 */
1160 dl 1.86 public void execute(Runnable command) {
1161     if (command == null)
1162     throw new NullPointerException();
1163 dl 1.107 /*
1164     * Proceed in 3 steps:
1165     *
1166     * 1. If fewer than corePoolSize threads are running, try to
1167     * start a new thread with the given command as its first
1168     * task. The call to addWorker atomically checks runState and
1169     * workerCount, and so prevents false alarms that would add
1170     * threads when it shouldn't, by returning false.
1171     *
1172     * 2. If a task can be successfully queued, then we still need
1173     * to double-check whether we should have added a thread
1174     * (because existing ones died since last checking) or that
1175     * the pool shut down since entry into this method. So we
1176     * recheck state and if necessary roll back the enqueuing if
1177     * stopped, or start a new thread if there are none.
1178     *
1179     * 3. If we cannot queue task, then we try to add a new
1180     * thread. If it fails, we know we are shut down or saturated
1181     * and so reject the task.
1182     */
1183     int c = ctl.get();
1184     if (workerCountOf(c) < corePoolSize) {
1185     if (addWorker(command, true))
1186     return;
1187     c = ctl.get();
1188     }
1189     if (runStateOf(c) == RUNNING && workQueue.offer(command)) {
1190     int recheck = ctl.get();
1191     if (runStateOf(recheck) != RUNNING && remove(command))
1192     reject(command);
1193     else if (workerCountOf(recheck) == 0)
1194     addWorker(null, false);
1195 dl 1.86 }
1196 dl 1.107 else if (!addWorker(command, false))
1197 dl 1.85 reject(command);
1198 tim 1.1 }
1199 dl 1.4
1200 dl 1.53 /**
1201     * Initiates an orderly shutdown in which previously submitted
1202     * tasks are executed, but no new tasks will be
1203     * accepted. Invocation has no additional effect if already shut
1204     * down.
1205     * @throws SecurityException if a security manager exists and
1206     * shutting down this ExecutorService may manipulate threads that
1207     * the caller is not permitted to modify because it does not hold
1208     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1209 jsr166 1.68 * or the security manager's <tt>checkAccess</tt> method denies access.
1210 dl 1.53 */
1211 dl 1.2 public void shutdown() {
1212 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1213 dl 1.2 mainLock.lock();
1214     try {
1215 dl 1.107 checkShutdownAccess();
1216     advanceRunState(SHUTDOWN);
1217     interruptIdleWorkers(false);
1218     onShutdown(); // hook for ScheduledThreadPoolExecutor
1219 tim 1.14 } finally {
1220 dl 1.2 mainLock.unlock();
1221     }
1222 dl 1.107 tryTerminate();
1223 tim 1.1 }
1224    
1225 dl 1.53 /**
1226     * Attempts to stop all actively executing tasks, halts the
1227 jsr166 1.75 * processing of waiting tasks, and returns a list of the tasks
1228 dl 1.85 * that were awaiting execution. These tasks are drained (removed)
1229     * from the task queue upon return from this method.
1230 jsr166 1.66 *
1231 jsr166 1.75 * <p>There are no guarantees beyond best-effort attempts to stop
1232     * processing actively executing tasks. This implementation
1233     * cancels tasks via {@link Thread#interrupt}, so any task that
1234     * fails to respond to interrupts may never terminate.
1235 dl 1.53 *
1236     * @return list of tasks that never commenced execution
1237     * @throws SecurityException if a security manager exists and
1238     * shutting down this ExecutorService may manipulate threads that
1239     * the caller is not permitted to modify because it does not hold
1240     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1241     * or the security manager's <tt>checkAccess</tt> method denies access.
1242     */
1243 tim 1.39 public List<Runnable> shutdownNow() {
1244 dl 1.107 List<Runnable> tasks;
1245 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1246 dl 1.2 mainLock.lock();
1247     try {
1248 dl 1.107 checkShutdownAccess();
1249     advanceRunState(STOP);
1250     interruptWorkers();
1251     tasks = drainQueue();
1252 tim 1.14 } finally {
1253 dl 1.2 mainLock.unlock();
1254     }
1255 dl 1.107 tryTerminate();
1256     return tasks;
1257 dl 1.86 }
1258    
1259 dl 1.2 public boolean isShutdown() {
1260 dl 1.107 return runStateOf(ctl.get()) != RUNNING;
1261 dl 1.16 }
1262    
1263 jsr166 1.66 /**
1264 dl 1.55 * Returns true if this executor is in the process of terminating
1265 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1266     * completely terminated. This method may be useful for
1267     * debugging. A return of <tt>true</tt> reported a sufficient
1268     * period after shutdown may indicate that submitted tasks have
1269     * ignored or suppressed interruption, causing this executor not
1270     * to properly terminate.
1271 jsr166 1.93 * @return true if terminating but not yet terminated
1272 dl 1.16 */
1273     public boolean isTerminating() {
1274 dl 1.107 int rs = runStateOf(ctl.get());
1275     return rs == SHUTDOWN || rs == STOP;
1276 tim 1.1 }
1277    
1278 dl 1.2 public boolean isTerminated() {
1279 dl 1.107 return runStateOf(ctl.get()) == TERMINATED;
1280 dl 1.2 }
1281 tim 1.1
1282 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1283     throws InterruptedException {
1284 dl 1.50 long nanos = unit.toNanos(timeout);
1285 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1286 dl 1.2 mainLock.lock();
1287     try {
1288 dl 1.25 for (;;) {
1289 dl 1.107 if (runStateOf(ctl.get()) == TERMINATED)
1290 dl 1.25 return true;
1291     if (nanos <= 0)
1292     return false;
1293     nanos = termination.awaitNanos(nanos);
1294     }
1295 tim 1.14 } finally {
1296 dl 1.2 mainLock.unlock();
1297     }
1298 dl 1.15 }
1299    
1300     /**
1301     * Invokes <tt>shutdown</tt> when this executor is no longer
1302 dl 1.107 * referenced and there are no threads.
1303 jsr166 1.66 */
1304 dl 1.107 protected void finalize() {
1305 dl 1.15 shutdown();
1306 dl 1.2 }
1307 tim 1.10
1308 dl 1.2 /**
1309     * Sets the thread factory used to create new threads.
1310     *
1311     * @param threadFactory the new thread factory
1312 dl 1.30 * @throws NullPointerException if threadFactory is null
1313 tim 1.11 * @see #getThreadFactory
1314 dl 1.2 */
1315     public void setThreadFactory(ThreadFactory threadFactory) {
1316 dl 1.30 if (threadFactory == null)
1317     throw new NullPointerException();
1318 dl 1.2 this.threadFactory = threadFactory;
1319 tim 1.1 }
1320    
1321 dl 1.2 /**
1322     * Returns the thread factory used to create new threads.
1323     *
1324     * @return the current thread factory
1325 tim 1.11 * @see #setThreadFactory
1326 dl 1.2 */
1327     public ThreadFactory getThreadFactory() {
1328     return threadFactory;
1329 tim 1.1 }
1330    
1331 dl 1.2 /**
1332     * Sets a new handler for unexecutable tasks.
1333     *
1334     * @param handler the new handler
1335 dl 1.31 * @throws NullPointerException if handler is null
1336 tim 1.11 * @see #getRejectedExecutionHandler
1337 dl 1.2 */
1338     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1339 dl 1.31 if (handler == null)
1340     throw new NullPointerException();
1341 dl 1.2 this.handler = handler;
1342     }
1343 tim 1.1
1344 dl 1.2 /**
1345     * Returns the current handler for unexecutable tasks.
1346     *
1347     * @return the current handler
1348 tim 1.11 * @see #setRejectedExecutionHandler
1349 dl 1.2 */
1350     public RejectedExecutionHandler getRejectedExecutionHandler() {
1351     return handler;
1352 tim 1.1 }
1353    
1354 dl 1.2 /**
1355     * Sets the core number of threads. This overrides any value set
1356     * in the constructor. If the new value is smaller than the
1357     * current value, excess existing threads will be terminated when
1358 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1359     * be started to execute any queued tasks.
1360 tim 1.1 *
1361 dl 1.2 * @param corePoolSize the new core size
1362 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1363 dl 1.8 * less than zero
1364 tim 1.11 * @see #getCorePoolSize
1365 tim 1.1 */
1366 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1367     if (corePoolSize < 0)
1368     throw new IllegalArgumentException();
1369 dl 1.107 int delta = corePoolSize - this.corePoolSize;
1370     this.corePoolSize = corePoolSize;
1371     if (workerCountOf(ctl.get()) > corePoolSize)
1372     interruptIdleWorkers(false);
1373     else if (delta > 0) {
1374     // We don't really know how many new threads are "needed".
1375     // As a heuristic, prestart enough new workers (up to new
1376     // core size) to handle the current number of tasks in
1377     // queue, but stop if queue becomes empty while doing so.
1378     int k = Math.min(delta, workQueue.size());
1379     while (k-- > 0 && addWorker(null, true)) {
1380     if (workQueue.isEmpty())
1381     break;
1382 tim 1.38 }
1383 dl 1.2 }
1384     }
1385 tim 1.1
1386     /**
1387 dl 1.2 * Returns the core number of threads.
1388 tim 1.1 *
1389 dl 1.2 * @return the core number of threads
1390 tim 1.11 * @see #setCorePoolSize
1391 tim 1.1 */
1392 tim 1.10 public int getCorePoolSize() {
1393 dl 1.2 return corePoolSize;
1394 dl 1.16 }
1395    
1396     /**
1397 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1398 dl 1.16 * overrides the default policy of starting core threads only when
1399     * new tasks are executed. This method will return <tt>false</tt>
1400     * if all core threads have already been started.
1401     * @return true if a thread was started
1402 jsr166 1.66 */
1403 dl 1.16 public boolean prestartCoreThread() {
1404 dl 1.107 return workerCountOf(ctl.get()) < corePoolSize &&
1405     addWorker(null, true);
1406 dl 1.16 }
1407    
1408     /**
1409 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1410 dl 1.16 * overrides the default policy of starting core threads only when
1411 jsr166 1.66 * new tasks are executed.
1412 jsr166 1.88 * @return the number of threads started
1413 jsr166 1.66 */
1414 dl 1.16 public int prestartAllCoreThreads() {
1415     int n = 0;
1416 dl 1.107 while (addWorker(null, true))
1417 dl 1.16 ++n;
1418     return n;
1419 dl 1.2 }
1420 tim 1.1
1421     /**
1422 dl 1.62 * Returns true if this pool allows core threads to time out and
1423     * terminate if no tasks arrive within the keepAlive time, being
1424     * replaced if needed when new tasks arrive. When true, the same
1425     * keep-alive policy applying to non-core threads applies also to
1426     * core threads. When false (the default), core threads are never
1427     * terminated due to lack of incoming tasks.
1428     * @return <tt>true</tt> if core threads are allowed to time out,
1429     * else <tt>false</tt>
1430 jsr166 1.72 *
1431     * @since 1.6
1432 dl 1.62 */
1433     public boolean allowsCoreThreadTimeOut() {
1434     return allowCoreThreadTimeOut;
1435     }
1436    
1437     /**
1438     * Sets the policy governing whether core threads may time out and
1439     * terminate if no tasks arrive within the keep-alive time, being
1440     * replaced if needed when new tasks arrive. When false, core
1441     * threads are never terminated due to lack of incoming
1442     * tasks. When true, the same keep-alive policy applying to
1443     * non-core threads applies also to core threads. To avoid
1444     * continual thread replacement, the keep-alive time must be
1445 dl 1.64 * greater than zero when setting <tt>true</tt>. This method
1446     * should in general be called before the pool is actively used.
1447 dl 1.62 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1448 dl 1.64 * @throws IllegalArgumentException if value is <tt>true</tt>
1449     * and the current keep-alive time is not greater than zero.
1450 jsr166 1.72 *
1451     * @since 1.6
1452 dl 1.62 */
1453     public void allowCoreThreadTimeOut(boolean value) {
1454 dl 1.64 if (value && keepAliveTime <= 0)
1455     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1456 dl 1.107 if (value != allowCoreThreadTimeOut) {
1457     allowCoreThreadTimeOut = value;
1458     if (value)
1459     interruptIdleWorkers(false);
1460     }
1461 dl 1.62 }
1462    
1463     /**
1464 tim 1.1 * Sets the maximum allowed number of threads. This overrides any
1465 dl 1.2 * value set in the constructor. If the new value is smaller than
1466     * the current value, excess existing threads will be
1467     * terminated when they next become idle.
1468 tim 1.1 *
1469 dl 1.2 * @param maximumPoolSize the new maximum
1470 jsr166 1.84 * @throws IllegalArgumentException if the new maximum is
1471     * less than or equal to zero, or
1472     * less than the {@linkplain #getCorePoolSize core pool size}
1473 tim 1.11 * @see #getMaximumPoolSize
1474 dl 1.2 */
1475     public void setMaximumPoolSize(int maximumPoolSize) {
1476     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1477     throw new IllegalArgumentException();
1478 dl 1.107 this.maximumPoolSize = maximumPoolSize;
1479     if (workerCountOf(ctl.get()) > maximumPoolSize)
1480     interruptIdleWorkers(false);
1481 dl 1.2 }
1482 tim 1.1
1483     /**
1484     * Returns the maximum allowed number of threads.
1485     *
1486 dl 1.2 * @return the maximum allowed number of threads
1487 tim 1.11 * @see #setMaximumPoolSize
1488 tim 1.1 */
1489 tim 1.10 public int getMaximumPoolSize() {
1490 dl 1.2 return maximumPoolSize;
1491     }
1492 tim 1.1
1493     /**
1494     * Sets the time limit for which threads may remain idle before
1495 dl 1.2 * being terminated. If there are more than the core number of
1496 tim 1.1 * threads currently in the pool, after waiting this amount of
1497     * time without processing a task, excess threads will be
1498     * terminated. This overrides any value set in the constructor.
1499     * @param time the time to wait. A time value of zero will cause
1500     * excess threads to terminate immediately after executing tasks.
1501 jsr166 1.96 * @param unit the time unit of the time argument
1502 dl 1.64 * @throws IllegalArgumentException if time less than zero or
1503     * if time is zero and allowsCoreThreadTimeOut
1504 tim 1.11 * @see #getKeepAliveTime
1505 tim 1.1 */
1506 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1507     if (time < 0)
1508     throw new IllegalArgumentException();
1509 dl 1.64 if (time == 0 && allowsCoreThreadTimeOut())
1510     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1511 dl 1.107 long keepAliveTime = unit.toNanos(time);
1512     long delta = keepAliveTime - this.keepAliveTime;
1513     this.keepAliveTime = keepAliveTime;
1514     if (delta < 0)
1515     interruptIdleWorkers(false);
1516 dl 1.2 }
1517 tim 1.1
1518     /**
1519     * Returns the thread keep-alive time, which is the amount of time
1520 jsr166 1.93 * that threads in excess of the core pool size may remain
1521 tim 1.10 * idle before being terminated.
1522 tim 1.1 *
1523 dl 1.2 * @param unit the desired time unit of the result
1524 tim 1.1 * @return the time limit
1525 tim 1.11 * @see #setKeepAliveTime
1526 tim 1.1 */
1527 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1528 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1529     }
1530 tim 1.1
1531 dl 1.86 /* User-level queue utilities */
1532    
1533     /**
1534     * Returns the task queue used by this executor. Access to the
1535     * task queue is intended primarily for debugging and monitoring.
1536     * This queue may be in active use. Retrieving the task queue
1537     * does not prevent queued tasks from executing.
1538     *
1539     * @return the task queue
1540     */
1541     public BlockingQueue<Runnable> getQueue() {
1542     return workQueue;
1543     }
1544    
1545     /**
1546     * Removes this task from the executor's internal queue if it is
1547     * present, thus causing it not to be run if it has not already
1548     * started.
1549     *
1550     * <p> This method may be useful as one part of a cancellation
1551     * scheme. It may fail to remove tasks that have been converted
1552     * into other forms before being placed on the internal queue. For
1553     * example, a task entered using <tt>submit</tt> might be
1554     * converted into a form that maintains <tt>Future</tt> status.
1555     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1556     * may be used to remove those Futures that have been cancelled.
1557     *
1558     * @param task the task to remove
1559     * @return true if the task was removed
1560     */
1561     public boolean remove(Runnable task) {
1562 dl 1.107 boolean removed = workQueue.remove(task);
1563     tryTerminate(); // In case SHUTDOWN and now empty
1564     return removed;
1565 dl 1.86 }
1566    
1567     /**
1568     * Tries to remove from the work queue all {@link Future}
1569     * tasks that have been cancelled. This method can be useful as a
1570     * storage reclamation operation, that has no other impact on
1571     * functionality. Cancelled tasks are never executed, but may
1572     * accumulate in work queues until worker threads can actively
1573     * remove them. Invoking this method instead tries to remove them now.
1574     * However, this method may fail to remove tasks in
1575     * the presence of interference by other threads.
1576     */
1577     public void purge() {
1578 jsr166 1.111 final BlockingQueue<Runnable> q = workQueue;
1579 dl 1.86 try {
1580 dl 1.107 Iterator<Runnable> it = q.iterator();
1581 dl 1.86 while (it.hasNext()) {
1582     Runnable r = it.next();
1583 jsr166 1.111 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1584     it.remove();
1585 dl 1.107 }
1586 jsr166 1.111 } catch (ConcurrentModificationException fallThrough) {
1587     // Take slow path if we encounter interference during traversal.
1588     // Make copy for traversal and call remove for cancelled entries.
1589     // The slow path is more likely to be O(N*N).
1590     for (Object r : q.toArray())
1591     if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1592     q.remove(r);
1593 dl 1.86 }
1594 dl 1.107
1595     tryTerminate(); // In case SHUTDOWN and now empty
1596 dl 1.86 }
1597    
1598 tim 1.1 /* Statistics */
1599    
1600     /**
1601     * Returns the current number of threads in the pool.
1602     *
1603     * @return the number of threads
1604     */
1605 tim 1.10 public int getPoolSize() {
1606 dl 1.107 final ReentrantLock mainLock = this.mainLock;
1607     mainLock.lock();
1608     try {
1609     return workers.size();
1610     } finally {
1611     mainLock.unlock();
1612     }
1613 dl 1.2 }
1614 tim 1.1
1615     /**
1616 dl 1.2 * Returns the approximate number of threads that are actively
1617 tim 1.1 * executing tasks.
1618     *
1619     * @return the number of threads
1620     */
1621 tim 1.10 public int getActiveCount() {
1622 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1623 dl 1.2 mainLock.lock();
1624     try {
1625     int n = 0;
1626 tim 1.39 for (Worker w : workers) {
1627 dl 1.107 if (w.isLocked())
1628 dl 1.2 ++n;
1629     }
1630     return n;
1631 tim 1.14 } finally {
1632 dl 1.2 mainLock.unlock();
1633     }
1634     }
1635 tim 1.1
1636     /**
1637 dl 1.2 * Returns the largest number of threads that have ever
1638     * simultaneously been in the pool.
1639 tim 1.1 *
1640     * @return the number of threads
1641     */
1642 tim 1.10 public int getLargestPoolSize() {
1643 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1644 dl 1.2 mainLock.lock();
1645     try {
1646     return largestPoolSize;
1647 tim 1.14 } finally {
1648 dl 1.2 mainLock.unlock();
1649     }
1650     }
1651 tim 1.1
1652     /**
1653 dl 1.85 * Returns the approximate total number of tasks that have ever been
1654 dl 1.2 * scheduled for execution. Because the states of tasks and
1655     * threads may change dynamically during computation, the returned
1656 dl 1.97 * value is only an approximation.
1657 tim 1.1 *
1658     * @return the number of tasks
1659     */
1660 tim 1.10 public long getTaskCount() {
1661 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1662 dl 1.2 mainLock.lock();
1663     try {
1664     long n = completedTaskCount;
1665 tim 1.39 for (Worker w : workers) {
1666 dl 1.2 n += w.completedTasks;
1667 dl 1.107 if (w.isLocked())
1668 dl 1.2 ++n;
1669     }
1670     return n + workQueue.size();
1671 tim 1.14 } finally {
1672 dl 1.2 mainLock.unlock();
1673     }
1674     }
1675 tim 1.1
1676     /**
1677 dl 1.2 * Returns the approximate total number of tasks that have
1678     * completed execution. Because the states of tasks and threads
1679     * may change dynamically during computation, the returned value
1680 dl 1.17 * is only an approximation, but one that does not ever decrease
1681     * across successive calls.
1682 tim 1.1 *
1683     * @return the number of tasks
1684     */
1685 tim 1.10 public long getCompletedTaskCount() {
1686 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1687 dl 1.2 mainLock.lock();
1688     try {
1689     long n = completedTaskCount;
1690 tim 1.39 for (Worker w : workers)
1691     n += w.completedTasks;
1692 dl 1.2 return n;
1693 tim 1.14 } finally {
1694 dl 1.2 mainLock.unlock();
1695     }
1696     }
1697 tim 1.1
1698 dl 1.86 /* Extension hooks */
1699    
1700 tim 1.1 /**
1701 dl 1.17 * Method invoked prior to executing the given Runnable in the
1702 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1703     * will execute task <tt>r</tt>, and may be used to re-initialize
1704 jsr166 1.73 * ThreadLocals, or to perform logging.
1705     *
1706     * <p>This implementation does nothing, but may be customized in
1707     * subclasses. Note: To properly nest multiple overridings, subclasses
1708     * should generally invoke <tt>super.beforeExecute</tt> at the end of
1709     * this method.
1710 tim 1.1 *
1711 dl 1.2 * @param t the thread that will run task r.
1712     * @param r the task that will be executed.
1713 tim 1.1 */
1714 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1715 tim 1.1
1716     /**
1717 jsr166 1.70 * Method invoked upon completion of execution of the given Runnable.
1718     * This method is invoked by the thread that executed the task. If
1719     * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1720     * or <tt>Error</tt> that caused execution to terminate abruptly.
1721 dl 1.69 *
1722 dl 1.107 * <p>This implementation does nothing, but may be customized in
1723     * subclasses. Note: To properly nest multiple overridings, subclasses
1724     * should generally invoke <tt>super.afterExecute</tt> at the
1725     * beginning of this method.
1726     *
1727 dl 1.69 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1728     * {@link FutureTask}) either explicitly or via methods such as
1729     * <tt>submit</tt>, these task objects catch and maintain
1730     * computational exceptions, and so they do not cause abrupt
1731 jsr166 1.70 * termination, and the internal exceptions are <em>not</em>
1732 dl 1.107 * passed to this method. If you would like to trap both kinds of
1733     * failures in this method, you can further probe for such cases,
1734     * as in this sample subclass that prints either the direct cause
1735     * or the underlying exception if a task has been aborted:
1736     *
1737     * <pre>
1738     * class ExtendedExecutor extends ThreadPoolExecutor {
1739     * // ...
1740     * protected void afterExecute(Runnable r, Throwable t) {
1741     * super.afterExecute(r, t);
1742     * if (t == null && r instanceOf Future&lt;?&gt;) {
1743     * try {
1744     * Object result = ((Future&lt;?&gt;) r).get();
1745     * } catch (CancellationException ce) {
1746     * t = ce;
1747     * } catch (ExecutionException ee) {
1748     * t = ee.getCause();
1749     * } catch (InterruptedException ie) {
1750     * Thread.currentThread().interrupt(); // ignore/reset
1751     * }
1752     * }
1753     * if (t != null)
1754     * System.out.println(t);
1755     * }
1756     * }
1757     * </pre>
1758 tim 1.1 *
1759 dl 1.2 * @param r the runnable that has completed.
1760 dl 1.24 * @param t the exception that caused termination, or null if
1761 dl 1.2 * execution completed normally.
1762 tim 1.1 */
1763 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1764 tim 1.1
1765 dl 1.2 /**
1766     * Method invoked when the Executor has terminated. Default
1767 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1768     * overridings, subclasses should generally invoke
1769     * <tt>super.terminated</tt> within this method.
1770 dl 1.2 */
1771     protected void terminated() { }
1772 tim 1.1
1773 dl 1.86 /* Predefined RejectedExecutionHandlers */
1774    
1775 tim 1.1 /**
1776 dl 1.21 * A handler for rejected tasks that runs the rejected task
1777     * directly in the calling thread of the <tt>execute</tt> method,
1778     * unless the executor has been shut down, in which case the task
1779     * is discarded.
1780 tim 1.1 */
1781 jsr166 1.71 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1782 tim 1.1 /**
1783 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1784 tim 1.1 */
1785     public CallerRunsPolicy() { }
1786    
1787 dl 1.24 /**
1788     * Executes task r in the caller's thread, unless the executor
1789     * has been shut down, in which case the task is discarded.
1790     * @param r the runnable task requested to be executed
1791     * @param e the executor attempting to execute this task
1792     */
1793 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1794     if (!e.isShutdown()) {
1795 tim 1.1 r.run();
1796     }
1797     }
1798     }
1799    
1800     /**
1801 dl 1.21 * A handler for rejected tasks that throws a
1802 dl 1.8 * <tt>RejectedExecutionException</tt>.
1803 tim 1.1 */
1804 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1805 tim 1.1 /**
1806 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1807 tim 1.1 */
1808     public AbortPolicy() { }
1809    
1810 dl 1.24 /**
1811 dl 1.54 * Always throws RejectedExecutionException.
1812 dl 1.24 * @param r the runnable task requested to be executed
1813     * @param e the executor attempting to execute this task
1814     * @throws RejectedExecutionException always.
1815     */
1816 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1817     throw new RejectedExecutionException();
1818 tim 1.1 }
1819     }
1820    
1821     /**
1822 dl 1.21 * A handler for rejected tasks that silently discards the
1823     * rejected task.
1824 tim 1.1 */
1825 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1826 tim 1.1 /**
1827 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1828 tim 1.1 */
1829     public DiscardPolicy() { }
1830    
1831 dl 1.24 /**
1832     * Does nothing, which has the effect of discarding task r.
1833     * @param r the runnable task requested to be executed
1834     * @param e the executor attempting to execute this task
1835     */
1836 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1837 tim 1.1 }
1838     }
1839    
1840     /**
1841 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1842     * request and then retries <tt>execute</tt>, unless the executor
1843     * is shut down, in which case the task is discarded.
1844 tim 1.1 */
1845 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1846 tim 1.1 /**
1847 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1848 tim 1.1 */
1849     public DiscardOldestPolicy() { }
1850    
1851 dl 1.24 /**
1852     * Obtains and ignores the next task that the executor
1853     * would otherwise execute, if one is immediately available,
1854     * and then retries execution of task r, unless the executor
1855     * is shut down, in which case task r is instead discarded.
1856     * @param r the runnable task requested to be executed
1857     * @param e the executor attempting to execute this task
1858     */
1859 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1860     if (!e.isShutdown()) {
1861     e.getQueue().poll();
1862     e.execute(r);
1863 tim 1.1 }
1864     }
1865     }
1866     }