ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.97
Committed: Sat Jul 15 14:38:20 2006 UTC (17 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.96: +15 -23 lines
Log Message:
Preserve core pool size when tasks encounter exceptions

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.2 import java.util.*;
10 tim 1.1
11     /**
12 dl 1.17 * An {@link ExecutorService} that executes each submitted task using
13 dl 1.28 * one of possibly several pooled threads, normally configured
14     * using {@link Executors} factory methods.
15 tim 1.1 *
16 dl 1.17 * <p>Thread pools address two different problems: they usually
17     * provide improved performance when executing large numbers of
18     * asynchronous tasks, due to reduced per-task invocation overhead,
19     * and they provide a means of bounding and managing the resources,
20     * including threads, consumed when executing a collection of tasks.
21 dl 1.20 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
22 dl 1.22 * statistics, such as the number of completed tasks.
23 dl 1.17 *
24 tim 1.1 * <p>To be useful across a wide range of contexts, this class
25 dl 1.24 * provides many adjustable parameters and extensibility
26     * hooks. However, programmers are urged to use the more convenient
27 dl 1.20 * {@link Executors} factory methods {@link
28     * Executors#newCachedThreadPool} (unbounded thread pool, with
29     * automatic thread reclamation), {@link Executors#newFixedThreadPool}
30     * (fixed size thread pool) and {@link
31     * Executors#newSingleThreadExecutor} (single background thread), that
32 dl 1.22 * preconfigure settings for the most common usage
33     * scenarios. Otherwise, use the following guide when manually
34 dl 1.24 * configuring and tuning this class:
35 dl 1.17 *
36 tim 1.1 * <dl>
37 dl 1.2 *
38 dl 1.21 * <dt>Core and maximum pool sizes</dt>
39 dl 1.2 *
40 dl 1.19 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
41 jsr166 1.66 * pool size
42 dl 1.21 * (see {@link ThreadPoolExecutor#getPoolSize})
43 jsr166 1.66 * according to the bounds set by corePoolSize
44 dl 1.21 * (see {@link ThreadPoolExecutor#getCorePoolSize})
45     * and
46     * maximumPoolSize
47     * (see {@link ThreadPoolExecutor#getMaximumPoolSize}).
48     * When a new task is submitted in method {@link
49     * ThreadPoolExecutor#execute}, and fewer than corePoolSize threads
50     * are running, a new thread is created to handle the request, even if
51     * other worker threads are idle. If there are more than
52     * corePoolSize but less than maximumPoolSize threads running, a new
53     * thread will be created only if the queue is full. By setting
54     * corePoolSize and maximumPoolSize the same, you create a fixed-size
55     * thread pool. By setting maximumPoolSize to an essentially unbounded
56     * value such as <tt>Integer.MAX_VALUE</tt>, you allow the pool to
57 dl 1.27 * accommodate an arbitrary number of concurrent tasks. Most typically,
58 dl 1.21 * core and maximum pool sizes are set only upon construction, but they
59     * may also be changed dynamically using {@link
60     * ThreadPoolExecutor#setCorePoolSize} and {@link
61 jsr166 1.93 * ThreadPoolExecutor#setMaximumPoolSize}. </dd>
62 dl 1.2 *
63 jsr166 1.93 * <dt>On-demand construction</dt>
64 dl 1.2 *
65 dl 1.21 * <dd> By default, even core threads are initially created and
66 dl 1.69 * started only when new tasks arrive, but this can be overridden
67 dl 1.21 * dynamically using method {@link
68     * ThreadPoolExecutor#prestartCoreThread} or
69 dl 1.64 * {@link ThreadPoolExecutor#prestartAllCoreThreads}.
70     * You probably want to prestart threads if you construct the
71     * pool with a non-empty queue. </dd>
72 dl 1.2 *
73 tim 1.1 * <dt>Creating new threads</dt>
74 dl 1.2 *
75 dl 1.33 * <dd>New threads are created using a {@link
76     * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
77 dl 1.34 * {@link Executors#defaultThreadFactory} is used, that creates threads to all
78 dl 1.33 * be in the same {@link ThreadGroup} and with the same
79     * <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying
80     * a different ThreadFactory, you can alter the thread's name, thread
81 dl 1.57 * group, priority, daemon status, etc. If a <tt>ThreadFactory</tt> fails to create
82 jsr166 1.66 * a thread when asked by returning null from <tt>newThread</tt>,
83 dl 1.57 * the executor will continue, but might
84 dl 1.56 * not be able to execute any tasks. </dd>
85 dl 1.2 *
86 dl 1.21 * <dt>Keep-alive times</dt>
87     *
88     * <dd>If the pool currently has more than corePoolSize threads,
89     * excess threads will be terminated if they have been idle for more
90     * than the keepAliveTime (see {@link
91     * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
92     * reducing resource consumption when the pool is not being actively
93     * used. If the pool becomes more active later, new threads will be
94 dl 1.62 * constructed. This parameter can also be changed dynamically using
95     * method {@link ThreadPoolExecutor#setKeepAliveTime}. Using a value
96     * of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS} effectively
97     * disables idle threads from ever terminating prior to shut down. By
98     * default, the keep-alive policy applies only when there are more
99     * than corePoolSizeThreads. But method {@link
100     * ThreadPoolExecutor#allowCoreThreadTimeOut} can be used to apply
101 dl 1.64 * this time-out policy to core threads as well, so long as
102     * the keepAliveTime value is non-zero. </dd>
103 dl 1.21 *
104 dl 1.48 * <dt>Queuing</dt>
105 dl 1.21 *
106     * <dd>Any {@link BlockingQueue} may be used to transfer and hold
107     * submitted tasks. The use of this queue interacts with pool sizing:
108 dl 1.2 *
109 dl 1.21 * <ul>
110     *
111 dl 1.23 * <li> If fewer than corePoolSize threads are running, the Executor
112     * always prefers adding a new thread
113 dl 1.48 * rather than queuing.</li>
114 dl 1.21 *
115 dl 1.23 * <li> If corePoolSize or more threads are running, the Executor
116     * always prefers queuing a request rather than adding a new
117     * thread.</li>
118 jsr166 1.66 *
119 dl 1.21 * <li> If a request cannot be queued, a new thread is created unless
120     * this would exceed maximumPoolSize, in which case, the task will be
121     * rejected.</li>
122     *
123     * </ul>
124     *
125     * There are three general strategies for queuing:
126     * <ol>
127     *
128     * <li> <em> Direct handoffs.</em> A good default choice for a work
129     * queue is a {@link SynchronousQueue} that hands off tasks to threads
130     * without otherwise holding them. Here, an attempt to queue a task
131     * will fail if no threads are immediately available to run it, so a
132     * new thread will be constructed. This policy avoids lockups when
133     * handling sets of requests that might have internal dependencies.
134     * Direct handoffs generally require unbounded maximumPoolSizes to
135 dl 1.24 * avoid rejection of new submitted tasks. This in turn admits the
136 dl 1.21 * possibility of unbounded thread growth when commands continue to
137     * arrive on average faster than they can be processed. </li>
138     *
139     * <li><em> Unbounded queues.</em> Using an unbounded queue (for
140     * example a {@link LinkedBlockingQueue} without a predefined
141 dl 1.69 * capacity) will cause new tasks to wait in the queue when all
142 dl 1.22 * corePoolSize threads are busy. Thus, no more than corePoolSize
143     * threads will ever be created. (And the value of the maximumPoolSize
144     * therefore doesn't have any effect.) This may be appropriate when
145     * each task is completely independent of others, so tasks cannot
146     * affect each others execution; for example, in a web page server.
147     * While this style of queuing can be useful in smoothing out
148     * transient bursts of requests, it admits the possibility of
149     * unbounded work queue growth when commands continue to arrive on
150     * average faster than they can be processed. </li>
151 dl 1.21 *
152     * <li><em>Bounded queues.</em> A bounded queue (for example, an
153     * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
154     * used with finite maximumPoolSizes, but can be more difficult to
155     * tune and control. Queue sizes and maximum pool sizes may be traded
156     * off for each other: Using large queues and small pools minimizes
157     * CPU usage, OS resources, and context-switching overhead, but can
158 dl 1.27 * lead to artificially low throughput. If tasks frequently block (for
159 dl 1.21 * example if they are I/O bound), a system may be able to schedule
160     * time for more threads than you otherwise allow. Use of small queues
161 dl 1.24 * generally requires larger pool sizes, which keeps CPUs busier but
162     * may encounter unacceptable scheduling overhead, which also
163     * decreases throughput. </li>
164 dl 1.21 *
165     * </ol>
166     *
167     * </dd>
168     *
169     * <dt>Rejected tasks</dt>
170     *
171     * <dd> New tasks submitted in method {@link
172     * ThreadPoolExecutor#execute} will be <em>rejected</em> when the
173     * Executor has been shut down, and also when the Executor uses finite
174     * bounds for both maximum threads and work queue capacity, and is
175 dl 1.22 * saturated. In either case, the <tt>execute</tt> method invokes the
176     * {@link RejectedExecutionHandler#rejectedExecution} method of its
177     * {@link RejectedExecutionHandler}. Four predefined handler policies
178     * are provided:
179 dl 1.21 *
180     * <ol>
181     *
182     * <li> In the
183     * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
184     * runtime {@link RejectedExecutionException} upon rejection. </li>
185 jsr166 1.66 *
186 dl 1.21 * <li> In {@link
187     * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
188     * <tt>execute</tt> itself runs the task. This provides a simple
189     * feedback control mechanism that will slow down the rate that new
190     * tasks are submitted. </li>
191     *
192     * <li> In {@link ThreadPoolExecutor.DiscardPolicy},
193     * a task that cannot be executed is simply dropped. </li>
194     *
195     * <li>In {@link
196     * ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not
197     * shut down, the task at the head of the work queue is dropped, and
198     * then execution is retried (which can fail again, causing this to be
199     * repeated.) </li>
200     *
201     * </ol>
202     *
203     * It is possible to define and use other kinds of {@link
204     * RejectedExecutionHandler} classes. Doing so requires some care
205     * especially when policies are designed to work only under particular
206 dl 1.48 * capacity or queuing policies. </dd>
207 dl 1.21 *
208     * <dt>Hook methods</dt>
209     *
210 dl 1.23 * <dd>This class provides <tt>protected</tt> overridable {@link
211 dl 1.21 * ThreadPoolExecutor#beforeExecute} and {@link
212     * ThreadPoolExecutor#afterExecute} methods that are called before and
213 dl 1.19 * after execution of each task. These can be used to manipulate the
214 dl 1.59 * execution environment; for example, reinitializing ThreadLocals,
215 dl 1.21 * gathering statistics, or adding log entries. Additionally, method
216     * {@link ThreadPoolExecutor#terminated} can be overridden to perform
217     * any special processing that needs to be done once the Executor has
218 jsr166 1.66 * fully terminated.
219 dl 1.57 *
220 jsr166 1.66 * <p>If hook or callback methods throw
221 dl 1.57 * exceptions, internal worker threads may in turn fail and
222 jsr166 1.66 * abruptly terminate.</dd>
223 dl 1.2 *
224 dl 1.21 * <dt>Queue maintenance</dt>
225 dl 1.2 *
226 dl 1.24 * <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to
227     * the work queue for purposes of monitoring and debugging. Use of
228     * this method for any other purpose is strongly discouraged. Two
229     * supplied methods, {@link ThreadPoolExecutor#remove} and {@link
230     * ThreadPoolExecutor#purge} are available to assist in storage
231     * reclamation when large numbers of queued tasks become
232 jsr166 1.80 * cancelled.</dd>
233 dl 1.79 *
234     * <dt>Finalization</dt>
235     *
236     * <dd> A pool that is no longer referenced in a program <em>AND</em>
237     * has no remaining threads will be <tt>shutdown</tt>
238     * automatically. If you would like to ensure that unreferenced pools
239     * are reclaimed even if users forget to call {@link
240     * ThreadPoolExecutor#shutdown}, then you must arrange that unused
241     * threads eventually die, by setting appropriate keep-alive times,
242     * using a lower bound of zero core threads and/or setting {@link
243     * ThreadPoolExecutor#allowCoreThreadTimeOut}. </dd> </dl>
244 tim 1.1 *
245 dl 1.43 * <p> <b>Extension example</b>. Most extensions of this class
246     * override one or more of the protected hook methods. For example,
247     * here is a subclass that adds a simple pause/resume feature:
248     *
249     * <pre>
250     * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
251     * private boolean isPaused;
252     * private ReentrantLock pauseLock = new ReentrantLock();
253     * private Condition unpaused = pauseLock.newCondition();
254     *
255     * public PausableThreadPoolExecutor(...) { super(...); }
256 jsr166 1.66 *
257 dl 1.43 * protected void beforeExecute(Thread t, Runnable r) {
258     * super.beforeExecute(t, r);
259     * pauseLock.lock();
260     * try {
261     * while (isPaused) unpaused.await();
262 jsr166 1.66 * } catch (InterruptedException ie) {
263 dl 1.53 * t.interrupt();
264 dl 1.43 * } finally {
265 dl 1.53 * pauseLock.unlock();
266 dl 1.43 * }
267     * }
268 jsr166 1.66 *
269 dl 1.43 * public void pause() {
270     * pauseLock.lock();
271     * try {
272     * isPaused = true;
273     * } finally {
274 dl 1.53 * pauseLock.unlock();
275 dl 1.43 * }
276     * }
277 jsr166 1.66 *
278 dl 1.43 * public void resume() {
279     * pauseLock.lock();
280     * try {
281     * isPaused = false;
282     * unpaused.signalAll();
283     * } finally {
284 dl 1.53 * pauseLock.unlock();
285 dl 1.43 * }
286     * }
287     * }
288     * </pre>
289 tim 1.1 * @since 1.5
290 dl 1.8 * @author Doug Lea
291 tim 1.1 */
292 tim 1.38 public class ThreadPoolExecutor extends AbstractExecutorService {
293 dl 1.85
294 dl 1.86 /**
295     * Permission for checking shutdown
296     */
297     private static final RuntimePermission shutdownPerm =
298     new RuntimePermission("modifyThread");
299    
300 dl 1.85 /*
301 dl 1.86 * A ThreadPoolExecutor manages a largish set of control fields.
302     * State changes in fields that affect execution control
303     * guarantees only occur within mainLock regions. These include
304     * fields runState, poolSize, corePoolSize, and maximumPoolSize
305     * However, these fields are also declared volatile, so can be
306     * read outside of locked regions. (Also, the workers Set is
307     * accessed only under lock).
308     *
309 jsr166 1.88 * The other fields representing user control parameters do not
310 dl 1.86 * affect execution invariants, so are declared volatile and
311     * allowed to change (via user methods) asynchronously with
312 dl 1.89 * execution. These fields: allowCoreThreadTimeOut, keepAliveTime,
313     * the rejected execution handler, and threadFactory, are not
314     * updated within locks.
315 dl 1.86 *
316     * The extensive use of volatiles here enables the most
317 jsr166 1.91 * performance-critical actions, such as enqueuing and dequeuing
318 dl 1.86 * tasks in the workQueue, to normally proceed without holding the
319     * mainLock when they see that the state allows actions, although,
320     * as described below, sometimes at the expense of re-checks
321     * following these actions.
322     */
323    
324     /**
325     * runState provides the main lifecyle control, taking on values:
326     *
327 dl 1.85 * RUNNING: Accept new tasks and process queued tasks
328     * SHUTDOWN: Don't accept new tasks, but process queued tasks
329 jsr166 1.91 * STOP: Don't accept new tasks, don't process queued tasks,
330 dl 1.85 * and interrupt in-progress tasks
331 jsr166 1.91 * TERMINATED: Same as STOP, plus all threads have terminated
332 dl 1.86 *
333     * The numerical order among these values matters, to allow
334     * ordered comparisons. The runState monotonically increases over
335     * time, but need not hit each state. The transitions are:
336 jsr166 1.87 *
337     * RUNNING -> SHUTDOWN
338 jsr166 1.88 * On invocation of shutdown(), perhaps implicitly in finalize()
339 jsr166 1.87 * (RUNNING or SHUTDOWN) -> STOP
340 dl 1.86 * On invocation of shutdownNow()
341     * SHUTDOWN -> TERMINATED
342     * When both queue and pool are empty
343     * STOP -> TERMINATED
344     * When pool is empty
345 tim 1.41 */
346 dl 1.86 volatile int runState;
347     static final int RUNNING = 0;
348     static final int SHUTDOWN = 1;
349     static final int STOP = 2;
350     static final int TERMINATED = 3;
351 tim 1.41
352     /**
353 dl 1.86 * The queue used for holding tasks and handing off to worker
354     * threads. Note that when using this queue, we do not require
355     * that workQueue.poll() returning null necessarily means that
356     * workQueue.isEmpty(), so must sometimes check both. This
357     * accommodates special-purpose queues such as DelayQueues for
358     * which poll() is allowed to return null even if it may later
359     * return non-null when delays expire.
360 tim 1.10 */
361 dl 1.2 private final BlockingQueue<Runnable> workQueue;
362    
363     /**
364 dl 1.85 * Lock held on updates to poolSize, corePoolSize,
365     * maximumPoolSize, runState, and workers set.
366 tim 1.10 */
367 dl 1.2 private final ReentrantLock mainLock = new ReentrantLock();
368    
369     /**
370     * Wait condition to support awaitTermination
371 tim 1.10 */
372 dl 1.46 private final Condition termination = mainLock.newCondition();
373 dl 1.2
374     /**
375 jsr166 1.88 * Set containing all worker threads in pool. Accessed only when
376 dl 1.86 * holding mainLock.
377 tim 1.10 */
378 dl 1.17 private final HashSet<Worker> workers = new HashSet<Worker>();
379 dl 1.2
380     /**
381 dl 1.35 * Timeout in nanoseconds for idle threads waiting for work.
382 dl 1.86 * Threads use this timeout when there are more than corePoolSize
383     * present or if allowCoreThreadTimeOut. Otherwise they wait
384     * forever for new work.
385 tim 1.10 */
386 dl 1.2 private volatile long keepAliveTime;
387    
388     /**
389 dl 1.86 * If false (default) core threads stay alive even when idle. If
390     * true, core threads use keepAliveTime to time out waiting for
391     * work.
392 dl 1.62 */
393 dl 1.82 private volatile boolean allowCoreThreadTimeOut;
394 dl 1.62
395     /**
396 dl 1.86 * Core pool size, updated only while holding mainLock, but
397     * volatile to allow concurrent readability even during updates.
398 tim 1.10 */
399 dl 1.2 private volatile int corePoolSize;
400    
401     /**
402 dl 1.86 * Maximum pool size, updated only while holding mainLock but
403     * volatile to allow concurrent readability even during updates.
404 tim 1.10 */
405 dl 1.2 private volatile int maximumPoolSize;
406    
407     /**
408 dl 1.86 * Current pool size, updated only while holding mainLock but
409     * volatile to allow concurrent readability even during updates.
410 tim 1.10 */
411 dl 1.2 private volatile int poolSize;
412    
413     /**
414     * Handler called when saturated or shutdown in execute.
415 tim 1.10 */
416 dl 1.33 private volatile RejectedExecutionHandler handler;
417 dl 1.2
418     /**
419 dl 1.86 * Factory for new threads. All threads are created using this
420     * factory (via method addThread). All callers must be prepared
421     * for addThread to fail by returning null, which may reflect a
422     * system or user's policy limiting the number of threads. Even
423     * though it is not treated as an error, failure to create threads
424     * may result in new tasks being rejected or existing ones
425     * remaining stuck in the queue. On the other hand, no special
426     * precautions exist to handle OutOfMemoryErrors that might be
427     * thrown while trying to create threads, since there is generally
428     * no recourse from within this class.
429 tim 1.10 */
430 dl 1.33 private volatile ThreadFactory threadFactory;
431 dl 1.2
432     /**
433     * Tracks largest attained pool size.
434 tim 1.10 */
435 dl 1.2 private int largestPoolSize;
436    
437     /**
438     * Counter for completed tasks. Updated only on termination of
439     * worker threads.
440 tim 1.10 */
441 dl 1.2 private long completedTaskCount;
442 jsr166 1.66
443 dl 1.8 /**
444 dl 1.35 * The default rejected execution handler
445 dl 1.8 */
446 tim 1.10 private static final RejectedExecutionHandler defaultHandler =
447 dl 1.2 new AbortPolicy();
448    
449 dl 1.86 // Constructors
450    
451 dl 1.2 /**
452 dl 1.86 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
453     * parameters and default thread factory and rejected execution handler.
454     * It may be more convenient to use one of the {@link Executors} factory
455     * methods instead of this general purpose constructor.
456     *
457     * @param corePoolSize the number of threads to keep in the
458     * pool, even if they are idle.
459     * @param maximumPoolSize the maximum number of threads to allow in the
460     * pool.
461     * @param keepAliveTime when the number of threads is greater than
462     * the core, this is the maximum time that excess idle threads
463     * will wait for new tasks before terminating.
464     * @param unit the time unit for the keepAliveTime
465     * argument.
466     * @param workQueue the queue to use for holding tasks before they
467     * are executed. This queue will hold only the <tt>Runnable</tt>
468     * tasks submitted by the <tt>execute</tt> method.
469 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
470 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
471     * equal to zero, or if corePoolSize greater than maximumPoolSize.
472     * @throws NullPointerException if <tt>workQueue</tt> is null
473     */
474     public ThreadPoolExecutor(int corePoolSize,
475     int maximumPoolSize,
476     long keepAliveTime,
477     TimeUnit unit,
478     BlockingQueue<Runnable> workQueue) {
479     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
480     Executors.defaultThreadFactory(), defaultHandler);
481     }
482    
483     /**
484     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
485     * parameters and default rejected execution handler.
486     *
487     * @param corePoolSize the number of threads to keep in the
488     * pool, even if they are idle.
489     * @param maximumPoolSize the maximum number of threads to allow in the
490     * pool.
491     * @param keepAliveTime when the number of threads is greater than
492     * the core, this is the maximum time that excess idle threads
493     * will wait for new tasks before terminating.
494     * @param unit the time unit for the keepAliveTime
495     * argument.
496     * @param workQueue the queue to use for holding tasks before they
497     * are executed. This queue will hold only the <tt>Runnable</tt>
498     * tasks submitted by the <tt>execute</tt> method.
499     * @param threadFactory the factory to use when the executor
500     * creates a new thread.
501 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
502 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
503     * equal to zero, or if corePoolSize greater than maximumPoolSize.
504     * @throws NullPointerException if <tt>workQueue</tt>
505     * or <tt>threadFactory</tt> are null.
506     */
507     public ThreadPoolExecutor(int corePoolSize,
508     int maximumPoolSize,
509     long keepAliveTime,
510     TimeUnit unit,
511     BlockingQueue<Runnable> workQueue,
512     ThreadFactory threadFactory) {
513     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
514     threadFactory, defaultHandler);
515     }
516    
517     /**
518     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
519     * parameters and default thread factory.
520     *
521     * @param corePoolSize the number of threads to keep in the
522     * pool, even if they are idle.
523     * @param maximumPoolSize the maximum number of threads to allow in the
524     * pool.
525     * @param keepAliveTime when the number of threads is greater than
526     * the core, this is the maximum time that excess idle threads
527     * will wait for new tasks before terminating.
528     * @param unit the time unit for the keepAliveTime
529     * argument.
530     * @param workQueue the queue to use for holding tasks before they
531     * are executed. This queue will hold only the <tt>Runnable</tt>
532     * tasks submitted by the <tt>execute</tt> method.
533     * @param handler the handler to use when execution is blocked
534     * because the thread bounds and queue capacities are reached.
535 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
536 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
537     * equal to zero, or if corePoolSize greater than maximumPoolSize.
538     * @throws NullPointerException if <tt>workQueue</tt>
539     * or <tt>handler</tt> are null.
540     */
541     public ThreadPoolExecutor(int corePoolSize,
542     int maximumPoolSize,
543     long keepAliveTime,
544     TimeUnit unit,
545     BlockingQueue<Runnable> workQueue,
546     RejectedExecutionHandler handler) {
547     this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
548     Executors.defaultThreadFactory(), handler);
549     }
550    
551     /**
552     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
553     * parameters.
554     *
555     * @param corePoolSize the number of threads to keep in the
556     * pool, even if they are idle.
557     * @param maximumPoolSize the maximum number of threads to allow in the
558     * pool.
559     * @param keepAliveTime when the number of threads is greater than
560     * the core, this is the maximum time that excess idle threads
561     * will wait for new tasks before terminating.
562     * @param unit the time unit for the keepAliveTime
563     * argument.
564     * @param workQueue the queue to use for holding tasks before they
565     * are executed. This queue will hold only the <tt>Runnable</tt>
566     * tasks submitted by the <tt>execute</tt> method.
567     * @param threadFactory the factory to use when the executor
568     * creates a new thread.
569     * @param handler the handler to use when execution is blocked
570     * because the thread bounds and queue capacities are reached.
571 jsr166 1.93 * @throws IllegalArgumentException if corePoolSize or
572 dl 1.86 * keepAliveTime less than zero, or if maximumPoolSize less than or
573     * equal to zero, or if corePoolSize greater than maximumPoolSize.
574     * @throws NullPointerException if <tt>workQueue</tt>
575     * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
576     */
577     public ThreadPoolExecutor(int corePoolSize,
578     int maximumPoolSize,
579     long keepAliveTime,
580     TimeUnit unit,
581     BlockingQueue<Runnable> workQueue,
582     ThreadFactory threadFactory,
583     RejectedExecutionHandler handler) {
584     if (corePoolSize < 0 ||
585     maximumPoolSize <= 0 ||
586     maximumPoolSize < corePoolSize ||
587     keepAliveTime < 0)
588     throw new IllegalArgumentException();
589     if (workQueue == null || threadFactory == null || handler == null)
590     throw new NullPointerException();
591     this.corePoolSize = corePoolSize;
592     this.maximumPoolSize = maximumPoolSize;
593     this.workQueue = workQueue;
594     this.keepAliveTime = unit.toNanos(keepAliveTime);
595     this.threadFactory = threadFactory;
596     this.handler = handler;
597     }
598    
599     /*
600 jsr166 1.87 * Support for execute().
601 dl 1.86 *
602     * Method execute() and its helper methods handle the various
603     * cases encountered when new tasks are submitted. The main
604     * execute() method proceeds in 3 steps:
605     *
606     * 1. If it appears that fewer than corePoolSize threads are
607     * running, try to start a new thread with the given command as
608     * its first task. The check here errs on the side of caution.
609     * The call to addIfUnderCorePoolSize rechecks runState and pool
610     * size under lock (they change only under lock) so prevents false
611     * alarms that would add threads when it shouldn't, but may also
612     * fail to add them when they should. This is compensated within
613     * the following steps.
614     *
615     * 2. If a task can be successfully queued, then we are done, but
616     * still need to compensate for missing the fact that we should
617     * have added a thread (because existing ones died) or that
618 jsr166 1.88 * shutdown occurred since entry into this method. So we recheck
619 jsr166 1.95 * state and if necessary (in ensureQueuedTaskHandled) roll back
620     * the enqueuing if shut down, or start a new thread if there are
621     * none.
622 dl 1.86 *
623     * 3. If we cannot queue task, then we try to add a new
624     * thread. There's no guesswork here (addIfUnderMaximumPoolSize)
625     * since it is performed under lock. If it fails, we know we are
626     * shut down or saturated.
627     *
628     * The reason for taking this overall approach is to normally
629     * avoid holding mainLock during this method, which would be a
630     * serious scalability bottleneck. After warmup, almost all calls
631     * take step 2 in a way that entails no locking.
632     */
633    
634     /**
635     * Executes the given task sometime in the future. The task
636     * may execute in a new thread or in an existing pooled thread.
637     *
638     * If the task cannot be submitted for execution, either because this
639     * executor has been shutdown or because its capacity has been reached,
640     * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
641     *
642     * @param command the task to execute
643     * @throws RejectedExecutionException at discretion of
644     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
645     * for execution
646     * @throws NullPointerException if command is null
647 dl 1.13 */
648 dl 1.86 public void execute(Runnable command) {
649     if (command == null)
650     throw new NullPointerException();
651     if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
652     if (runState == RUNNING && workQueue.offer(command)) {
653     if (runState != RUNNING || poolSize == 0)
654     ensureQueuedTaskHandled(command);
655     }
656     else if (!addIfUnderMaximumPoolSize(command))
657     reject(command); // is shutdown or saturated
658     }
659 dl 1.13 }
660    
661 dl 1.33 /**
662 jsr166 1.66 * Creates and returns a new thread running firstTask as its first
663 jsr166 1.87 * task. Call only while holding mainLock.
664 dl 1.86 *
665 dl 1.8 * @param firstTask the task the new thread should run first (or
666     * null if none)
667 dl 1.56 * @return the new thread, or null if threadFactory fails to create thread
668 dl 1.2 */
669     private Thread addThread(Runnable firstTask) {
670     Worker w = new Worker(firstTask);
671 dl 1.57 Thread t = threadFactory.newThread(w);
672 dl 1.56 if (t != null) {
673     w.thread = t;
674     workers.add(w);
675     int nt = ++poolSize;
676     if (nt > largestPoolSize)
677     largestPoolSize = nt;
678     }
679 dl 1.2 return t;
680     }
681 dl 1.15
682 dl 1.2 /**
683 jsr166 1.66 * Creates and starts a new thread running firstTask as its first
684 dl 1.86 * task, only if fewer than corePoolSize threads are running
685     * and the pool is not shut down.
686 dl 1.8 * @param firstTask the task the new thread should run first (or
687     * null if none)
688 jsr166 1.88 * @return true if successful
689 dl 1.2 */
690 dl 1.16 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
691 dl 1.2 Thread t = null;
692 dl 1.45 final ReentrantLock mainLock = this.mainLock;
693 dl 1.2 mainLock.lock();
694     try {
695 dl 1.85 if (poolSize < corePoolSize && runState == RUNNING)
696 dl 1.8 t = addThread(firstTask);
697 tim 1.14 } finally {
698 dl 1.2 mainLock.unlock();
699     }
700     if (t == null)
701     return false;
702     t.start();
703     return true;
704     }
705    
706     /**
707 dl 1.86 * Creates and starts a new thread running firstTask as its first
708     * task, only if fewer than maximumPoolSize threads are running
709     * and pool is not shut down.
710 dl 1.8 * @param firstTask the task the new thread should run first (or
711     * null if none)
712 jsr166 1.88 * @return true if successful
713 dl 1.2 */
714 dl 1.86 private boolean addIfUnderMaximumPoolSize(Runnable firstTask) {
715 dl 1.2 Thread t = null;
716 dl 1.45 final ReentrantLock mainLock = this.mainLock;
717 dl 1.2 mainLock.lock();
718     try {
719 dl 1.86 if (poolSize < maximumPoolSize && runState == RUNNING)
720     t = addThread(firstTask);
721 tim 1.14 } finally {
722 dl 1.2 mainLock.unlock();
723     }
724     if (t == null)
725 dl 1.86 return false;
726 dl 1.2 t.start();
727 dl 1.86 return true;
728 dl 1.16 }
729    
730 dl 1.85 /**
731 dl 1.86 * Rechecks state after queuing a task. Called from execute when
732     * pool state has been observed to change after queuing a task. If
733     * the task was queued concurrently with a call to shutdownNow,
734     * and is still present in the queue, this task must be removed
735     * and rejected to preserve shutdownNow guarantees. Otherwise,
736     * this method ensures (unless addThread fails) that there is at
737     * least one live thread to handle this task
738 dl 1.85 * @param command the task
739     */
740 dl 1.86 private void ensureQueuedTaskHandled(Runnable command) {
741 dl 1.85 final ReentrantLock mainLock = this.mainLock;
742     mainLock.lock();
743 dl 1.86 boolean reject = false;
744     Thread t = null;
745 dl 1.85 try {
746 dl 1.86 int state = runState;
747     if (state != RUNNING && workQueue.remove(command))
748     reject = true;
749     else if (state < STOP &&
750 jsr166 1.87 poolSize < Math.max(corePoolSize, 1) &&
751 dl 1.86 !workQueue.isEmpty())
752     t = addThread(null);
753 dl 1.85 } finally {
754     mainLock.unlock();
755     }
756 dl 1.86 if (reject)
757 dl 1.85 reject(command);
758 dl 1.86 else if (t != null)
759     t.start();
760 dl 1.85 }
761    
762 dl 1.16 /**
763 dl 1.86 * Invokes the rejected execution handler for the given command.
764 dl 1.16 */
765 dl 1.86 void reject(Runnable command) {
766     handler.rejectedExecution(command, this);
767 dl 1.2 }
768    
769    
770     /**
771 dl 1.86 * Worker threads.
772     *
773     * Worker threads can start out life either with an initial first
774 jsr166 1.88 * task, or without one. Normally, they are started with a first
775 dl 1.86 * task. This enables execute(), etc to bypass queuing when there
776     * are fewer than corePoolSize threads (in which case we always
777     * start one), or when the queue is full.(in which case we must
778     * bypass queue.) Initially idle threads are created either by
779     * users (prestartCoreThread and setCorePoolSize) or when methods
780     * ensureQueuedTaskHandled and tryTerminate notice that the queue
781     * is not empty but there are no active threads to handle them.
782     *
783     * After completing a task, workers try to get another one,
784 dl 1.89 * via method getTask. If they cannot (i.e., getTask returns
785     * null), they exit, calling workerDone to update pool state.
786 dl 1.86 *
787     * When starting to run a task, unless the pool is stopped, each
788     * worker thread ensures that it is not interrupted, and uses
789     * runLock to prevent the pool from interrupting it in the midst
790     * of execution. This shields user tasks from any interrupts that
791     * may otherwise be needed during shutdown (see method
792     * interruptIdleWorkers), unless the pool is stopping (via
793     * shutdownNow) in which case interrupts are let through to affect
794     * both tasks and workers. However, this shielding does not
795     * necessarily protect the workers from lagging interrupts from
796     * other user threads directed towards tasks that have already
797 jsr166 1.87 * been completed. Thus, a worker thread may be interrupted
798 dl 1.86 * needlessly (for example in getTask), in which case it rechecks
799 dl 1.89 * pool state to see if it should exit.
800 dl 1.2 */
801 dl 1.85 private final class Worker implements Runnable {
802 dl 1.2 /**
803     * The runLock is acquired and released surrounding each task
804     * execution. It mainly protects against interrupts that are
805     * intended to cancel the worker thread from instead
806     * interrupting the task being run.
807     */
808     private final ReentrantLock runLock = new ReentrantLock();
809    
810     /**
811 dl 1.86 * Initial task to run before entering run loop. Possibly null.
812 dl 1.2 */
813     private Runnable firstTask;
814    
815     /**
816     * Per thread completed task counter; accumulated
817     * into completedTaskCount upon termination.
818     */
819     volatile long completedTasks;
820    
821     /**
822     * Thread this worker is running in. Acts as a final field,
823     * but cannot be set until thread is created.
824     */
825     Thread thread;
826    
827     Worker(Runnable firstTask) {
828     this.firstTask = firstTask;
829     }
830    
831     boolean isActive() {
832     return runLock.isLocked();
833     }
834    
835     /**
836 jsr166 1.73 * Interrupts thread if not running a task.
837 tim 1.10 */
838 dl 1.2 void interruptIfIdle() {
839 dl 1.45 final ReentrantLock runLock = this.runLock;
840 dl 1.2 if (runLock.tryLock()) {
841     try {
842     thread.interrupt();
843 tim 1.14 } finally {
844 dl 1.2 runLock.unlock();
845     }
846     }
847     }
848    
849     /**
850 jsr166 1.73 * Interrupts thread even if running a task.
851 tim 1.10 */
852 dl 1.2 void interruptNow() {
853     thread.interrupt();
854     }
855    
856     /**
857 jsr166 1.73 * Runs a single task between before/after methods.
858 dl 1.2 */
859     private void runTask(Runnable task) {
860 dl 1.45 final ReentrantLock runLock = this.runLock;
861 dl 1.2 runLock.lock();
862     try {
863 dl 1.86 /*
864     * Ensure that unless pool is stopping, this thread
865     * does not have its interrupt set. This requires a
866     * double-check of state in case the interrupt was
867     * cleared concurrently with a shutdownNow -- if so,
868     * the interrupt is re-enabled.
869     */
870 jsr166 1.87 if (runState < STOP &&
871     Thread.interrupted() &&
872     runState >= STOP)
873 dl 1.81 thread.interrupt();
874 dl 1.97
875 dl 1.2 beforeExecute(thread, task);
876 dl 1.97 Throwable ex = null;
877 dl 1.2 try {
878     task.run();
879 dl 1.97 } catch (Throwable throwable) {
880     ex = throwable;
881     } finally {
882 dl 1.2 ++completedTasks;
883 dl 1.97 afterExecute(task, ex);
884 dl 1.2 }
885 tim 1.14 } finally {
886 dl 1.2 runLock.unlock();
887     }
888     }
889    
890     /**
891     * Main run loop
892     */
893     public void run() {
894     try {
895 dl 1.50 Runnable task = firstTask;
896     firstTask = null;
897     while (task != null || (task = getTask()) != null) {
898 dl 1.2 runTask(task);
899 dl 1.85 task = null;
900 dl 1.2 }
901 tim 1.14 } finally {
902 dl 1.2 workerDone(this);
903     }
904     }
905     }
906 tim 1.1
907 dl 1.86 /* Utilities for worker thread control */
908 dl 1.17
909 tim 1.1 /**
910 dl 1.86 * Gets the next task for a worker thread to run. The general
911     * approach is similar to execute() in that worker threads trying
912     * to get a task to run do so on the basis of prevailing state
913     * accessed outside of locks. This may cause them to choose the
914 jsr166 1.96 * "wrong" action, such as trying to exit because no tasks
915 dl 1.89 * appear to be available, or entering a take when the pool is in
916 jsr166 1.96 * the process of being shut down. These potential problems are
917 dl 1.86 * countered by (1) rechecking pool state (in workerCanExit)
918     * before giving up, and (2) interrupting other workers upon
919     * shutdown, so they can recheck state. All other user-based state
920     * changes (to allowCoreThreadTimeOut etc) are OK even when
921 jsr166 1.88 * performed asynchronously wrt getTask.
922 tim 1.1 *
923 dl 1.86 * @return the task
924 tim 1.1 */
925 dl 1.86 Runnable getTask() {
926     for (;;) {
927     try {
928     int state = runState;
929     if (state > SHUTDOWN)
930     return null;
931     Runnable r;
932     if (state == SHUTDOWN) // Help drain queue
933     r = workQueue.poll();
934     else if (poolSize > corePoolSize || allowCoreThreadTimeOut)
935     r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
936     else
937     r = workQueue.take();
938     if (r != null)
939     return r;
940     if (workerCanExit()) {
941     if (runState >= SHUTDOWN) // Wake up others
942     interruptIdleWorkers();
943     return null;
944     }
945     // Else retry
946     } catch (InterruptedException ie) {
947 jsr166 1.88 // On interruption, re-check runState
948 dl 1.86 }
949     }
950 dl 1.2 }
951 tim 1.1
952 dl 1.2 /**
953 dl 1.86 * Check whether a worker thread that fails to get a task can
954     * exit. We allow a worker thread to die if the pool is stopping,
955     * or the queue is empty, or there is at least one thread to
956     * handle possibly non-empty queue, even if core timeouts are
957     * allowed.
958 dl 1.2 */
959 dl 1.86 private boolean workerCanExit() {
960     final ReentrantLock mainLock = this.mainLock;
961     mainLock.lock();
962     boolean canExit;
963     try {
964 jsr166 1.87 canExit = runState >= STOP ||
965     workQueue.isEmpty() ||
966     (allowCoreThreadTimeOut &&
967 dl 1.86 poolSize > Math.max(1, corePoolSize));
968     } finally {
969     mainLock.unlock();
970     }
971     return canExit;
972 dl 1.2 }
973 tim 1.1
974 dl 1.2 /**
975 dl 1.86 * Wakes up all threads that might be waiting for tasks so they
976     * can check for termination. Note: this method is also called by
977     * ScheduledThreadPoolExecutor.
978 dl 1.2 */
979 dl 1.86 void interruptIdleWorkers() {
980     final ReentrantLock mainLock = this.mainLock;
981     mainLock.lock();
982     try {
983     for (Worker w : workers)
984     w.interruptIfIdle();
985     } finally {
986     mainLock.unlock();
987     }
988 dl 1.2 }
989 tim 1.1
990 dl 1.2 /**
991 dl 1.86 * Performs bookkeeping for an exiting worker thread.
992     * @param w the worker
993 dl 1.2 */
994 dl 1.86 void workerDone(Worker w) {
995     final ReentrantLock mainLock = this.mainLock;
996     mainLock.lock();
997     try {
998     completedTaskCount += w.completedTasks;
999     workers.remove(w);
1000 dl 1.97 --poolSize;
1001     tryTerminate();
1002 dl 1.86 } finally {
1003     mainLock.unlock();
1004     }
1005 tim 1.1 }
1006    
1007 dl 1.86 /* Termination support. */
1008    
1009 dl 1.2 /**
1010 dl 1.86 * Transitions to TERMINATED state if either (SHUTDOWN and pool
1011 jsr166 1.88 * and queue empty) or (STOP and pool empty), otherwise unless
1012 dl 1.97 * stopped, adding a thread if there are fewer than max(1,
1013     * corePoolSize) existing threads to handle queued tasks.
1014 dl 1.2 *
1015 dl 1.86 * This method is called from the three places in which
1016     * termination can occur: in workerDone on exit of the last thread
1017     * after pool has been shut down, or directly within calls to
1018 dl 1.90 * shutdown or shutdownNow, if there are no live threads.
1019 dl 1.2 */
1020 dl 1.86 private void tryTerminate() {
1021 dl 1.97 int n = poolSize;
1022     if (n < Math.max(1, corePoolSize)) {
1023 dl 1.86 int state = runState;
1024     if (state < STOP && !workQueue.isEmpty()) {
1025     Thread t = addThread(null);
1026     if (t != null)
1027     t.start();
1028 dl 1.97 return;
1029 dl 1.86 }
1030 dl 1.97 if (n == 0 && (state == STOP || state == SHUTDOWN)) {
1031 dl 1.86 runState = TERMINATED;
1032     termination.signalAll();
1033     terminated();
1034     }
1035 dl 1.2 }
1036 tim 1.1 }
1037 dl 1.4
1038 dl 1.53 /**
1039     * Initiates an orderly shutdown in which previously submitted
1040     * tasks are executed, but no new tasks will be
1041     * accepted. Invocation has no additional effect if already shut
1042     * down.
1043     * @throws SecurityException if a security manager exists and
1044     * shutting down this ExecutorService may manipulate threads that
1045     * the caller is not permitted to modify because it does not hold
1046     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1047 jsr166 1.68 * or the security manager's <tt>checkAccess</tt> method denies access.
1048 dl 1.53 */
1049 dl 1.2 public void shutdown() {
1050 dl 1.86 /*
1051     * Conceptually, shutdown is just a matter of changing the
1052 jsr166 1.88 * runState to SHUTDOWN, and then interrupting any worker
1053 dl 1.86 * threads that might be blocked in getTask() to wake them up
1054     * so they can exit. Then, if there happen not to be any
1055     * threads or tasks, we can directly terminate pool via
1056 jsr166 1.96 * tryTerminate. Else, the last worker to leave the building
1057     * turns off the lights (in workerDone).
1058 dl 1.86 *
1059     * But this is made more delicate because we must cooperate
1060     * with the security manager (if present), which may implement
1061     * policies that make more sense for operations on Threads
1062     * than they do for ThreadPools. This requires 3 steps:
1063     *
1064     * 1. Making sure caller has permission to shut down threads
1065     * in general (see shutdownPerm).
1066     *
1067     * 2. If (1) passes, making sure the caller is allowed to
1068     * modify each of our threads. This might not be true even if
1069     * first check passed, if the SecurityManager treats some
1070     * threads specially. If this check passes, then we can try
1071     * to set runState.
1072     *
1073     * 3. If both (1) and (2) pass, dealing with inconsistent
1074     * security managers that allow checkAccess but then throw a
1075     * SecurityException when interrupt() is invoked. In this
1076     * third case, because we have already set runState, we can
1077 jsr166 1.95 * only try to back out from the shutdown as cleanly as
1078 jsr166 1.96 * possible. Some workers may have been killed but we remain
1079     * in non-shutdown state (which may entail tryTerminate from
1080     * workerDone starting a new worker to maintain liveness.)
1081 dl 1.86 */
1082    
1083 dl 1.42 SecurityManager security = System.getSecurityManager();
1084 jsr166 1.66 if (security != null)
1085 dl 1.78 security.checkPermission(shutdownPerm);
1086 dl 1.42
1087 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1088 dl 1.2 mainLock.lock();
1089     try {
1090 dl 1.86 if (security != null) { // Check if caller can modify our threads
1091 jsr166 1.96 for (Worker w : workers)
1092 dl 1.85 security.checkAccess(w.thread);
1093     }
1094 dl 1.43
1095 dl 1.85 int state = runState;
1096 dl 1.86 if (state < SHUTDOWN)
1097 dl 1.85 runState = SHUTDOWN;
1098 dl 1.43
1099 dl 1.85 try {
1100 jsr166 1.96 for (Worker w : workers) {
1101 dl 1.85 w.interruptIfIdle();
1102 dl 1.43 }
1103 dl 1.86 } catch (SecurityException se) { // Try to back out
1104 dl 1.85 runState = state;
1105 jsr166 1.96 // tryTerminate() here would be a no-op
1106 dl 1.85 throw se;
1107 dl 1.25 }
1108 dl 1.85
1109 dl 1.86 tryTerminate(); // Terminate now if pool and queue empty
1110 tim 1.14 } finally {
1111 dl 1.2 mainLock.unlock();
1112     }
1113 tim 1.1 }
1114    
1115 dl 1.53 /**
1116     * Attempts to stop all actively executing tasks, halts the
1117 jsr166 1.75 * processing of waiting tasks, and returns a list of the tasks
1118 dl 1.85 * that were awaiting execution. These tasks are drained (removed)
1119     * from the task queue upon return from this method.
1120 jsr166 1.66 *
1121 jsr166 1.75 * <p>There are no guarantees beyond best-effort attempts to stop
1122     * processing actively executing tasks. This implementation
1123     * cancels tasks via {@link Thread#interrupt}, so any task that
1124     * fails to respond to interrupts may never terminate.
1125 dl 1.53 *
1126     * @return list of tasks that never commenced execution
1127     * @throws SecurityException if a security manager exists and
1128     * shutting down this ExecutorService may manipulate threads that
1129     * the caller is not permitted to modify because it does not hold
1130     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1131     * or the security manager's <tt>checkAccess</tt> method denies access.
1132     */
1133 tim 1.39 public List<Runnable> shutdownNow() {
1134 dl 1.86 /*
1135     * shutdownNow differs from shutdown only in that
1136 jsr166 1.96 * 1. runState is set to STOP,
1137     * 2. all worker threads are interrupted, not just the idle ones, and
1138     * 3. the queue is drained and returned.
1139 dl 1.86 */
1140 dl 1.42 SecurityManager security = System.getSecurityManager();
1141 jsr166 1.66 if (security != null)
1142 dl 1.78 security.checkPermission(shutdownPerm);
1143 dl 1.43
1144 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1145 dl 1.2 mainLock.lock();
1146     try {
1147 dl 1.86 if (security != null) { // Check if caller can modify our threads
1148 jsr166 1.96 for (Worker w : workers)
1149 dl 1.85 security.checkAccess(w.thread);
1150     }
1151 dl 1.43
1152 dl 1.85 int state = runState;
1153 dl 1.86 if (state < STOP)
1154 dl 1.85 runState = STOP;
1155 dl 1.86
1156 dl 1.85 try {
1157     for (Worker w : workers) {
1158     w.interruptNow();
1159 dl 1.43 }
1160 dl 1.86 } catch (SecurityException se) { // Try to back out
1161 jsr166 1.87 runState = state;
1162 jsr166 1.96 // tryTerminate() here would be a no-op
1163 dl 1.85 throw se;
1164 dl 1.25 }
1165 dl 1.85
1166 dl 1.86 List<Runnable> tasks = drainQueue();
1167     tryTerminate(); // Terminate now if pool and queue empty
1168     return tasks;
1169 tim 1.14 } finally {
1170 dl 1.2 mainLock.unlock();
1171     }
1172 tim 1.1 }
1173    
1174 dl 1.86 /**
1175     * Drains the task queue into a new list. Used by shutdownNow.
1176     * Call only while holding main lock.
1177     */
1178 jsr166 1.96 private List<Runnable> drainQueue() {
1179 dl 1.86 List<Runnable> taskList = new ArrayList<Runnable>();
1180     workQueue.drainTo(taskList);
1181     /*
1182     * If the queue is a DelayQueue or any other kind of queue
1183     * for which poll or drainTo may fail to remove some elements,
1184     * we need to manually traverse and remove remaining tasks.
1185     * To guarantee atomicity wrt other threads using this queue,
1186     * we need to create a new iterator for each element removed.
1187     */
1188     while (!workQueue.isEmpty()) {
1189     Iterator<Runnable> it = workQueue.iterator();
1190     try {
1191     if (it.hasNext()) {
1192     Runnable r = it.next();
1193     if (workQueue.remove(r))
1194     taskList.add(r);
1195     }
1196 jsr166 1.92 } catch (ConcurrentModificationException ignore) {
1197 dl 1.86 }
1198     }
1199     return taskList;
1200     }
1201    
1202 dl 1.2 public boolean isShutdown() {
1203 dl 1.16 return runState != RUNNING;
1204     }
1205    
1206 jsr166 1.66 /**
1207 dl 1.55 * Returns true if this executor is in the process of terminating
1208 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1209     * completely terminated. This method may be useful for
1210     * debugging. A return of <tt>true</tt> reported a sufficient
1211     * period after shutdown may indicate that submitted tasks have
1212     * ignored or suppressed interruption, causing this executor not
1213     * to properly terminate.
1214 jsr166 1.93 * @return true if terminating but not yet terminated
1215 dl 1.16 */
1216     public boolean isTerminating() {
1217 dl 1.94 int state = runState;
1218     return state == SHUTDOWN || state == STOP;
1219 tim 1.1 }
1220    
1221 dl 1.2 public boolean isTerminated() {
1222 dl 1.16 return runState == TERMINATED;
1223 dl 1.2 }
1224 tim 1.1
1225 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1226     throws InterruptedException {
1227 dl 1.50 long nanos = unit.toNanos(timeout);
1228 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1229 dl 1.2 mainLock.lock();
1230     try {
1231 dl 1.25 for (;;) {
1232 jsr166 1.66 if (runState == TERMINATED)
1233 dl 1.25 return true;
1234     if (nanos <= 0)
1235     return false;
1236     nanos = termination.awaitNanos(nanos);
1237     }
1238 tim 1.14 } finally {
1239 dl 1.2 mainLock.unlock();
1240     }
1241 dl 1.15 }
1242    
1243     /**
1244     * Invokes <tt>shutdown</tt> when this executor is no longer
1245     * referenced.
1246 jsr166 1.66 */
1247 dl 1.15 protected void finalize() {
1248     shutdown();
1249 dl 1.2 }
1250 tim 1.10
1251 dl 1.86 /* Getting and setting tunable parameters */
1252    
1253 dl 1.2 /**
1254     * Sets the thread factory used to create new threads.
1255     *
1256     * @param threadFactory the new thread factory
1257 dl 1.30 * @throws NullPointerException if threadFactory is null
1258 tim 1.11 * @see #getThreadFactory
1259 dl 1.2 */
1260     public void setThreadFactory(ThreadFactory threadFactory) {
1261 dl 1.30 if (threadFactory == null)
1262     throw new NullPointerException();
1263 dl 1.2 this.threadFactory = threadFactory;
1264 tim 1.1 }
1265    
1266 dl 1.2 /**
1267     * Returns the thread factory used to create new threads.
1268     *
1269     * @return the current thread factory
1270 tim 1.11 * @see #setThreadFactory
1271 dl 1.2 */
1272     public ThreadFactory getThreadFactory() {
1273     return threadFactory;
1274 tim 1.1 }
1275    
1276 dl 1.2 /**
1277     * Sets a new handler for unexecutable tasks.
1278     *
1279     * @param handler the new handler
1280 dl 1.31 * @throws NullPointerException if handler is null
1281 tim 1.11 * @see #getRejectedExecutionHandler
1282 dl 1.2 */
1283     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1284 dl 1.31 if (handler == null)
1285     throw new NullPointerException();
1286 dl 1.2 this.handler = handler;
1287     }
1288 tim 1.1
1289 dl 1.2 /**
1290     * Returns the current handler for unexecutable tasks.
1291     *
1292     * @return the current handler
1293 tim 1.11 * @see #setRejectedExecutionHandler
1294 dl 1.2 */
1295     public RejectedExecutionHandler getRejectedExecutionHandler() {
1296     return handler;
1297 tim 1.1 }
1298    
1299 dl 1.2 /**
1300     * Sets the core number of threads. This overrides any value set
1301     * in the constructor. If the new value is smaller than the
1302     * current value, excess existing threads will be terminated when
1303 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1304     * be started to execute any queued tasks.
1305 tim 1.1 *
1306 dl 1.2 * @param corePoolSize the new core size
1307 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1308 dl 1.8 * less than zero
1309 tim 1.11 * @see #getCorePoolSize
1310 tim 1.1 */
1311 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1312     if (corePoolSize < 0)
1313     throw new IllegalArgumentException();
1314 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1315 dl 1.2 mainLock.lock();
1316     try {
1317     int extra = this.corePoolSize - corePoolSize;
1318     this.corePoolSize = corePoolSize;
1319 tim 1.38 if (extra < 0) {
1320 dl 1.86 int n = workQueue.size(); // don't add more threads than tasks
1321     while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize) {
1322 dl 1.56 Thread t = addThread(null);
1323 jsr166 1.66 if (t != null)
1324 dl 1.56 t.start();
1325     else
1326     break;
1327     }
1328 tim 1.38 }
1329     else if (extra > 0 && poolSize > corePoolSize) {
1330 dl 1.86 try {
1331     Iterator<Worker> it = workers.iterator();
1332     while (it.hasNext() &&
1333     extra-- > 0 &&
1334     poolSize > corePoolSize &&
1335     workQueue.remainingCapacity() == 0)
1336     it.next().interruptIfIdle();
1337 jsr166 1.92 } catch (SecurityException ignore) {
1338 dl 1.89 // Not an error; it is OK if the threads stay live
1339 dl 1.86 }
1340 dl 1.2 }
1341 tim 1.14 } finally {
1342 dl 1.2 mainLock.unlock();
1343     }
1344     }
1345 tim 1.1
1346     /**
1347 dl 1.2 * Returns the core number of threads.
1348 tim 1.1 *
1349 dl 1.2 * @return the core number of threads
1350 tim 1.11 * @see #setCorePoolSize
1351 tim 1.1 */
1352 tim 1.10 public int getCorePoolSize() {
1353 dl 1.2 return corePoolSize;
1354 dl 1.16 }
1355    
1356     /**
1357 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1358 dl 1.16 * overrides the default policy of starting core threads only when
1359     * new tasks are executed. This method will return <tt>false</tt>
1360     * if all core threads have already been started.
1361     * @return true if a thread was started
1362 jsr166 1.66 */
1363 dl 1.16 public boolean prestartCoreThread() {
1364     return addIfUnderCorePoolSize(null);
1365     }
1366    
1367     /**
1368 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1369 dl 1.16 * overrides the default policy of starting core threads only when
1370 jsr166 1.66 * new tasks are executed.
1371 jsr166 1.88 * @return the number of threads started
1372 jsr166 1.66 */
1373 dl 1.16 public int prestartAllCoreThreads() {
1374     int n = 0;
1375     while (addIfUnderCorePoolSize(null))
1376     ++n;
1377     return n;
1378 dl 1.2 }
1379 tim 1.1
1380     /**
1381 dl 1.62 * Returns true if this pool allows core threads to time out and
1382     * terminate if no tasks arrive within the keepAlive time, being
1383     * replaced if needed when new tasks arrive. When true, the same
1384     * keep-alive policy applying to non-core threads applies also to
1385     * core threads. When false (the default), core threads are never
1386     * terminated due to lack of incoming tasks.
1387     * @return <tt>true</tt> if core threads are allowed to time out,
1388     * else <tt>false</tt>
1389 jsr166 1.72 *
1390     * @since 1.6
1391 dl 1.62 */
1392     public boolean allowsCoreThreadTimeOut() {
1393     return allowCoreThreadTimeOut;
1394     }
1395    
1396     /**
1397     * Sets the policy governing whether core threads may time out and
1398     * terminate if no tasks arrive within the keep-alive time, being
1399     * replaced if needed when new tasks arrive. When false, core
1400     * threads are never terminated due to lack of incoming
1401     * tasks. When true, the same keep-alive policy applying to
1402     * non-core threads applies also to core threads. To avoid
1403     * continual thread replacement, the keep-alive time must be
1404 dl 1.64 * greater than zero when setting <tt>true</tt>. This method
1405     * should in general be called before the pool is actively used.
1406 dl 1.62 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1407 dl 1.64 * @throws IllegalArgumentException if value is <tt>true</tt>
1408     * and the current keep-alive time is not greater than zero.
1409 jsr166 1.72 *
1410     * @since 1.6
1411 dl 1.62 */
1412     public void allowCoreThreadTimeOut(boolean value) {
1413 dl 1.64 if (value && keepAliveTime <= 0)
1414     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1415    
1416 dl 1.62 allowCoreThreadTimeOut = value;
1417     }
1418    
1419     /**
1420 tim 1.1 * Sets the maximum allowed number of threads. This overrides any
1421 dl 1.2 * value set in the constructor. If the new value is smaller than
1422     * the current value, excess existing threads will be
1423     * terminated when they next become idle.
1424 tim 1.1 *
1425 dl 1.2 * @param maximumPoolSize the new maximum
1426 jsr166 1.84 * @throws IllegalArgumentException if the new maximum is
1427     * less than or equal to zero, or
1428     * less than the {@linkplain #getCorePoolSize core pool size}
1429 tim 1.11 * @see #getMaximumPoolSize
1430 dl 1.2 */
1431     public void setMaximumPoolSize(int maximumPoolSize) {
1432     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1433     throw new IllegalArgumentException();
1434 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1435 dl 1.2 mainLock.lock();
1436     try {
1437     int extra = this.maximumPoolSize - maximumPoolSize;
1438     this.maximumPoolSize = maximumPoolSize;
1439     if (extra > 0 && poolSize > maximumPoolSize) {
1440 dl 1.86 try {
1441     Iterator<Worker> it = workers.iterator();
1442     while (it.hasNext() &&
1443     extra > 0 &&
1444     poolSize > maximumPoolSize) {
1445     it.next().interruptIfIdle();
1446     --extra;
1447     }
1448 jsr166 1.92 } catch (SecurityException ignore) {
1449 dl 1.89 // Not an error; it is OK if the threads stay live
1450 dl 1.2 }
1451     }
1452 tim 1.14 } finally {
1453 dl 1.2 mainLock.unlock();
1454     }
1455     }
1456 tim 1.1
1457     /**
1458     * Returns the maximum allowed number of threads.
1459     *
1460 dl 1.2 * @return the maximum allowed number of threads
1461 tim 1.11 * @see #setMaximumPoolSize
1462 tim 1.1 */
1463 tim 1.10 public int getMaximumPoolSize() {
1464 dl 1.2 return maximumPoolSize;
1465     }
1466 tim 1.1
1467     /**
1468     * Sets the time limit for which threads may remain idle before
1469 dl 1.2 * being terminated. If there are more than the core number of
1470 tim 1.1 * threads currently in the pool, after waiting this amount of
1471     * time without processing a task, excess threads will be
1472     * terminated. This overrides any value set in the constructor.
1473     * @param time the time to wait. A time value of zero will cause
1474     * excess threads to terminate immediately after executing tasks.
1475 jsr166 1.96 * @param unit the time unit of the time argument
1476 dl 1.64 * @throws IllegalArgumentException if time less than zero or
1477     * if time is zero and allowsCoreThreadTimeOut
1478 tim 1.11 * @see #getKeepAliveTime
1479 tim 1.1 */
1480 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1481     if (time < 0)
1482     throw new IllegalArgumentException();
1483 dl 1.64 if (time == 0 && allowsCoreThreadTimeOut())
1484     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1485 dl 1.2 this.keepAliveTime = unit.toNanos(time);
1486     }
1487 tim 1.1
1488     /**
1489     * Returns the thread keep-alive time, which is the amount of time
1490 jsr166 1.93 * that threads in excess of the core pool size may remain
1491 tim 1.10 * idle before being terminated.
1492 tim 1.1 *
1493 dl 1.2 * @param unit the desired time unit of the result
1494 tim 1.1 * @return the time limit
1495 tim 1.11 * @see #setKeepAliveTime
1496 tim 1.1 */
1497 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1498 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1499     }
1500 tim 1.1
1501 dl 1.86 /* User-level queue utilities */
1502    
1503     /**
1504     * Returns the task queue used by this executor. Access to the
1505     * task queue is intended primarily for debugging and monitoring.
1506     * This queue may be in active use. Retrieving the task queue
1507     * does not prevent queued tasks from executing.
1508     *
1509     * @return the task queue
1510     */
1511     public BlockingQueue<Runnable> getQueue() {
1512     return workQueue;
1513     }
1514    
1515     /**
1516     * Removes this task from the executor's internal queue if it is
1517     * present, thus causing it not to be run if it has not already
1518     * started.
1519     *
1520     * <p> This method may be useful as one part of a cancellation
1521     * scheme. It may fail to remove tasks that have been converted
1522     * into other forms before being placed on the internal queue. For
1523     * example, a task entered using <tt>submit</tt> might be
1524     * converted into a form that maintains <tt>Future</tt> status.
1525     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1526     * may be used to remove those Futures that have been cancelled.
1527     *
1528     * @param task the task to remove
1529     * @return true if the task was removed
1530     */
1531     public boolean remove(Runnable task) {
1532     return getQueue().remove(task);
1533     }
1534    
1535     /**
1536     * Tries to remove from the work queue all {@link Future}
1537     * tasks that have been cancelled. This method can be useful as a
1538     * storage reclamation operation, that has no other impact on
1539     * functionality. Cancelled tasks are never executed, but may
1540     * accumulate in work queues until worker threads can actively
1541     * remove them. Invoking this method instead tries to remove them now.
1542     * However, this method may fail to remove tasks in
1543     * the presence of interference by other threads.
1544     */
1545     public void purge() {
1546     // Fail if we encounter interference during traversal
1547     try {
1548     Iterator<Runnable> it = getQueue().iterator();
1549     while (it.hasNext()) {
1550     Runnable r = it.next();
1551     if (r instanceof Future<?>) {
1552     Future<?> c = (Future<?>)r;
1553     if (c.isCancelled())
1554     it.remove();
1555     }
1556     }
1557     }
1558     catch (ConcurrentModificationException ex) {
1559     return;
1560     }
1561     }
1562    
1563 tim 1.1 /* Statistics */
1564    
1565     /**
1566     * Returns the current number of threads in the pool.
1567     *
1568     * @return the number of threads
1569     */
1570 tim 1.10 public int getPoolSize() {
1571 dl 1.2 return poolSize;
1572     }
1573 tim 1.1
1574     /**
1575 dl 1.2 * Returns the approximate number of threads that are actively
1576 tim 1.1 * executing tasks.
1577     *
1578     * @return the number of threads
1579     */
1580 tim 1.10 public int getActiveCount() {
1581 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1582 dl 1.2 mainLock.lock();
1583     try {
1584     int n = 0;
1585 tim 1.39 for (Worker w : workers) {
1586     if (w.isActive())
1587 dl 1.2 ++n;
1588     }
1589     return n;
1590 tim 1.14 } finally {
1591 dl 1.2 mainLock.unlock();
1592     }
1593     }
1594 tim 1.1
1595     /**
1596 dl 1.2 * Returns the largest number of threads that have ever
1597     * simultaneously been in the pool.
1598 tim 1.1 *
1599     * @return the number of threads
1600     */
1601 tim 1.10 public int getLargestPoolSize() {
1602 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1603 dl 1.2 mainLock.lock();
1604     try {
1605     return largestPoolSize;
1606 tim 1.14 } finally {
1607 dl 1.2 mainLock.unlock();
1608     }
1609     }
1610 tim 1.1
1611     /**
1612 dl 1.85 * Returns the approximate total number of tasks that have ever been
1613 dl 1.2 * scheduled for execution. Because the states of tasks and
1614     * threads may change dynamically during computation, the returned
1615 dl 1.97 * value is only an approximation.
1616 tim 1.1 *
1617     * @return the number of tasks
1618     */
1619 tim 1.10 public long getTaskCount() {
1620 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1621 dl 1.2 mainLock.lock();
1622     try {
1623     long n = completedTaskCount;
1624 tim 1.39 for (Worker w : workers) {
1625 dl 1.2 n += w.completedTasks;
1626     if (w.isActive())
1627     ++n;
1628     }
1629     return n + workQueue.size();
1630 tim 1.14 } finally {
1631 dl 1.2 mainLock.unlock();
1632     }
1633     }
1634 tim 1.1
1635     /**
1636 dl 1.2 * Returns the approximate total number of tasks that have
1637     * completed execution. Because the states of tasks and threads
1638     * may change dynamically during computation, the returned value
1639 dl 1.17 * is only an approximation, but one that does not ever decrease
1640     * across successive calls.
1641 tim 1.1 *
1642     * @return the number of tasks
1643     */
1644 tim 1.10 public long getCompletedTaskCount() {
1645 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1646 dl 1.2 mainLock.lock();
1647     try {
1648     long n = completedTaskCount;
1649 tim 1.39 for (Worker w : workers)
1650     n += w.completedTasks;
1651 dl 1.2 return n;
1652 tim 1.14 } finally {
1653 dl 1.2 mainLock.unlock();
1654     }
1655     }
1656 tim 1.1
1657 dl 1.86 /* Extension hooks */
1658    
1659 tim 1.1 /**
1660 dl 1.17 * Method invoked prior to executing the given Runnable in the
1661 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1662     * will execute task <tt>r</tt>, and may be used to re-initialize
1663 jsr166 1.73 * ThreadLocals, or to perform logging.
1664     *
1665     * <p>This implementation does nothing, but may be customized in
1666     * subclasses. Note: To properly nest multiple overridings, subclasses
1667     * should generally invoke <tt>super.beforeExecute</tt> at the end of
1668     * this method.
1669 tim 1.1 *
1670 dl 1.2 * @param t the thread that will run task r.
1671     * @param r the task that will be executed.
1672 tim 1.1 */
1673 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1674 tim 1.1
1675     /**
1676 jsr166 1.70 * Method invoked upon completion of execution of the given Runnable.
1677     * This method is invoked by the thread that executed the task. If
1678     * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1679     * or <tt>Error</tt> that caused execution to terminate abruptly.
1680 dl 1.69 *
1681     * <p><b>Note:</b> When actions are enclosed in tasks (such as
1682     * {@link FutureTask}) either explicitly or via methods such as
1683     * <tt>submit</tt>, these task objects catch and maintain
1684     * computational exceptions, and so they do not cause abrupt
1685 jsr166 1.70 * termination, and the internal exceptions are <em>not</em>
1686 dl 1.69 * passed to this method.
1687     *
1688 jsr166 1.70 * <p>This implementation does nothing, but may be customized in
1689     * subclasses. Note: To properly nest multiple overridings, subclasses
1690     * should generally invoke <tt>super.afterExecute</tt> at the
1691     * beginning of this method.
1692 tim 1.1 *
1693 dl 1.2 * @param r the runnable that has completed.
1694 dl 1.24 * @param t the exception that caused termination, or null if
1695 dl 1.2 * execution completed normally.
1696 tim 1.1 */
1697 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1698 tim 1.1
1699 dl 1.2 /**
1700     * Method invoked when the Executor has terminated. Default
1701 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1702     * overridings, subclasses should generally invoke
1703     * <tt>super.terminated</tt> within this method.
1704 dl 1.2 */
1705     protected void terminated() { }
1706 tim 1.1
1707 dl 1.86 /* Predefined RejectedExecutionHandlers */
1708    
1709 tim 1.1 /**
1710 dl 1.21 * A handler for rejected tasks that runs the rejected task
1711     * directly in the calling thread of the <tt>execute</tt> method,
1712     * unless the executor has been shut down, in which case the task
1713     * is discarded.
1714 tim 1.1 */
1715 jsr166 1.71 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1716 tim 1.1 /**
1717 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1718 tim 1.1 */
1719     public CallerRunsPolicy() { }
1720    
1721 dl 1.24 /**
1722     * Executes task r in the caller's thread, unless the executor
1723     * has been shut down, in which case the task is discarded.
1724     * @param r the runnable task requested to be executed
1725     * @param e the executor attempting to execute this task
1726     */
1727 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1728     if (!e.isShutdown()) {
1729 tim 1.1 r.run();
1730     }
1731     }
1732     }
1733    
1734     /**
1735 dl 1.21 * A handler for rejected tasks that throws a
1736 dl 1.8 * <tt>RejectedExecutionException</tt>.
1737 tim 1.1 */
1738 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1739 tim 1.1 /**
1740 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1741 tim 1.1 */
1742     public AbortPolicy() { }
1743    
1744 dl 1.24 /**
1745 dl 1.54 * Always throws RejectedExecutionException.
1746 dl 1.24 * @param r the runnable task requested to be executed
1747     * @param e the executor attempting to execute this task
1748     * @throws RejectedExecutionException always.
1749     */
1750 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1751     throw new RejectedExecutionException();
1752 tim 1.1 }
1753     }
1754    
1755     /**
1756 dl 1.21 * A handler for rejected tasks that silently discards the
1757     * rejected task.
1758 tim 1.1 */
1759 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1760 tim 1.1 /**
1761 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1762 tim 1.1 */
1763     public DiscardPolicy() { }
1764    
1765 dl 1.24 /**
1766     * Does nothing, which has the effect of discarding task r.
1767     * @param r the runnable task requested to be executed
1768     * @param e the executor attempting to execute this task
1769     */
1770 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1771 tim 1.1 }
1772     }
1773    
1774     /**
1775 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1776     * request and then retries <tt>execute</tt>, unless the executor
1777     * is shut down, in which case the task is discarded.
1778 tim 1.1 */
1779 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1780 tim 1.1 /**
1781 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1782 tim 1.1 */
1783     public DiscardOldestPolicy() { }
1784    
1785 dl 1.24 /**
1786     * Obtains and ignores the next task that the executor
1787     * would otherwise execute, if one is immediately available,
1788     * and then retries execution of task r, unless the executor
1789     * is shut down, in which case task r is instead 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     e.getQueue().poll();
1796     e.execute(r);
1797 tim 1.1 }
1798     }
1799     }
1800     }