ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.114
Committed: Tue Oct 3 00:21:08 2006 UTC (17 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.113: +11 -3 lines
Log Message:
More conservative recheck on STOP

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 jsr166 1.113 interruptIdleWorkers(ONLY_ONE);
567 dl 1.107 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 jsr166 1.113 * signals in case all threads are currently waiting.
655 dl 1.107 * Interrupting any arbitrary thread ensures that newly arriving
656     * workers since shutdown began will also eventually exit.
657 jsr166 1.113 * To guarantee eventual termination, it suffices to always
658     * interrupt only one idle worker, but shutdown() interrupts all
659     * idle workers so that redundant workers exit promptly, not
660     * waiting for a straggler task to finish.
661 tim 1.10 */
662 dl 1.107 private void interruptIdleWorkers(boolean onlyOne) {
663     final ReentrantLock mainLock = this.mainLock;
664     mainLock.lock();
665     try {
666     Iterator<Worker> it = workers.iterator();
667     while (it.hasNext()) {
668     Worker w = it.next();
669     Thread t = w.thread;
670     if (!t.isInterrupted() && w.tryLock()) {
671     try {
672     t.interrupt();
673     } catch (SecurityException ignore) {
674     } finally {
675     w.unlock();
676     }
677     }
678     if (onlyOne)
679     break;
680     }
681     } finally {
682     mainLock.unlock();
683     }
684     }
685    
686 jsr166 1.113 private void interruptIdleWorkers() { interruptIdleWorkers(false); }
687     private static final boolean ONLY_ONE = true;
688    
689 dl 1.107 /**
690     * Ensures that unless the pool is stopping, the current thread
691     * does not have its interrupt set. This requires a double-check
692     * of state in case the interrupt was cleared concurrently with a
693     * shutdownNow -- if so, the interrupt is re-enabled.
694     */
695     private void clearInterruptsForTaskRun() {
696     if (runStateOf(ctl.get()) < STOP &&
697     Thread.interrupted() &&
698     runStateOf(ctl.get()) >= STOP)
699     Thread.currentThread().interrupt();
700     }
701    
702     /*
703     * Misc utilities, most of which are also exported to
704     * ScheduledThreadPoolExecutor
705     */
706    
707     /**
708     * Invokes the rejected execution handler for the given command.
709     * Package-protected for use by ScheduledThreadPoolExecutor.
710     */
711     final void reject(Runnable command) {
712     handler.rejectedExecution(command, this);
713     }
714 dl 1.2
715     /**
716 dl 1.107 * Performs any further cleanup following run state transition on
717     * invocation of shutdown. A no-op here, but used by
718     * ScheduledThreadPoolExecutor to cancel delayed tasks.
719 tim 1.10 */
720 dl 1.107 void onShutdown() {
721     }
722 dl 1.2
723     /**
724 dl 1.107 * State check needed by ScheduledThreadPoolExecutor to
725     * enable running tasks during shutdown;
726     * @param shutdownOK true if should return true if SHUTDOWN
727 tim 1.10 */
728 dl 1.107 final boolean isRunningOrShutdown(boolean shutdownOK) {
729     int rs = runStateOf(ctl.get());
730     return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
731     }
732 dl 1.2
733     /**
734 dl 1.107 * Drains the task queue into a new list, normally using
735     * drainTo. But if the queue is a DelayQueue or any other kind of
736     * queue for which poll or drainTo may fail to remove some
737     * elements, it deletes them one by one.
738     */
739     private List<Runnable> drainQueue() {
740     BlockingQueue<Runnable> q = workQueue;
741     List<Runnable> taskList = new ArrayList<Runnable>();
742     q.drainTo(taskList);
743     if (!q.isEmpty()) {
744     for (Runnable r : q.toArray(new Runnable[0])) {
745     if (q.remove(r))
746     taskList.add(r);
747     }
748     }
749     return taskList;
750     }
751    
752     /*
753     * Methods for creating, running and cleaning up after workers
754 tim 1.10 */
755 dl 1.2
756     /**
757 dl 1.107 * Checks if a new worker can be added with respect to current
758     * pool state and the given bound (either core or maximum). If so
759     * the worker count is adjusted accordingly, and, if possible, a
760     * new worker is created and started running firstTask as its
761     * first task, This method returns false if the pool is stopped or
762     * eligible to shut down. It also returns false if the thread
763     * factory fails to create a thread when asked, which requires a
764     * backout of workerCount, and a recheck for termination, in case
765     * the existence of this worker was holding up termination.
766     *
767     * @param firstTask the task the new thread should run first (or
768     * null if none). Workers are created with an initial first task
769     * (in method execute()) to bypass queuing when there are fewer
770     * than corePoolSize threads (in which case we always start one),
771 jsr166 1.110 * or when the queue is full (in which case we must bypass queue).
772 dl 1.107 * Initially idle threads are usually created via
773     * prestartCoreThread or to replace other dying workers.
774     *
775     * @param core if true use corePoolSize as bound, else
776 jsr166 1.110 * maximumPoolSize. (A boolean indicator is used here rather than a
777 dl 1.107 * value to ensure reads of fresh values after checking other pool
778     * state).
779     * @return true if successful
780 tim 1.10 */
781 dl 1.107 private boolean addWorker(Runnable firstTask, boolean core) {
782     for (;;) {
783     int c = ctl.get();
784     int rs = runStateOf(c);
785 jsr166 1.113 // Check if queue empty only if necessary.
786 dl 1.107 if (rs == SHUTDOWN) {
787     if (workQueue.isEmpty())
788     return false;
789 jsr166 1.113 // isEmpty() may be slow, so re-read ctl to reduce the risk
790     // of CAS failing due to harmless change to workerCount.
791     c = ctl.get();
792 dl 1.107 }
793     int wc = workerCountOf(c);
794     if (rs > SHUTDOWN ||
795     wc >= CAPACITY ||
796 jsr166 1.110 wc >= (core ? corePoolSize : maximumPoolSize))
797 dl 1.107 return false;
798     if (ctl.compareAndSet(c, ctlOf(rs, wc+1)))
799     break;
800     }
801    
802     Worker w = new Worker(firstTask);
803     Thread t = w.thread;
804 jsr166 1.109 if (t == null) { // Back out on ThreadFactory failure
805 dl 1.107 decrementWorkerCount();
806     tryTerminate();
807     return false;
808     }
809    
810     final ReentrantLock mainLock = this.mainLock;
811     mainLock.lock();
812     try {
813     workers.add(w);
814     int s = workers.size();
815     if (s > largestPoolSize)
816     largestPoolSize = s;
817     } finally {
818     mainLock.unlock();
819     }
820    
821     t.start();
822     return true;
823     }
824 dl 1.2
825     /**
826 dl 1.107 * Performs cleanup and bookkeeping for a dying worker. Called
827     * only from worker threads. Unless completedAbruptly is set,
828     * assumes that workerCount has already been adjusted to account
829     * for exit. This method removes thread from worker set, and
830     * possibly terminates the pool or replaces the worker if either
831     * it exited due to user task exception or if fewer than
832     * corePoolSize workers are running or queue is non-empty but
833     * there are no workers.
834     *
835     * @param w the worker
836     * @param completedAbruptly if the worker died due to user exception
837 tim 1.10 */
838 dl 1.107 private void processWorkerExit(Worker w, boolean completedAbruptly) {
839     if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
840     decrementWorkerCount();
841    
842     final ReentrantLock mainLock = this.mainLock;
843     mainLock.lock();
844     try {
845     completedTaskCount += w.completedTasks;
846     workers.remove(w);
847     } finally {
848     mainLock.unlock();
849     }
850    
851     tryTerminate();
852    
853     if (!completedAbruptly) {
854 jsr166 1.110 int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
855 dl 1.107 if (min == 0 && !workQueue.isEmpty())
856     min = 1;
857     int c = ctl.get();
858     if (workerCountOf(c) >= min || runStateOf(c) >= STOP)
859     return; // replacement not needed
860     }
861     addWorker(null, false);
862     }
863 dl 1.2
864     /**
865 dl 1.107 * Performs blocking or timed wait for a task, depending on
866     * current configuration settings, or returns null if this worker
867     * must exit because of any of:
868     * 1. There are more than maximumPoolSize workers (due to
869     * a call to setMaximumPoolSize).
870 jsr166 1.110 * 2. The pool is stopped.
871 dl 1.107 * 3. The queue is empty, and either the pool is shutdown,
872     * or the thread has already timed out at least once
873     * waiting for a task, and would otherwise enter another
874     * timed wait.
875     *
876     * @return task, or null if the worker must exit, in which case
877     * workerCount is decremented
878 tim 1.10 */
879 dl 1.107 private Runnable getTask() {
880     /*
881     * Variable "empty" tracks whether the queue appears to be
882     * empty in case we need to know to check exit. This is set
883     * true on time-out from timed poll as an indicator of likely
884     * emptiness, in which case it is rechecked explicitly via
885     * isEmpty when deciding whether to exit. Emptiness must also
886     * be checked in state SHUTDOWN. The variable is initialized
887     * false to indicate lack of prior timeout, and left false
888     * until otherwise required to check.
889     */
890     boolean empty = false;
891     for (;;) {
892     int c = ctl.get();
893     int rs = runStateOf(c);
894     if (rs == SHUTDOWN || empty) {
895     empty = workQueue.isEmpty();
896     if (runStateOf(c = ctl.get()) != rs)
897     continue; // retry if state changed
898     }
899    
900     int wc = workerCountOf(c);
901     boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
902    
903     // Try to exit if too many threads, shutting down, and/or timed out
904     if (wc > maximumPoolSize || rs > SHUTDOWN ||
905     (empty && (timed || rs == SHUTDOWN))) {
906     if (ctl.compareAndSet(c, ctlOf(rs, wc-1)))
907     return null;
908     else
909     continue; // retry on CAS failure
910     }
911    
912     try {
913 jsr166 1.110 Runnable r = timed ?
914 dl 1.107 workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
915     workQueue.take();
916     if (r != null)
917     return r;
918     empty = true; // queue probably empty; recheck above
919 jsr166 1.108 } catch (InterruptedException retry) {
920 dl 1.107 }
921     }
922     }
923 jsr166 1.66
924 dl 1.8 /**
925 dl 1.107 * Main worker run loop. Repeatedly gets tasks from queue and
926     * executes them, while coping with a number of issues:
927     *
928     * 1. We may start out with an initial task, in which case we
929     * don't need to get the first one. Otherwise, as long as pool is
930     * running, we get tasks from getTask. If it returns null then the
931     * worker exits due to changed pool state or configuration
932     * parameters. Other exits result from exception throws in
933     * external code, in which case completedAbruptly holds, which
934     * usually leads processWorkerExit to replace this thread.
935     *
936     * 2. Before running any task, the lock is acquired to prevent
937 jsr166 1.108 * other pool interrupts while the task is executing, and
938 dl 1.107 * clearInterruptsForTaskRun called to ensure that unless pool is
939     * stopping, this thread does not have its interrupt set.
940     *
941     * 3. Each task run is preceded by a call to beforeExecute, which
942     * might throw an exception, in which case we cause thread to die
943     * (breaking loop with completedAbruptly true) without processing
944     * the task.
945     *
946     * 4. Assuming beforeExecute completes normally, we run the task,
947     * gathering any of its thrown exceptions to send to
948     * afterExecute. We separately handle RuntimeException, Error
949     * (both of which the specs guarantee that we trap) and arbitrary
950     * Throwables. Because we cannot rethrow Throwables within
951     * Runnable.run, we wrap them within Errors on the way out (to the
952     * thread's UncaughtExceptionHandler). Any thrown exception also
953     * conservatively causes thread to die.
954     *
955     * 5. After task.run completes, we call afterExecute, which may
956     * also throw an exception, which will also cause thread to
957     * die. According to JLS Sec 14.20, this exception is the one that
958     * will be in effect even if task.run throws.
959     *
960     * The net effect of the exception mechanics is that afterExecute
961     * and the thread's UncaughtExceptionHandler have as accurate
962     * information as we can provide about any problems encountered by
963     * user code.
964     *
965     * @param w the worker
966 dl 1.8 */
967 dl 1.107 final void runWorker(Worker w) {
968     Runnable task = w.firstTask;
969     w.firstTask = null;
970     boolean completedAbruptly = true;
971     try {
972     while (task != null || (task = getTask()) != null) {
973     w.lock();
974     clearInterruptsForTaskRun();
975     try {
976     beforeExecute(w.thread, task);
977     Throwable thrown = null;
978     try {
979     task.run();
980     } catch (RuntimeException x) {
981     thrown = x; throw x;
982     } catch (Error x) {
983     thrown = x; throw x;
984     } catch (Throwable x) {
985     thrown = x; throw new Error(x);
986     } finally {
987     afterExecute(task, thrown);
988     }
989     } finally {
990     task = null;
991     w.completedTasks++;
992     w.unlock();
993     }
994     }
995     completedAbruptly = false;
996     } finally {
997     processWorkerExit(w, completedAbruptly);
998     }
999     }
1000 dl 1.2
1001 dl 1.107 // Public constructors and methods
1002 dl 1.86
1003 dl 1.2 /**
1004 dl 1.86 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1005     * parameters and default thread factory and rejected execution handler.
1006     * It may be more convenient to use one of the {@link Executors} factory
1007     * methods instead of this general purpose constructor.
1008     *
1009     * @param corePoolSize the number of threads to keep in the
1010     * pool, even if they are idle.
1011     * @param maximumPoolSize the maximum number of threads to allow in the
1012     * pool.
1013     * @param keepAliveTime when the number of threads is greater than
1014     * the core, this is the maximum time that excess idle threads
1015     * will wait for new tasks before terminating.
1016     * @param unit the time unit for the keepAliveTime
1017     * argument.
1018     * @param workQueue the queue to use for holding tasks before they
1019     * are executed. This queue will hold only the <tt>Runnable</tt>
1020     * tasks submitted by the <tt>execute</tt> method.
1021 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1022 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1023     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1024     * @throws NullPointerException if <tt>workQueue</tt> is null
1025     */
1026     public ThreadPoolExecutor(int corePoolSize,
1027     int maximumPoolSize,
1028     long keepAliveTime,
1029     TimeUnit unit,
1030     BlockingQueue<Runnable> workQueue) {
1031     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1032     Executors.defaultThreadFactory(), defaultHandler);
1033     }
1034    
1035     /**
1036     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1037     * parameters and default rejected execution handler.
1038     *
1039     * @param corePoolSize the number of threads to keep in the
1040     * pool, even if they are idle.
1041     * @param maximumPoolSize the maximum number of threads to allow in the
1042     * pool.
1043     * @param keepAliveTime when the number of threads is greater than
1044     * the core, this is the maximum time that excess idle threads
1045     * will wait for new tasks before terminating.
1046     * @param unit the time unit for the keepAliveTime
1047     * argument.
1048     * @param workQueue the queue to use for holding tasks before they
1049     * are executed. This queue will hold only the <tt>Runnable</tt>
1050     * tasks submitted by the <tt>execute</tt> method.
1051     * @param threadFactory the factory to use when the executor
1052     * creates a new thread.
1053 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1054 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1055     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1056     * @throws NullPointerException if <tt>workQueue</tt>
1057     * or <tt>threadFactory</tt> are null.
1058     */
1059     public ThreadPoolExecutor(int corePoolSize,
1060     int maximumPoolSize,
1061     long keepAliveTime,
1062     TimeUnit unit,
1063     BlockingQueue<Runnable> workQueue,
1064     ThreadFactory threadFactory) {
1065     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1066     threadFactory, defaultHandler);
1067     }
1068    
1069     /**
1070     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1071     * parameters and default thread factory.
1072     *
1073     * @param corePoolSize the number of threads to keep in the
1074     * pool, even if they are idle.
1075     * @param maximumPoolSize the maximum number of threads to allow in the
1076     * pool.
1077     * @param keepAliveTime when the number of threads is greater than
1078     * the core, this is the maximum time that excess idle threads
1079     * will wait for new tasks before terminating.
1080     * @param unit the time unit for the keepAliveTime
1081     * argument.
1082     * @param workQueue the queue to use for holding tasks before they
1083     * are executed. This queue will hold only the <tt>Runnable</tt>
1084     * tasks submitted by the <tt>execute</tt> method.
1085     * @param handler the handler to use when execution is blocked
1086     * because the thread bounds and queue capacities are reached.
1087 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1088 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1089     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1090     * @throws NullPointerException if <tt>workQueue</tt>
1091     * or <tt>handler</tt> are null.
1092     */
1093     public ThreadPoolExecutor(int corePoolSize,
1094     int maximumPoolSize,
1095     long keepAliveTime,
1096     TimeUnit unit,
1097     BlockingQueue<Runnable> workQueue,
1098     RejectedExecutionHandler handler) {
1099     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
1100     Executors.defaultThreadFactory(), handler);
1101     }
1102    
1103     /**
1104     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
1105     * parameters.
1106     *
1107     * @param corePoolSize the number of threads to keep in the
1108     * pool, even if they are idle.
1109     * @param maximumPoolSize the maximum number of threads to allow in the
1110     * pool.
1111     * @param keepAliveTime when the number of threads is greater than
1112     * the core, this is the maximum time that excess idle threads
1113     * will wait for new tasks before terminating.
1114     * @param unit the time unit for the keepAliveTime
1115     * argument.
1116     * @param workQueue the queue to use for holding tasks before they
1117     * are executed. This queue will hold only the <tt>Runnable</tt>
1118     * tasks submitted by the <tt>execute</tt> method.
1119     * @param threadFactory the factory to use when the executor
1120     * creates a new thread.
1121     * @param handler the handler to use when execution is blocked
1122     * because the thread bounds and queue capacities are reached.
1123 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
1124 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
1125     * equal to zero, or if corePoolSize greater than maximumPoolSize.
1126     * @throws NullPointerException if <tt>workQueue</tt>
1127     * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
1128     */
1129     public ThreadPoolExecutor(int corePoolSize,
1130     int maximumPoolSize,
1131     long keepAliveTime,
1132     TimeUnit unit,
1133     BlockingQueue<Runnable> workQueue,
1134     ThreadFactory threadFactory,
1135     RejectedExecutionHandler handler) {
1136     if (corePoolSize < 0 ||
1137     maximumPoolSize <= 0 ||
1138     maximumPoolSize < corePoolSize ||
1139     keepAliveTime < 0)
1140     throw new IllegalArgumentException();
1141     if (workQueue == null || threadFactory == null || handler == null)
1142     throw new NullPointerException();
1143     this.corePoolSize = corePoolSize;
1144     this.maximumPoolSize = maximumPoolSize;
1145     this.workQueue = workQueue;
1146     this.keepAliveTime = unit.toNanos(keepAliveTime);
1147     this.threadFactory = threadFactory;
1148     this.handler = handler;
1149     }
1150    
1151     /**
1152     * Executes the given task sometime in the future. The task
1153     * may execute in a new thread or in an existing pooled thread.
1154     *
1155     * If the task cannot be submitted for execution, either because this
1156     * executor has been shutdown or because its capacity has been reached,
1157     * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
1158     *
1159     * @param command the task to execute
1160     * @throws RejectedExecutionException at discretion of
1161     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
1162     * for execution
1163     * @throws NullPointerException if command is null
1164 dl 1.13 */
1165 dl 1.86 public void execute(Runnable command) {
1166     if (command == null)
1167     throw new NullPointerException();
1168 dl 1.107 /*
1169     * Proceed in 3 steps:
1170     *
1171     * 1. If fewer than corePoolSize threads are running, try to
1172     * start a new thread with the given command as its first
1173     * task. The call to addWorker atomically checks runState and
1174     * workerCount, and so prevents false alarms that would add
1175     * threads when it shouldn't, by returning false.
1176     *
1177     * 2. If a task can be successfully queued, then we still need
1178     * to double-check whether we should have added a thread
1179     * (because existing ones died since last checking) or that
1180     * the pool shut down since entry into this method. So we
1181     * recheck state and if necessary roll back the enqueuing if
1182     * stopped, or start a new thread if there are none.
1183     *
1184     * 3. If we cannot queue task, then we try to add a new
1185     * thread. If it fails, we know we are shut down or saturated
1186     * and so reject the task.
1187     */
1188     int c = ctl.get();
1189     if (workerCountOf(c) < corePoolSize) {
1190     if (addWorker(command, true))
1191     return;
1192     c = ctl.get();
1193     }
1194     if (runStateOf(c) == RUNNING && workQueue.offer(command)) {
1195     int recheck = ctl.get();
1196 dl 1.114 if (runStateOf(recheck) >= STOP && remove(command))
1197 dl 1.107 reject(command);
1198     else if (workerCountOf(recheck) == 0)
1199     addWorker(null, false);
1200 dl 1.86 }
1201 dl 1.107 else if (!addWorker(command, false))
1202 dl 1.85 reject(command);
1203 tim 1.1 }
1204 dl 1.4
1205 dl 1.53 /**
1206     * Initiates an orderly shutdown in which previously submitted
1207     * tasks are executed, but no new tasks will be
1208     * accepted. Invocation has no additional effect if already shut
1209     * down.
1210     * @throws SecurityException if a security manager exists and
1211     * shutting down this ExecutorService may manipulate threads that
1212     * the caller is not permitted to modify because it does not hold
1213     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1214 jsr166 1.68 * or the security manager's <tt>checkAccess</tt> method denies access.
1215 dl 1.53 */
1216 dl 1.2 public void shutdown() {
1217 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1218 dl 1.2 mainLock.lock();
1219     try {
1220 dl 1.107 checkShutdownAccess();
1221     advanceRunState(SHUTDOWN);
1222 jsr166 1.113 interruptIdleWorkers();
1223 dl 1.107 onShutdown(); // hook for ScheduledThreadPoolExecutor
1224 tim 1.14 } finally {
1225 dl 1.2 mainLock.unlock();
1226     }
1227 dl 1.107 tryTerminate();
1228 tim 1.1 }
1229    
1230 dl 1.53 /**
1231     * Attempts to stop all actively executing tasks, halts the
1232 jsr166 1.75 * processing of waiting tasks, and returns a list of the tasks
1233 dl 1.85 * that were awaiting execution. These tasks are drained (removed)
1234     * from the task queue upon return from this method.
1235 jsr166 1.66 *
1236 jsr166 1.75 * <p>There are no guarantees beyond best-effort attempts to stop
1237     * processing actively executing tasks. This implementation
1238     * cancels tasks via {@link Thread#interrupt}, so any task that
1239     * fails to respond to interrupts may never terminate.
1240 dl 1.53 *
1241     * @return list of tasks that never commenced execution
1242     * @throws SecurityException if a security manager exists and
1243     * shutting down this ExecutorService may manipulate threads that
1244     * the caller is not permitted to modify because it does not hold
1245     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1246     * or the security manager's <tt>checkAccess</tt> method denies access.
1247     */
1248 tim 1.39 public List<Runnable> shutdownNow() {
1249 dl 1.107 List<Runnable> tasks;
1250 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1251 dl 1.2 mainLock.lock();
1252     try {
1253 dl 1.107 checkShutdownAccess();
1254     advanceRunState(STOP);
1255     interruptWorkers();
1256     tasks = drainQueue();
1257 tim 1.14 } finally {
1258 dl 1.2 mainLock.unlock();
1259     }
1260 dl 1.107 tryTerminate();
1261     return tasks;
1262 dl 1.86 }
1263    
1264 dl 1.2 public boolean isShutdown() {
1265 dl 1.107 return runStateOf(ctl.get()) != RUNNING;
1266 dl 1.16 }
1267    
1268 jsr166 1.66 /**
1269 dl 1.55 * Returns true if this executor is in the process of terminating
1270 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1271     * completely terminated. This method may be useful for
1272     * debugging. A return of <tt>true</tt> reported a sufficient
1273     * period after shutdown may indicate that submitted tasks have
1274     * ignored or suppressed interruption, causing this executor not
1275     * to properly terminate.
1276 jsr166 1.93 * @return true if terminating but not yet terminated
1277 dl 1.16 */
1278     public boolean isTerminating() {
1279 dl 1.107 int rs = runStateOf(ctl.get());
1280     return rs == SHUTDOWN || rs == STOP;
1281 tim 1.1 }
1282    
1283 dl 1.2 public boolean isTerminated() {
1284 dl 1.107 return runStateOf(ctl.get()) == TERMINATED;
1285 dl 1.2 }
1286 tim 1.1
1287 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1288     throws InterruptedException {
1289 dl 1.50 long nanos = unit.toNanos(timeout);
1290 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1291 dl 1.2 mainLock.lock();
1292     try {
1293 dl 1.25 for (;;) {
1294 dl 1.107 if (runStateOf(ctl.get()) == TERMINATED)
1295 dl 1.25 return true;
1296     if (nanos <= 0)
1297     return false;
1298     nanos = termination.awaitNanos(nanos);
1299     }
1300 tim 1.14 } finally {
1301 dl 1.2 mainLock.unlock();
1302     }
1303 dl 1.15 }
1304    
1305     /**
1306     * Invokes <tt>shutdown</tt> when this executor is no longer
1307 dl 1.107 * referenced and there are no threads.
1308 jsr166 1.66 */
1309 dl 1.107 protected void finalize() {
1310 dl 1.15 shutdown();
1311 dl 1.2 }
1312 tim 1.10
1313 dl 1.2 /**
1314     * Sets the thread factory used to create new threads.
1315     *
1316     * @param threadFactory the new thread factory
1317 dl 1.30 * @throws NullPointerException if threadFactory is null
1318 tim 1.11 * @see #getThreadFactory
1319 dl 1.2 */
1320     public void setThreadFactory(ThreadFactory threadFactory) {
1321 dl 1.30 if (threadFactory == null)
1322     throw new NullPointerException();
1323 dl 1.2 this.threadFactory = threadFactory;
1324 tim 1.1 }
1325    
1326 dl 1.2 /**
1327     * Returns the thread factory used to create new threads.
1328     *
1329     * @return the current thread factory
1330 tim 1.11 * @see #setThreadFactory
1331 dl 1.2 */
1332     public ThreadFactory getThreadFactory() {
1333     return threadFactory;
1334 tim 1.1 }
1335    
1336 dl 1.2 /**
1337     * Sets a new handler for unexecutable tasks.
1338     *
1339     * @param handler the new handler
1340 dl 1.31 * @throws NullPointerException if handler is null
1341 tim 1.11 * @see #getRejectedExecutionHandler
1342 dl 1.2 */
1343     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1344 dl 1.31 if (handler == null)
1345     throw new NullPointerException();
1346 dl 1.2 this.handler = handler;
1347     }
1348 tim 1.1
1349 dl 1.2 /**
1350     * Returns the current handler for unexecutable tasks.
1351     *
1352     * @return the current handler
1353 tim 1.11 * @see #setRejectedExecutionHandler
1354 dl 1.2 */
1355     public RejectedExecutionHandler getRejectedExecutionHandler() {
1356     return handler;
1357 tim 1.1 }
1358    
1359 dl 1.2 /**
1360     * Sets the core number of threads. This overrides any value set
1361     * in the constructor. If the new value is smaller than the
1362     * current value, excess existing threads will be terminated when
1363 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1364     * be started to execute any queued tasks.
1365 tim 1.1 *
1366 dl 1.2 * @param corePoolSize the new core size
1367 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1368 dl 1.8 * less than zero
1369 tim 1.11 * @see #getCorePoolSize
1370 tim 1.1 */
1371 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1372     if (corePoolSize < 0)
1373     throw new IllegalArgumentException();
1374 dl 1.107 int delta = corePoolSize - this.corePoolSize;
1375     this.corePoolSize = corePoolSize;
1376     if (workerCountOf(ctl.get()) > corePoolSize)
1377 jsr166 1.113 interruptIdleWorkers();
1378 dl 1.107 else if (delta > 0) {
1379     // We don't really know how many new threads are "needed".
1380     // As a heuristic, prestart enough new workers (up to new
1381     // core size) to handle the current number of tasks in
1382     // queue, but stop if queue becomes empty while doing so.
1383     int k = Math.min(delta, workQueue.size());
1384     while (k-- > 0 && addWorker(null, true)) {
1385     if (workQueue.isEmpty())
1386     break;
1387 tim 1.38 }
1388 dl 1.2 }
1389     }
1390 tim 1.1
1391     /**
1392 dl 1.2 * Returns the core number of threads.
1393 tim 1.1 *
1394 dl 1.2 * @return the core number of threads
1395 tim 1.11 * @see #setCorePoolSize
1396 tim 1.1 */
1397 tim 1.10 public int getCorePoolSize() {
1398 dl 1.2 return corePoolSize;
1399 dl 1.16 }
1400    
1401     /**
1402 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1403 dl 1.16 * overrides the default policy of starting core threads only when
1404     * new tasks are executed. This method will return <tt>false</tt>
1405     * if all core threads have already been started.
1406     * @return true if a thread was started
1407 jsr166 1.66 */
1408 dl 1.16 public boolean prestartCoreThread() {
1409 dl 1.107 return workerCountOf(ctl.get()) < corePoolSize &&
1410     addWorker(null, true);
1411 dl 1.16 }
1412    
1413     /**
1414 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1415 dl 1.16 * overrides the default policy of starting core threads only when
1416 jsr166 1.66 * new tasks are executed.
1417 jsr166 1.88 * @return the number of threads started
1418 jsr166 1.66 */
1419 dl 1.16 public int prestartAllCoreThreads() {
1420     int n = 0;
1421 dl 1.107 while (addWorker(null, true))
1422 dl 1.16 ++n;
1423     return n;
1424 dl 1.2 }
1425 tim 1.1
1426     /**
1427 dl 1.62 * Returns true if this pool allows core threads to time out and
1428     * terminate if no tasks arrive within the keepAlive time, being
1429     * replaced if needed when new tasks arrive. When true, the same
1430     * keep-alive policy applying to non-core threads applies also to
1431     * core threads. When false (the default), core threads are never
1432     * terminated due to lack of incoming tasks.
1433     * @return <tt>true</tt> if core threads are allowed to time out,
1434     * else <tt>false</tt>
1435 jsr166 1.72 *
1436     * @since 1.6
1437 dl 1.62 */
1438     public boolean allowsCoreThreadTimeOut() {
1439     return allowCoreThreadTimeOut;
1440     }
1441    
1442     /**
1443     * Sets the policy governing whether core threads may time out and
1444     * terminate if no tasks arrive within the keep-alive time, being
1445     * replaced if needed when new tasks arrive. When false, core
1446     * threads are never terminated due to lack of incoming
1447     * tasks. When true, the same keep-alive policy applying to
1448     * non-core threads applies also to core threads. To avoid
1449     * continual thread replacement, the keep-alive time must be
1450 dl 1.64 * greater than zero when setting <tt>true</tt>. This method
1451     * should in general be called before the pool is actively used.
1452 dl 1.62 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1453 dl 1.64 * @throws IllegalArgumentException if value is <tt>true</tt>
1454     * and the current keep-alive time is not greater than zero.
1455 jsr166 1.72 *
1456     * @since 1.6
1457 dl 1.62 */
1458     public void allowCoreThreadTimeOut(boolean value) {
1459 dl 1.64 if (value && keepAliveTime <= 0)
1460     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1461 dl 1.107 if (value != allowCoreThreadTimeOut) {
1462     allowCoreThreadTimeOut = value;
1463     if (value)
1464 jsr166 1.113 interruptIdleWorkers();
1465 dl 1.107 }
1466 dl 1.62 }
1467    
1468     /**
1469 tim 1.1 * Sets the maximum allowed number of threads. This overrides any
1470 dl 1.2 * value set in the constructor. If the new value is smaller than
1471     * the current value, excess existing threads will be
1472     * terminated when they next become idle.
1473 tim 1.1 *
1474 dl 1.2 * @param maximumPoolSize the new maximum
1475 jsr166 1.84 * @throws IllegalArgumentException if the new maximum is
1476     * less than or equal to zero, or
1477     * less than the {@linkplain #getCorePoolSize core pool size}
1478 tim 1.11 * @see #getMaximumPoolSize
1479 dl 1.2 */
1480     public void setMaximumPoolSize(int maximumPoolSize) {
1481     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1482     throw new IllegalArgumentException();
1483 dl 1.107 this.maximumPoolSize = maximumPoolSize;
1484     if (workerCountOf(ctl.get()) > maximumPoolSize)
1485 jsr166 1.113 interruptIdleWorkers();
1486 dl 1.2 }
1487 tim 1.1
1488     /**
1489     * Returns the maximum allowed number of threads.
1490     *
1491 dl 1.2 * @return the maximum allowed number of threads
1492 tim 1.11 * @see #setMaximumPoolSize
1493 tim 1.1 */
1494 tim 1.10 public int getMaximumPoolSize() {
1495 dl 1.2 return maximumPoolSize;
1496     }
1497 tim 1.1
1498     /**
1499     * Sets the time limit for which threads may remain idle before
1500 dl 1.2 * being terminated. If there are more than the core number of
1501 tim 1.1 * threads currently in the pool, after waiting this amount of
1502     * time without processing a task, excess threads will be
1503     * terminated. This overrides any value set in the constructor.
1504     * @param time the time to wait. A time value of zero will cause
1505     * excess threads to terminate immediately after executing tasks.
1506 jsr166 1.96 * @param unit the time unit of the time argument
1507 dl 1.64 * @throws IllegalArgumentException if time less than zero or
1508     * if time is zero and allowsCoreThreadTimeOut
1509 tim 1.11 * @see #getKeepAliveTime
1510 tim 1.1 */
1511 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1512     if (time < 0)
1513     throw new IllegalArgumentException();
1514 dl 1.64 if (time == 0 && allowsCoreThreadTimeOut())
1515     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1516 dl 1.107 long keepAliveTime = unit.toNanos(time);
1517     long delta = keepAliveTime - this.keepAliveTime;
1518     this.keepAliveTime = keepAliveTime;
1519     if (delta < 0)
1520 jsr166 1.113 interruptIdleWorkers();
1521 dl 1.2 }
1522 tim 1.1
1523     /**
1524     * Returns the thread keep-alive time, which is the amount of time
1525 jsr166 1.93 * that threads in excess of the core pool size may remain
1526 tim 1.10 * idle before being terminated.
1527 tim 1.1 *
1528 dl 1.2 * @param unit the desired time unit of the result
1529 tim 1.1 * @return the time limit
1530 tim 1.11 * @see #setKeepAliveTime
1531 tim 1.1 */
1532 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1533 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1534     }
1535 tim 1.1
1536 dl 1.86 /* User-level queue utilities */
1537    
1538     /**
1539     * Returns the task queue used by this executor. Access to the
1540     * task queue is intended primarily for debugging and monitoring.
1541     * This queue may be in active use. Retrieving the task queue
1542     * does not prevent queued tasks from executing.
1543     *
1544     * @return the task queue
1545     */
1546     public BlockingQueue<Runnable> getQueue() {
1547     return workQueue;
1548     }
1549    
1550     /**
1551     * Removes this task from the executor's internal queue if it is
1552     * present, thus causing it not to be run if it has not already
1553     * started.
1554     *
1555     * <p> This method may be useful as one part of a cancellation
1556     * scheme. It may fail to remove tasks that have been converted
1557     * into other forms before being placed on the internal queue. For
1558     * example, a task entered using <tt>submit</tt> might be
1559     * converted into a form that maintains <tt>Future</tt> status.
1560     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1561     * may be used to remove those Futures that have been cancelled.
1562     *
1563     * @param task the task to remove
1564     * @return true if the task was removed
1565     */
1566     public boolean remove(Runnable task) {
1567 dl 1.114 boolean removed;
1568     final ReentrantLock mainLock = this.mainLock;
1569     mainLock.lock();
1570     try {
1571     removed = workQueue.remove(task);
1572     } finally {
1573     mainLock.unlock();
1574     }
1575     if (removed)
1576     tryTerminate(); // In case SHUTDOWN and now empty
1577 dl 1.107 return removed;
1578 dl 1.86 }
1579    
1580     /**
1581     * Tries to remove from the work queue all {@link Future}
1582     * tasks that have been cancelled. This method can be useful as a
1583     * storage reclamation operation, that has no other impact on
1584     * functionality. Cancelled tasks are never executed, but may
1585     * accumulate in work queues until worker threads can actively
1586     * remove them. Invoking this method instead tries to remove them now.
1587     * However, this method may fail to remove tasks in
1588     * the presence of interference by other threads.
1589     */
1590     public void purge() {
1591 jsr166 1.111 final BlockingQueue<Runnable> q = workQueue;
1592 dl 1.86 try {
1593 dl 1.107 Iterator<Runnable> it = q.iterator();
1594 dl 1.86 while (it.hasNext()) {
1595     Runnable r = it.next();
1596 jsr166 1.111 if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1597     it.remove();
1598 dl 1.107 }
1599 jsr166 1.111 } catch (ConcurrentModificationException fallThrough) {
1600     // Take slow path if we encounter interference during traversal.
1601     // Make copy for traversal and call remove for cancelled entries.
1602     // The slow path is more likely to be O(N*N).
1603     for (Object r : q.toArray())
1604     if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
1605     q.remove(r);
1606 dl 1.86 }
1607 dl 1.107
1608     tryTerminate(); // In case SHUTDOWN and now empty
1609 dl 1.86 }
1610    
1611 tim 1.1 /* Statistics */
1612    
1613     /**
1614     * Returns the current number of threads in the pool.
1615     *
1616     * @return the number of threads
1617     */
1618 tim 1.10 public int getPoolSize() {
1619 dl 1.107 final ReentrantLock mainLock = this.mainLock;
1620     mainLock.lock();
1621     try {
1622     return workers.size();
1623     } finally {
1624     mainLock.unlock();
1625     }
1626 dl 1.2 }
1627 tim 1.1
1628     /**
1629 dl 1.2 * Returns the approximate number of threads that are actively
1630 tim 1.1 * executing tasks.
1631     *
1632     * @return the number of threads
1633     */
1634 tim 1.10 public int getActiveCount() {
1635 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1636 dl 1.2 mainLock.lock();
1637     try {
1638     int n = 0;
1639 tim 1.39 for (Worker w : workers) {
1640 dl 1.107 if (w.isLocked())
1641 dl 1.2 ++n;
1642     }
1643     return n;
1644 tim 1.14 } finally {
1645 dl 1.2 mainLock.unlock();
1646     }
1647     }
1648 tim 1.1
1649     /**
1650 dl 1.2 * Returns the largest number of threads that have ever
1651     * simultaneously been in the pool.
1652 tim 1.1 *
1653     * @return the number of threads
1654     */
1655 tim 1.10 public int getLargestPoolSize() {
1656 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1657 dl 1.2 mainLock.lock();
1658     try {
1659     return largestPoolSize;
1660 tim 1.14 } finally {
1661 dl 1.2 mainLock.unlock();
1662     }
1663     }
1664 tim 1.1
1665     /**
1666 dl 1.85 * Returns the approximate total number of tasks that have ever been
1667 dl 1.2 * scheduled for execution. Because the states of tasks and
1668     * threads may change dynamically during computation, the returned
1669 dl 1.97 * value is only an approximation.
1670 tim 1.1 *
1671     * @return the number of tasks
1672     */
1673 tim 1.10 public long getTaskCount() {
1674 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1675 dl 1.2 mainLock.lock();
1676     try {
1677     long n = completedTaskCount;
1678 tim 1.39 for (Worker w : workers) {
1679 dl 1.2 n += w.completedTasks;
1680 dl 1.107 if (w.isLocked())
1681 dl 1.2 ++n;
1682     }
1683     return n + workQueue.size();
1684 tim 1.14 } finally {
1685 dl 1.2 mainLock.unlock();
1686     }
1687     }
1688 tim 1.1
1689     /**
1690 dl 1.2 * Returns the approximate total number of tasks that have
1691     * completed execution. Because the states of tasks and threads
1692     * may change dynamically during computation, the returned value
1693 dl 1.17 * is only an approximation, but one that does not ever decrease
1694     * across successive calls.
1695 tim 1.1 *
1696     * @return the number of tasks
1697     */
1698 tim 1.10 public long getCompletedTaskCount() {
1699 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1700 dl 1.2 mainLock.lock();
1701     try {
1702     long n = completedTaskCount;
1703 tim 1.39 for (Worker w : workers)
1704     n += w.completedTasks;
1705 dl 1.2 return n;
1706 tim 1.14 } finally {
1707 dl 1.2 mainLock.unlock();
1708     }
1709     }
1710 tim 1.1
1711 dl 1.86 /* Extension hooks */
1712    
1713 tim 1.1 /**
1714 dl 1.17 * Method invoked prior to executing the given Runnable in the
1715 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1716     * will execute task <tt>r</tt>, and may be used to re-initialize
1717 jsr166 1.73 * ThreadLocals, or to perform logging.
1718     *
1719     * <p>This implementation does nothing, but may be customized in
1720     * subclasses. Note: To properly nest multiple overridings, subclasses
1721     * should generally invoke <tt>super.beforeExecute</tt> at the end of
1722     * this method.
1723 tim 1.1 *
1724 dl 1.2 * @param t the thread that will run task r.
1725     * @param r the task that will be executed.
1726 tim 1.1 */
1727 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1728 tim 1.1
1729     /**
1730 jsr166 1.70 * Method invoked upon completion of execution of the given Runnable.
1731     * This method is invoked by the thread that executed the task. If
1732     * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1733     * or <tt>Error</tt> that caused execution to terminate abruptly.
1734 dl 1.69 *
1735 dl 1.107 * <p>This implementation does nothing, but may be customized in
1736     * subclasses. Note: To properly nest multiple overridings, subclasses
1737     * should generally invoke <tt>super.afterExecute</tt> at the
1738     * beginning of this method.
1739     *
1740 dl 1.69 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1741     * {@link FutureTask}) either explicitly or via methods such as
1742     * <tt>submit</tt>, these task objects catch and maintain
1743     * computational exceptions, and so they do not cause abrupt
1744 jsr166 1.70 * termination, and the internal exceptions are <em>not</em>
1745 dl 1.107 * passed to this method. If you would like to trap both kinds of
1746     * failures in this method, you can further probe for such cases,
1747     * as in this sample subclass that prints either the direct cause
1748     * or the underlying exception if a task has been aborted:
1749     *
1750     * <pre>
1751     * class ExtendedExecutor extends ThreadPoolExecutor {
1752     * // ...
1753     * protected void afterExecute(Runnable r, Throwable t) {
1754     * super.afterExecute(r, t);
1755     * if (t == null && r instanceOf Future&lt;?&gt;) {
1756     * try {
1757     * Object result = ((Future&lt;?&gt;) r).get();
1758     * } catch (CancellationException ce) {
1759     * t = ce;
1760     * } catch (ExecutionException ee) {
1761     * t = ee.getCause();
1762     * } catch (InterruptedException ie) {
1763     * Thread.currentThread().interrupt(); // ignore/reset
1764     * }
1765     * }
1766     * if (t != null)
1767     * System.out.println(t);
1768     * }
1769     * }
1770     * </pre>
1771 tim 1.1 *
1772 dl 1.2 * @param r the runnable that has completed.
1773 dl 1.24 * @param t the exception that caused termination, or null if
1774 dl 1.2 * execution completed normally.
1775 tim 1.1 */
1776 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1777 tim 1.1
1778 dl 1.2 /**
1779     * Method invoked when the Executor has terminated. Default
1780 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1781     * overridings, subclasses should generally invoke
1782     * <tt>super.terminated</tt> within this method.
1783 dl 1.2 */
1784     protected void terminated() { }
1785 tim 1.1
1786 dl 1.86 /* Predefined RejectedExecutionHandlers */
1787    
1788 tim 1.1 /**
1789 dl 1.21 * A handler for rejected tasks that runs the rejected task
1790     * directly in the calling thread of the <tt>execute</tt> method,
1791     * unless the executor has been shut down, in which case the task
1792     * is discarded.
1793 tim 1.1 */
1794 jsr166 1.71 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1795 tim 1.1 /**
1796 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1797 tim 1.1 */
1798     public CallerRunsPolicy() { }
1799    
1800 dl 1.24 /**
1801     * Executes task r in the caller's thread, unless the executor
1802     * has been shut down, in which case the task is discarded.
1803     * @param r the runnable task requested to be executed
1804     * @param e the executor attempting to execute this task
1805     */
1806 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1807     if (!e.isShutdown()) {
1808 tim 1.1 r.run();
1809     }
1810     }
1811     }
1812    
1813     /**
1814 dl 1.21 * A handler for rejected tasks that throws a
1815 dl 1.8 * <tt>RejectedExecutionException</tt>.
1816 tim 1.1 */
1817 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1818 tim 1.1 /**
1819 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1820 tim 1.1 */
1821     public AbortPolicy() { }
1822    
1823 dl 1.24 /**
1824 dl 1.54 * Always throws RejectedExecutionException.
1825 dl 1.24 * @param r the runnable task requested to be executed
1826     * @param e the executor attempting to execute this task
1827     * @throws RejectedExecutionException always.
1828     */
1829 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1830     throw new RejectedExecutionException();
1831 tim 1.1 }
1832     }
1833    
1834     /**
1835 dl 1.21 * A handler for rejected tasks that silently discards the
1836     * rejected task.
1837 tim 1.1 */
1838 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1839 tim 1.1 /**
1840 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1841 tim 1.1 */
1842     public DiscardPolicy() { }
1843    
1844 dl 1.24 /**
1845     * Does nothing, which has the effect of discarding task r.
1846     * @param r the runnable task requested to be executed
1847     * @param e the executor attempting to execute this task
1848     */
1849 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1850 tim 1.1 }
1851     }
1852    
1853     /**
1854 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1855     * request and then retries <tt>execute</tt>, unless the executor
1856     * is shut down, in which case the task is discarded.
1857 tim 1.1 */
1858 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1859 tim 1.1 /**
1860 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1861 tim 1.1 */
1862     public DiscardOldestPolicy() { }
1863    
1864 dl 1.24 /**
1865     * Obtains and ignores the next task that the executor
1866     * would otherwise execute, if one is immediately available,
1867     * and then retries execution of task r, unless the executor
1868     * is shut down, in which case task r is instead discarded.
1869     * @param r the runnable task requested to be executed
1870     * @param e the executor attempting to execute this task
1871     */
1872 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1873     if (!e.isShutdown()) {
1874     e.getQueue().poll();
1875     e.execute(r);
1876 tim 1.1 }
1877     }
1878     }
1879     }