ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.30
Committed: Sun Oct 5 23:00:18 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.29: +3 -0 lines
Log Message:
added drainTo; clarified various exception specs

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     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
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 dl 1.21 * pool size
42     * (see {@link ThreadPoolExecutor#getPoolSize})
43     * according to the bounds set by corePoolSize
44     * (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     * ThreadPoolExecutor#setMaximumPoolSize}. <dd>
62 dl 1.2 *
63 dl 1.21 * <dt> On-demand construction
64 dl 1.2 *
65 dl 1.21 * <dd> By default, even core threads are initially created and
66     * started only when needed by new tasks, but this can be overridden
67     * dynamically using method {@link
68     * ThreadPoolExecutor#prestartCoreThread} or
69     * {@link ThreadPoolExecutor#prestartAllCoreThreads}. </dd>
70 dl 1.2 *
71 tim 1.1 * <dt>Creating new threads</dt>
72 dl 1.2 *
73 dl 1.19 * <dd>New threads are created using a {@link ThreadFactory}. By
74     * default, threads are created simply with the <tt>new
75     * Thread(Runnable)</tt> constructor, but by supplying a different
76     * ThreadFactory, you can alter the thread's name, thread group,
77     * priority, daemon status, etc. </dd>
78 dl 1.2 *
79 dl 1.21 * <dt>Keep-alive times</dt>
80     *
81     * <dd>If the pool currently has more than corePoolSize threads,
82     * excess threads will be terminated if they have been idle for more
83     * than the keepAliveTime (see {@link
84     * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
85     * reducing resource consumption when the pool is not being actively
86     * used. If the pool becomes more active later, new threads will be
87     * constructed. This parameter can also be changed dynamically
88     * using method {@link ThreadPoolExecutor#setKeepAliveTime}. Using
89     * a value of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS}
90     * effectively disables idle threads from ever terminating prior
91     * to shut down.
92     * </dd>
93     *
94     * <dt>Queueing</dt>
95     *
96     * <dd>Any {@link BlockingQueue} may be used to transfer and hold
97     * submitted tasks. The use of this queue interacts with pool sizing:
98 dl 1.2 *
99 dl 1.21 * <ul>
100     *
101 dl 1.23 * <li> If fewer than corePoolSize threads are running, the Executor
102     * always prefers adding a new thread
103 dl 1.21 * rather than queueing.</li>
104     *
105 dl 1.23 * <li> If corePoolSize or more threads are running, the Executor
106     * always prefers queuing a request rather than adding a new
107     * thread.</li>
108 dl 1.21 *
109     * <li> If a request cannot be queued, a new thread is created unless
110     * this would exceed maximumPoolSize, in which case, the task will be
111     * rejected.</li>
112     *
113     * </ul>
114     *
115     * There are three general strategies for queuing:
116     * <ol>
117     *
118     * <li> <em> Direct handoffs.</em> A good default choice for a work
119     * queue is a {@link SynchronousQueue} that hands off tasks to threads
120     * without otherwise holding them. Here, an attempt to queue a task
121     * will fail if no threads are immediately available to run it, so a
122     * new thread will be constructed. This policy avoids lockups when
123     * handling sets of requests that might have internal dependencies.
124     * Direct handoffs generally require unbounded maximumPoolSizes to
125 dl 1.24 * avoid rejection of new submitted tasks. This in turn admits the
126 dl 1.21 * possibility of unbounded thread growth when commands continue to
127     * arrive on average faster than they can be processed. </li>
128     *
129     * <li><em> Unbounded queues.</em> Using an unbounded queue (for
130     * example a {@link LinkedBlockingQueue} without a predefined
131     * capacity) will cause new tasks to be queued in cases where all
132 dl 1.22 * corePoolSize threads are busy. Thus, no more than corePoolSize
133     * threads will ever be created. (And the value of the maximumPoolSize
134     * therefore doesn't have any effect.) This may be appropriate when
135     * each task is completely independent of others, so tasks cannot
136     * affect each others execution; for example, in a web page server.
137     * While this style of queuing can be useful in smoothing out
138     * transient bursts of requests, it admits the possibility of
139     * unbounded work queue growth when commands continue to arrive on
140     * average faster than they can be processed. </li>
141 dl 1.21 *
142     * <li><em>Bounded queues.</em> A bounded queue (for example, an
143     * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
144     * used with finite maximumPoolSizes, but can be more difficult to
145     * tune and control. Queue sizes and maximum pool sizes may be traded
146     * off for each other: Using large queues and small pools minimizes
147     * CPU usage, OS resources, and context-switching overhead, but can
148 dl 1.27 * lead to artificially low throughput. If tasks frequently block (for
149 dl 1.21 * example if they are I/O bound), a system may be able to schedule
150     * time for more threads than you otherwise allow. Use of small queues
151 dl 1.24 * generally requires larger pool sizes, which keeps CPUs busier but
152     * may encounter unacceptable scheduling overhead, which also
153     * decreases throughput. </li>
154 dl 1.21 *
155     * </ol>
156     *
157     * </dd>
158     *
159     * <dt>Rejected tasks</dt>
160     *
161     * <dd> New tasks submitted in method {@link
162     * ThreadPoolExecutor#execute} will be <em>rejected</em> when the
163     * Executor has been shut down, and also when the Executor uses finite
164     * bounds for both maximum threads and work queue capacity, and is
165 dl 1.22 * saturated. In either case, the <tt>execute</tt> method invokes the
166     * {@link RejectedExecutionHandler#rejectedExecution} method of its
167     * {@link RejectedExecutionHandler}. Four predefined handler policies
168     * are provided:
169 dl 1.21 *
170     * <ol>
171     *
172     * <li> In the
173     * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
174     * runtime {@link RejectedExecutionException} upon rejection. </li>
175     *
176     * <li> In {@link
177     * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
178     * <tt>execute</tt> itself runs the task. This provides a simple
179     * feedback control mechanism that will slow down the rate that new
180     * tasks are submitted. </li>
181     *
182     * <li> In {@link ThreadPoolExecutor.DiscardPolicy},
183     * a task that cannot be executed is simply dropped. </li>
184     *
185     * <li>In {@link
186     * ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not
187     * shut down, the task at the head of the work queue is dropped, and
188     * then execution is retried (which can fail again, causing this to be
189     * repeated.) </li>
190     *
191     * </ol>
192     *
193     * It is possible to define and use other kinds of {@link
194     * RejectedExecutionHandler} classes. Doing so requires some care
195     * especially when policies are designed to work only under particular
196     * capacity or queueing policies. </dd>
197     *
198     * <dt>Hook methods</dt>
199     *
200 dl 1.23 * <dd>This class provides <tt>protected</tt> overridable {@link
201 dl 1.21 * ThreadPoolExecutor#beforeExecute} and {@link
202     * ThreadPoolExecutor#afterExecute} methods that are called before and
203 dl 1.19 * after execution of each task. These can be used to manipulate the
204     * execution environment, for example, reinitializing ThreadLocals,
205 dl 1.21 * gathering statistics, or adding log entries. Additionally, method
206     * {@link ThreadPoolExecutor#terminated} can be overridden to perform
207     * any special processing that needs to be done once the Executor has
208     * fully terminated.</dd>
209 dl 1.2 *
210 dl 1.21 * <dt>Queue maintenance</dt>
211 dl 1.2 *
212 dl 1.24 * <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to
213     * the work queue for purposes of monitoring and debugging. Use of
214     * this method for any other purpose is strongly discouraged. Two
215     * supplied methods, {@link ThreadPoolExecutor#remove} and {@link
216     * ThreadPoolExecutor#purge} are available to assist in storage
217     * reclamation when large numbers of queued tasks become
218     * cancelled.</dd> </dl>
219 tim 1.1 *
220     * @since 1.5
221 dl 1.8 * @author Doug Lea
222 tim 1.1 */
223 dl 1.2 public class ThreadPoolExecutor implements ExecutorService {
224     /**
225     * Queue used for holding tasks and handing off to worker threads.
226 tim 1.10 */
227 dl 1.2 private final BlockingQueue<Runnable> workQueue;
228    
229     /**
230     * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
231     * workers set.
232 tim 1.10 */
233 dl 1.2 private final ReentrantLock mainLock = new ReentrantLock();
234    
235     /**
236     * Wait condition to support awaitTermination
237 tim 1.10 */
238 dl 1.2 private final Condition termination = mainLock.newCondition();
239    
240     /**
241     * Set containing all worker threads in pool.
242 tim 1.10 */
243 dl 1.17 private final HashSet<Worker> workers = new HashSet<Worker>();
244 dl 1.2
245     /**
246     * Timeout in nanosecods for idle threads waiting for work.
247     * Threads use this timeout only when there are more than
248     * corePoolSize present. Otherwise they wait forever for new work.
249 tim 1.10 */
250 dl 1.2 private volatile long keepAliveTime;
251    
252     /**
253     * Core pool size, updated only while holding mainLock,
254     * but volatile to allow concurrent readability even
255     * during updates.
256 tim 1.10 */
257 dl 1.2 private volatile int corePoolSize;
258    
259     /**
260     * Maximum pool size, updated only while holding mainLock
261     * but volatile to allow concurrent readability even
262     * during updates.
263 tim 1.10 */
264 dl 1.2 private volatile int maximumPoolSize;
265    
266     /**
267     * Current pool size, updated only while holding mainLock
268     * but volatile to allow concurrent readability even
269     * during updates.
270 tim 1.10 */
271 dl 1.2 private volatile int poolSize;
272    
273     /**
274 dl 1.16 * Lifecycle state
275 tim 1.10 */
276 dl 1.16 private volatile int runState;
277 dl 1.2
278 dl 1.16 // Special values for runState
279 dl 1.8 /** Normal, not-shutdown mode */
280 dl 1.16 private static final int RUNNING = 0;
281 dl 1.8 /** Controlled shutdown mode */
282 dl 1.16 private static final int SHUTDOWN = 1;
283     /** Immediate shutdown mode */
284     private static final int STOP = 2;
285     /** Final state */
286     private static final int TERMINATED = 3;
287 dl 1.2
288     /**
289     * Handler called when saturated or shutdown in execute.
290 tim 1.10 */
291 dl 1.2 private volatile RejectedExecutionHandler handler = defaultHandler;
292    
293     /**
294     * Factory for new threads.
295 tim 1.10 */
296 dl 1.2 private volatile ThreadFactory threadFactory = defaultThreadFactory;
297    
298     /**
299     * Tracks largest attained pool size.
300 tim 1.10 */
301 dl 1.2 private int largestPoolSize;
302    
303     /**
304     * Counter for completed tasks. Updated only on termination of
305     * worker threads.
306 tim 1.10 */
307 dl 1.2 private long completedTaskCount;
308    
309 dl 1.8 /**
310 dl 1.16 * The default thread factory
311 dl 1.8 */
312 tim 1.10 private static final ThreadFactory defaultThreadFactory =
313 dl 1.2 new ThreadFactory() {
314     public Thread newThread(Runnable r) {
315     return new Thread(r);
316     }
317     };
318    
319 dl 1.8 /**
320     * The default rejectect execution handler
321     */
322 tim 1.10 private static final RejectedExecutionHandler defaultHandler =
323 dl 1.2 new AbortPolicy();
324    
325     /**
326 dl 1.17 * Invoke the rejected execution handler for the given command.
327 dl 1.13 */
328     void reject(Runnable command) {
329     handler.rejectedExecution(command, this);
330     }
331    
332     /**
333 dl 1.2 * Create and return a new thread running firstTask as its first
334     * task. Call only while holding mainLock
335 dl 1.8 * @param firstTask the task the new thread should run first (or
336     * null if none)
337     * @return the new thread
338 dl 1.2 */
339     private Thread addThread(Runnable firstTask) {
340     Worker w = new Worker(firstTask);
341     Thread t = threadFactory.newThread(w);
342     w.thread = t;
343     workers.add(w);
344     int nt = ++poolSize;
345     if (nt > largestPoolSize)
346     largestPoolSize = nt;
347     return t;
348     }
349    
350 dl 1.16
351 dl 1.15
352 dl 1.2 /**
353     * Create and start a new thread running firstTask as its first
354     * task, only if less than corePoolSize threads are running.
355 dl 1.8 * @param firstTask the task the new thread should run first (or
356     * null if none)
357 dl 1.2 * @return true if successful.
358     */
359 dl 1.16 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
360 dl 1.2 Thread t = null;
361     mainLock.lock();
362     try {
363 tim 1.10 if (poolSize < corePoolSize)
364 dl 1.8 t = addThread(firstTask);
365 tim 1.14 } finally {
366 dl 1.2 mainLock.unlock();
367     }
368     if (t == null)
369     return false;
370     t.start();
371     return true;
372     }
373    
374     /**
375     * Create and start a new thread only if less than maximumPoolSize
376     * threads are running. The new thread runs as its first task the
377     * next task in queue, or if there is none, the given task.
378 dl 1.8 * @param firstTask the task the new thread should run first (or
379     * null if none)
380 dl 1.2 * @return null on failure, else the first task to be run by new thread.
381     */
382 dl 1.8 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
383 dl 1.2 Thread t = null;
384     Runnable next = null;
385     mainLock.lock();
386     try {
387     if (poolSize < maximumPoolSize) {
388     next = workQueue.poll();
389     if (next == null)
390 dl 1.8 next = firstTask;
391 dl 1.2 t = addThread(next);
392     }
393 tim 1.14 } finally {
394 dl 1.2 mainLock.unlock();
395     }
396     if (t == null)
397     return null;
398     t.start();
399     return next;
400     }
401    
402    
403     /**
404     * Get the next task for a worker thread to run.
405 dl 1.8 * @return the task
406     * @throws InterruptedException if interrupted while waiting for task
407 dl 1.2 */
408     private Runnable getTask() throws InterruptedException {
409     for (;;) {
410 dl 1.16 switch(runState) {
411     case RUNNING: {
412     if (poolSize <= corePoolSize) // untimed wait if core
413     return workQueue.take();
414    
415     long timeout = keepAliveTime;
416     if (timeout <= 0) // die immediately for 0 timeout
417     return null;
418     Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
419     if (r != null)
420     return r;
421     if (poolSize > corePoolSize) // timed out
422     return null;
423     // else, after timeout, pool shrank so shouldn't die, so retry
424     break;
425     }
426    
427     case SHUTDOWN: {
428     // Help drain queue
429     Runnable r = workQueue.poll();
430     if (r != null)
431     return r;
432    
433     // Check if can terminate
434     if (workQueue.isEmpty()) {
435     interruptIdleWorkers();
436     return null;
437     }
438    
439     // There could still be delayed tasks in queue.
440     // Wait for one, re-checking state upon interruption
441     try {
442     return workQueue.take();
443     }
444     catch(InterruptedException ignore) {
445     }
446     break;
447     }
448    
449     case STOP:
450 dl 1.2 return null;
451 dl 1.16 default:
452     assert false;
453     }
454     }
455     }
456    
457     /**
458     * Wake up all threads that might be waiting for tasks.
459     */
460     void interruptIdleWorkers() {
461     mainLock.lock();
462     try {
463     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
464     it.next().interruptIfIdle();
465     } finally {
466     mainLock.unlock();
467 dl 1.2 }
468     }
469    
470     /**
471     * Perform bookkeeping for a terminated worker thread.
472 tim 1.10 * @param w the worker
473 dl 1.2 */
474     private void workerDone(Worker w) {
475     mainLock.lock();
476     try {
477     completedTaskCount += w.completedTasks;
478     workers.remove(w);
479 tim 1.10 if (--poolSize > 0)
480 dl 1.2 return;
481    
482 dl 1.16 // Else, this is the last thread. Deal with potential shutdown.
483    
484     int state = runState;
485     assert state != TERMINATED;
486 tim 1.10
487 dl 1.16 if (state != STOP) {
488     // If there are queued tasks but no threads, create
489     // replacement.
490 dl 1.2 Runnable r = workQueue.poll();
491     if (r != null) {
492     addThread(r).start();
493     return;
494     }
495 dl 1.16
496     // If there are some (presumably delayed) tasks but
497     // none pollable, create an idle replacement to wait.
498     if (!workQueue.isEmpty()) {
499     addThread(null).start();
500     return;
501     }
502    
503     // Otherwise, we can exit without replacement
504     if (state == RUNNING)
505     return;
506 dl 1.2 }
507    
508 dl 1.16 // Either state is STOP, or state is SHUTDOWN and there is
509     // no work to do. So we can terminate.
510     runState = TERMINATED;
511 dl 1.2 termination.signalAll();
512 dl 1.16 // fall through to call terminate() outside of lock.
513 tim 1.14 } finally {
514 dl 1.2 mainLock.unlock();
515     }
516    
517 dl 1.16 assert runState == TERMINATED;
518     terminated();
519 dl 1.2 }
520    
521     /**
522 tim 1.10 * Worker threads
523 dl 1.2 */
524     private class Worker implements Runnable {
525    
526     /**
527     * The runLock is acquired and released surrounding each task
528     * execution. It mainly protects against interrupts that are
529     * intended to cancel the worker thread from instead
530     * interrupting the task being run.
531     */
532     private final ReentrantLock runLock = new ReentrantLock();
533    
534     /**
535     * Initial task to run before entering run loop
536     */
537     private Runnable firstTask;
538    
539     /**
540     * Per thread completed task counter; accumulated
541     * into completedTaskCount upon termination.
542     */
543     volatile long completedTasks;
544    
545     /**
546     * Thread this worker is running in. Acts as a final field,
547     * but cannot be set until thread is created.
548     */
549     Thread thread;
550    
551     Worker(Runnable firstTask) {
552     this.firstTask = firstTask;
553     }
554    
555     boolean isActive() {
556     return runLock.isLocked();
557     }
558    
559     /**
560     * Interrupt thread if not running a task
561 tim 1.10 */
562 dl 1.2 void interruptIfIdle() {
563     if (runLock.tryLock()) {
564     try {
565     thread.interrupt();
566 tim 1.14 } finally {
567 dl 1.2 runLock.unlock();
568     }
569     }
570     }
571    
572     /**
573     * Cause thread to die even if running a task.
574 tim 1.10 */
575 dl 1.2 void interruptNow() {
576     thread.interrupt();
577     }
578    
579     /**
580     * Run a single task between before/after methods.
581     */
582     private void runTask(Runnable task) {
583     runLock.lock();
584     try {
585     // Abort now if immediate cancel. Otherwise, we have
586     // committed to run this task.
587 dl 1.16 if (runState == STOP)
588 dl 1.2 return;
589    
590     Thread.interrupted(); // clear interrupt status on entry
591     boolean ran = false;
592     beforeExecute(thread, task);
593     try {
594     task.run();
595     ran = true;
596     afterExecute(task, null);
597     ++completedTasks;
598 tim 1.14 } catch(RuntimeException ex) {
599 dl 1.2 if (!ran)
600     afterExecute(task, ex);
601 dl 1.17 // Else the exception occurred within
602 dl 1.2 // afterExecute itself in which case we don't
603     // want to call it again.
604     throw ex;
605     }
606 tim 1.14 } finally {
607 dl 1.2 runLock.unlock();
608     }
609     }
610    
611     /**
612     * Main run loop
613     */
614     public void run() {
615     try {
616     for (;;) {
617     Runnable task;
618     if (firstTask != null) {
619     task = firstTask;
620     firstTask = null;
621 tim 1.14 } else {
622 dl 1.2 task = getTask();
623     if (task == null)
624     break;
625     }
626     runTask(task);
627     task = null; // unnecessary but can help GC
628     }
629 tim 1.14 } catch(InterruptedException ie) {
630 dl 1.2 // fall through
631 tim 1.14 } finally {
632 dl 1.2 workerDone(this);
633     }
634     }
635     }
636 tim 1.1
637 dl 1.17 // Public methods
638    
639 tim 1.1 /**
640 dl 1.17 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
641     * initial parameters. It may be more convenient to use one of
642 dholmes 1.18 * the {@link Executors} factory methods instead of this general
643 dl 1.17 * purpose constructor.
644 tim 1.1 *
645 dl 1.2 * @param corePoolSize the number of threads to keep in the
646 tim 1.1 * pool, even if they are idle.
647 dl 1.2 * @param maximumPoolSize the maximum number of threads to allow in the
648 tim 1.1 * pool.
649     * @param keepAliveTime when the number of threads is greater than
650 dl 1.2 * the core, this is the maximum time that excess idle threads
651 tim 1.1 * will wait for new tasks before terminating.
652 dl 1.2 * @param unit the time unit for the keepAliveTime
653 tim 1.1 * argument.
654     * @param workQueue the queue to use for holding tasks before the
655     * are executed. This queue will hold only the <tt>Runnable</tt>
656     * tasks submitted by the <tt>execute</tt> method.
657 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
658     * keepAliveTime less than zero, or if maximumPoolSize less than or
659     * equal to zero, or if corePoolSize greater than maximumPoolSize.
660 tim 1.1 * @throws NullPointerException if <tt>workQueue</tt> is null
661     */
662 dl 1.2 public ThreadPoolExecutor(int corePoolSize,
663     int maximumPoolSize,
664 tim 1.1 long keepAliveTime,
665 dl 1.2 TimeUnit unit,
666     BlockingQueue<Runnable> workQueue) {
667 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
668 dl 1.2 defaultThreadFactory, defaultHandler);
669     }
670 tim 1.1
671 dl 1.2 /**
672     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
673     * parameters.
674     *
675     * @param corePoolSize the number of threads to keep in the
676     * pool, even if they are idle.
677     * @param maximumPoolSize the maximum number of threads to allow in the
678     * pool.
679     * @param keepAliveTime when the number of threads is greater than
680     * the core, this is the maximum time that excess idle threads
681     * will wait for new tasks before terminating.
682     * @param unit the time unit for the keepAliveTime
683     * argument.
684     * @param workQueue the queue to use for holding tasks before the
685     * are executed. This queue will hold only the <tt>Runnable</tt>
686     * tasks submitted by the <tt>execute</tt> method.
687     * @param threadFactory the factory to use when the executor
688 tim 1.10 * creates a new thread.
689 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
690     * keepAliveTime less than zero, or if maximumPoolSize less than or
691     * equal to zero, or if corePoolSize greater than maximumPoolSize.
692 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
693 dl 1.2 * or <tt>threadFactory</tt> are null.
694     */
695     public ThreadPoolExecutor(int corePoolSize,
696     int maximumPoolSize,
697     long keepAliveTime,
698     TimeUnit unit,
699     BlockingQueue<Runnable> workQueue,
700     ThreadFactory threadFactory) {
701 tim 1.1
702 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
703 dl 1.2 threadFactory, defaultHandler);
704     }
705 tim 1.1
706 dl 1.2 /**
707     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
708     * parameters.
709     *
710     * @param corePoolSize the number of threads to keep in the
711     * pool, even if they are idle.
712     * @param maximumPoolSize the maximum number of threads to allow in the
713     * pool.
714     * @param keepAliveTime when the number of threads is greater than
715     * the core, this is the maximum time that excess idle threads
716     * will wait for new tasks before terminating.
717     * @param unit the time unit for the keepAliveTime
718     * argument.
719     * @param workQueue the queue to use for holding tasks before the
720     * are executed. This queue will hold only the <tt>Runnable</tt>
721     * tasks submitted by the <tt>execute</tt> method.
722     * @param handler the handler to use when execution is blocked
723     * because the thread bounds and queue capacities are reached.
724     * @throws IllegalArgumentException if corePoolSize, or
725     * keepAliveTime less than zero, or if maximumPoolSize less than or
726     * equal to zero, or if corePoolSize greater than maximumPoolSize.
727 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
728 dl 1.2 * or <tt>handler</tt> are null.
729     */
730     public ThreadPoolExecutor(int corePoolSize,
731     int maximumPoolSize,
732     long keepAliveTime,
733     TimeUnit unit,
734     BlockingQueue<Runnable> workQueue,
735     RejectedExecutionHandler handler) {
736 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
737 dl 1.2 defaultThreadFactory, handler);
738     }
739 tim 1.1
740 dl 1.2 /**
741     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
742     * parameters.
743     *
744     * @param corePoolSize the number of threads to keep in the
745     * pool, even if they are idle.
746     * @param maximumPoolSize the maximum number of threads to allow in the
747     * pool.
748     * @param keepAliveTime when the number of threads is greater than
749     * the core, this is the maximum time that excess idle threads
750     * will wait for new tasks before terminating.
751     * @param unit the time unit for the keepAliveTime
752     * argument.
753     * @param workQueue the queue to use for holding tasks before the
754     * are executed. This queue will hold only the <tt>Runnable</tt>
755     * tasks submitted by the <tt>execute</tt> method.
756     * @param threadFactory the factory to use when the executor
757 tim 1.10 * creates a new thread.
758 dl 1.2 * @param handler the handler to use when execution is blocked
759     * because the thread bounds and queue capacities are reached.
760     * @throws IllegalArgumentException if corePoolSize, or
761     * keepAliveTime less than zero, or if maximumPoolSize less than or
762     * equal to zero, or if corePoolSize greater than maximumPoolSize.
763 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
764 dl 1.2 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
765     */
766     public ThreadPoolExecutor(int corePoolSize,
767     int maximumPoolSize,
768     long keepAliveTime,
769     TimeUnit unit,
770     BlockingQueue<Runnable> workQueue,
771     ThreadFactory threadFactory,
772     RejectedExecutionHandler handler) {
773 tim 1.10 if (corePoolSize < 0 ||
774 dl 1.2 maximumPoolSize <= 0 ||
775 tim 1.10 maximumPoolSize < corePoolSize ||
776 dl 1.2 keepAliveTime < 0)
777     throw new IllegalArgumentException();
778     if (workQueue == null || threadFactory == null || handler == null)
779     throw new NullPointerException();
780     this.corePoolSize = corePoolSize;
781     this.maximumPoolSize = maximumPoolSize;
782     this.workQueue = workQueue;
783     this.keepAliveTime = unit.toNanos(keepAliveTime);
784     this.threadFactory = threadFactory;
785     this.handler = handler;
786 tim 1.1 }
787    
788 dl 1.2
789     /**
790     * Executes the given task sometime in the future. The task
791     * may execute in a new thread or in an existing pooled thread.
792     *
793     * If the task cannot be submitted for execution, either because this
794     * executor has been shutdown or because its capacity has been reached,
795 tim 1.10 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
796 dl 1.2 *
797     * @param command the task to execute
798     * @throws RejectedExecutionException at discretion of
799 dl 1.8 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
800     * for execution
801 dl 1.26 * @throws NullPointerException if command is null
802 dl 1.2 */
803 tim 1.10 public void execute(Runnable command) {
804 dl 1.26 if (command == null)
805     throw new NullPointerException();
806 dl 1.2 for (;;) {
807 dl 1.16 if (runState != RUNNING) {
808 dl 1.13 reject(command);
809 dl 1.2 return;
810     }
811     if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
812     return;
813     if (workQueue.offer(command))
814     return;
815     Runnable r = addIfUnderMaximumPoolSize(command);
816     if (r == command)
817     return;
818     if (r == null) {
819 dl 1.13 reject(command);
820 dl 1.2 return;
821     }
822     // else retry
823     }
824 tim 1.1 }
825 dl 1.4
826 dl 1.2 public void shutdown() {
827 dl 1.25 boolean fullyTerminated = false;
828 dl 1.2 mainLock.lock();
829     try {
830 dl 1.25 if (workers.size() > 0) {
831     if (runState == RUNNING) // don't override shutdownNow
832     runState = SHUTDOWN;
833     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
834     it.next().interruptIfIdle();
835     }
836     else { // If no workers, trigger full termination now
837     fullyTerminated = true;
838     runState = TERMINATED;
839     termination.signalAll();
840     }
841 tim 1.14 } finally {
842 dl 1.2 mainLock.unlock();
843     }
844 dl 1.25 if (fullyTerminated)
845     terminated();
846 tim 1.1 }
847    
848 dl 1.16
849 dl 1.2 public List shutdownNow() {
850 dl 1.25 boolean fullyTerminated = false;
851 dl 1.2 mainLock.lock();
852     try {
853 dl 1.25 if (workers.size() > 0) {
854     if (runState != TERMINATED)
855     runState = STOP;
856     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
857     it.next().interruptNow();
858     }
859     else { // If no workers, trigger full termination now
860     fullyTerminated = true;
861     runState = TERMINATED;
862     termination.signalAll();
863     }
864 tim 1.14 } finally {
865 dl 1.2 mainLock.unlock();
866     }
867 dl 1.25 if (fullyTerminated)
868     terminated();
869 dl 1.2 return Arrays.asList(workQueue.toArray());
870 tim 1.1 }
871    
872 dl 1.2 public boolean isShutdown() {
873 dl 1.16 return runState != RUNNING;
874     }
875    
876     /**
877     * Return true if this executor is in the process of terminating
878     * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
879     * completely terminated. This method may be useful for
880     * debugging. A return of <tt>true</tt> reported a sufficient
881     * period after shutdown may indicate that submitted tasks have
882     * ignored or suppressed interruption, causing this executor not
883     * to properly terminate.
884     * @return true if terminating but not yet terminated.
885     */
886     public boolean isTerminating() {
887     return runState == STOP;
888 tim 1.1 }
889    
890 dl 1.2 public boolean isTerminated() {
891 dl 1.16 return runState == TERMINATED;
892 dl 1.2 }
893 tim 1.1
894 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
895     throws InterruptedException {
896     mainLock.lock();
897     try {
898 dl 1.25 long nanos = unit.toNanos(timeout);
899     for (;;) {
900     if (runState == TERMINATED)
901     return true;
902     if (nanos <= 0)
903     return false;
904     nanos = termination.awaitNanos(nanos);
905     }
906 tim 1.14 } finally {
907 dl 1.2 mainLock.unlock();
908     }
909 dl 1.15 }
910    
911     /**
912     * Invokes <tt>shutdown</tt> when this executor is no longer
913     * referenced.
914     */
915     protected void finalize() {
916     shutdown();
917 dl 1.2 }
918 tim 1.10
919 dl 1.2 /**
920     * Sets the thread factory used to create new threads.
921     *
922     * @param threadFactory the new thread factory
923 dl 1.30 * @throws NullPointerException if threadFactory is null
924 tim 1.11 * @see #getThreadFactory
925 dl 1.2 */
926     public void setThreadFactory(ThreadFactory threadFactory) {
927 dl 1.30 if (threadFactory == null)
928     throw new NullPointerException();
929 dl 1.2 this.threadFactory = threadFactory;
930 tim 1.1 }
931    
932 dl 1.2 /**
933     * Returns the thread factory used to create new threads.
934     *
935     * @return the current thread factory
936 tim 1.11 * @see #setThreadFactory
937 dl 1.2 */
938     public ThreadFactory getThreadFactory() {
939     return threadFactory;
940 tim 1.1 }
941    
942 dl 1.2 /**
943     * Sets a new handler for unexecutable tasks.
944     *
945     * @param handler the new handler
946 tim 1.11 * @see #getRejectedExecutionHandler
947 dl 1.2 */
948     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
949     this.handler = handler;
950     }
951 tim 1.1
952 dl 1.2 /**
953     * Returns the current handler for unexecutable tasks.
954     *
955     * @return the current handler
956 tim 1.11 * @see #setRejectedExecutionHandler
957 dl 1.2 */
958     public RejectedExecutionHandler getRejectedExecutionHandler() {
959     return handler;
960 tim 1.1 }
961    
962 dl 1.2 /**
963 dl 1.17 * Returns the task queue used by this executor. Access to the
964     * task queue is intended primarily for debugging and monitoring.
965 dl 1.27 * This queue may be in active use. Retrieving the task queue
966 dl 1.2 * does not prevent queued tasks from executing.
967     *
968     * @return the task queue
969     */
970     public BlockingQueue<Runnable> getQueue() {
971     return workQueue;
972 tim 1.1 }
973 dl 1.4
974     /**
975     * Removes this task from internal queue if it is present, thus
976     * causing it not to be run if it has not already started. This
977     * method may be useful as one part of a cancellation scheme.
978 tim 1.10 *
979 dl 1.8 * @param task the task to remove
980     * @return true if the task was removed
981 dl 1.4 */
982 dl 1.5 public boolean remove(Runnable task) {
983 dl 1.4 return getQueue().remove(task);
984     }
985    
986 dl 1.7
987     /**
988 dl 1.16 * Tries to remove from the work queue all {@link Cancellable}
989     * tasks that have been cancelled. This method can be useful as a
990     * storage reclamation operation, that has no other impact on
991     * functionality. Cancelled tasks are never executed, but may
992     * accumulate in work queues until worker threads can actively
993     * remove them. Invoking this method instead tries to remove them now.
994 dl 1.23 * However, this method may fail to remove tasks in
995 dl 1.16 * the presence of interference by other threads.
996 dl 1.7 */
997    
998     public void purge() {
999 dl 1.16 // Fail if we encounter interference during traversal
1000     try {
1001     Iterator<Runnable> it = getQueue().iterator();
1002     while (it.hasNext()) {
1003     Runnable r = it.next();
1004     if (r instanceof Cancellable) {
1005     Cancellable c = (Cancellable)r;
1006     if (c.isCancelled())
1007     it.remove();
1008     }
1009 dl 1.7 }
1010     }
1011 dl 1.16 catch(ConcurrentModificationException ex) {
1012     return;
1013     }
1014 dl 1.7 }
1015 tim 1.1
1016     /**
1017 dl 1.2 * Sets the core number of threads. This overrides any value set
1018     * in the constructor. If the new value is smaller than the
1019     * current value, excess existing threads will be terminated when
1020     * they next become idle.
1021 tim 1.1 *
1022 dl 1.2 * @param corePoolSize the new core size
1023 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1024 dl 1.8 * less than zero
1025 tim 1.11 * @see #getCorePoolSize
1026 tim 1.1 */
1027 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1028     if (corePoolSize < 0)
1029     throw new IllegalArgumentException();
1030     mainLock.lock();
1031     try {
1032     int extra = this.corePoolSize - corePoolSize;
1033     this.corePoolSize = corePoolSize;
1034     if (extra > 0 && poolSize > corePoolSize) {
1035     Iterator<Worker> it = workers.iterator();
1036 tim 1.10 while (it.hasNext() &&
1037     extra > 0 &&
1038 dl 1.2 poolSize > corePoolSize &&
1039     workQueue.remainingCapacity() == 0) {
1040     it.next().interruptIfIdle();
1041     --extra;
1042     }
1043     }
1044 tim 1.10
1045 tim 1.14 } finally {
1046 dl 1.2 mainLock.unlock();
1047     }
1048     }
1049 tim 1.1
1050     /**
1051 dl 1.2 * Returns the core number of threads.
1052 tim 1.1 *
1053 dl 1.2 * @return the core number of threads
1054 tim 1.11 * @see #setCorePoolSize
1055 tim 1.1 */
1056 tim 1.10 public int getCorePoolSize() {
1057 dl 1.2 return corePoolSize;
1058 dl 1.16 }
1059    
1060     /**
1061     * Start a core thread, causing it to idly wait for work. This
1062     * overrides the default policy of starting core threads only when
1063     * new tasks are executed. This method will return <tt>false</tt>
1064     * if all core threads have already been started.
1065     * @return true if a thread was started
1066     */
1067     public boolean prestartCoreThread() {
1068     return addIfUnderCorePoolSize(null);
1069     }
1070    
1071     /**
1072     * Start all core threads, causing them to idly wait for work. This
1073     * overrides the default policy of starting core threads only when
1074     * new tasks are executed.
1075     * @return the number of threads started.
1076     */
1077     public int prestartAllCoreThreads() {
1078     int n = 0;
1079     while (addIfUnderCorePoolSize(null))
1080     ++n;
1081     return n;
1082 dl 1.2 }
1083 tim 1.1
1084     /**
1085     * Sets the maximum allowed number of threads. This overrides any
1086 dl 1.2 * value set in the constructor. If the new value is smaller than
1087     * the current value, excess existing threads will be
1088     * terminated when they next become idle.
1089 tim 1.1 *
1090 dl 1.2 * @param maximumPoolSize the new maximum
1091     * @throws IllegalArgumentException if maximumPoolSize less than zero or
1092     * the {@link #getCorePoolSize core pool size}
1093 tim 1.11 * @see #getMaximumPoolSize
1094 dl 1.2 */
1095     public void setMaximumPoolSize(int maximumPoolSize) {
1096     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1097     throw new IllegalArgumentException();
1098     mainLock.lock();
1099     try {
1100     int extra = this.maximumPoolSize - maximumPoolSize;
1101     this.maximumPoolSize = maximumPoolSize;
1102     if (extra > 0 && poolSize > maximumPoolSize) {
1103     Iterator<Worker> it = workers.iterator();
1104 tim 1.10 while (it.hasNext() &&
1105     extra > 0 &&
1106 dl 1.2 poolSize > maximumPoolSize) {
1107     it.next().interruptIfIdle();
1108     --extra;
1109     }
1110     }
1111 tim 1.14 } finally {
1112 dl 1.2 mainLock.unlock();
1113     }
1114     }
1115 tim 1.1
1116     /**
1117     * Returns the maximum allowed number of threads.
1118     *
1119 dl 1.2 * @return the maximum allowed number of threads
1120 tim 1.11 * @see #setMaximumPoolSize
1121 tim 1.1 */
1122 tim 1.10 public int getMaximumPoolSize() {
1123 dl 1.2 return maximumPoolSize;
1124     }
1125 tim 1.1
1126     /**
1127     * Sets the time limit for which threads may remain idle before
1128 dl 1.2 * being terminated. If there are more than the core number of
1129 tim 1.1 * threads currently in the pool, after waiting this amount of
1130     * time without processing a task, excess threads will be
1131     * terminated. This overrides any value set in the constructor.
1132     * @param time the time to wait. A time value of zero will cause
1133     * excess threads to terminate immediately after executing tasks.
1134 dl 1.2 * @param unit the time unit of the time argument
1135 dl 1.17 * @throws IllegalArgumentException if time less than zero
1136 tim 1.11 * @see #getKeepAliveTime
1137 tim 1.1 */
1138 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1139     if (time < 0)
1140     throw new IllegalArgumentException();
1141     this.keepAliveTime = unit.toNanos(time);
1142     }
1143 tim 1.1
1144     /**
1145     * Returns the thread keep-alive time, which is the amount of time
1146 dl 1.2 * which threads in excess of the core pool size may remain
1147 tim 1.10 * idle before being terminated.
1148 tim 1.1 *
1149 dl 1.2 * @param unit the desired time unit of the result
1150 tim 1.1 * @return the time limit
1151 tim 1.11 * @see #setKeepAliveTime
1152 tim 1.1 */
1153 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1154 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1155     }
1156 tim 1.1
1157     /* Statistics */
1158    
1159     /**
1160     * Returns the current number of threads in the pool.
1161     *
1162     * @return the number of threads
1163     */
1164 tim 1.10 public int getPoolSize() {
1165 dl 1.2 return poolSize;
1166     }
1167 tim 1.1
1168     /**
1169 dl 1.2 * Returns the approximate number of threads that are actively
1170 tim 1.1 * executing tasks.
1171     *
1172     * @return the number of threads
1173     */
1174 tim 1.10 public int getActiveCount() {
1175 dl 1.2 mainLock.lock();
1176     try {
1177     int n = 0;
1178     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1179     if (it.next().isActive())
1180     ++n;
1181     }
1182     return n;
1183 tim 1.14 } finally {
1184 dl 1.2 mainLock.unlock();
1185     }
1186     }
1187 tim 1.1
1188     /**
1189 dl 1.2 * Returns the largest number of threads that have ever
1190     * simultaneously been in the pool.
1191 tim 1.1 *
1192     * @return the number of threads
1193     */
1194 tim 1.10 public int getLargestPoolSize() {
1195 dl 1.2 mainLock.lock();
1196     try {
1197     return largestPoolSize;
1198 tim 1.14 } finally {
1199 dl 1.2 mainLock.unlock();
1200     }
1201     }
1202 tim 1.1
1203     /**
1204 dl 1.2 * Returns the approximate total number of tasks that have been
1205     * scheduled for execution. Because the states of tasks and
1206     * threads may change dynamically during computation, the returned
1207 dl 1.17 * value is only an approximation, but one that does not ever
1208     * decrease across successive calls.
1209 tim 1.1 *
1210     * @return the number of tasks
1211     */
1212 tim 1.10 public long getTaskCount() {
1213 dl 1.2 mainLock.lock();
1214     try {
1215     long n = completedTaskCount;
1216     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1217     Worker w = it.next();
1218     n += w.completedTasks;
1219     if (w.isActive())
1220     ++n;
1221     }
1222     return n + workQueue.size();
1223 tim 1.14 } finally {
1224 dl 1.2 mainLock.unlock();
1225     }
1226     }
1227 tim 1.1
1228     /**
1229 dl 1.2 * Returns the approximate total number of tasks that have
1230     * completed execution. Because the states of tasks and threads
1231     * may change dynamically during computation, the returned value
1232 dl 1.17 * is only an approximation, but one that does not ever decrease
1233     * across successive calls.
1234 tim 1.1 *
1235     * @return the number of tasks
1236     */
1237 tim 1.10 public long getCompletedTaskCount() {
1238 dl 1.2 mainLock.lock();
1239     try {
1240     long n = completedTaskCount;
1241 tim 1.10 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
1242 dl 1.2 n += it.next().completedTasks;
1243     return n;
1244 tim 1.14 } finally {
1245 dl 1.2 mainLock.unlock();
1246     }
1247     }
1248 tim 1.1
1249     /**
1250 dl 1.17 * Method invoked prior to executing the given Runnable in the
1251     * given thread. This method may be used to re-initialize
1252     * ThreadLocals, or to perform logging. Note: To properly nest
1253     * multiple overridings, subclasses should generally invoke
1254 dl 1.5 * <tt>super.beforeExecute</tt> at the end of this method.
1255 tim 1.1 *
1256 dl 1.2 * @param t the thread that will run task r.
1257     * @param r the task that will be executed.
1258 tim 1.1 */
1259 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1260 tim 1.1
1261     /**
1262 dl 1.2 * Method invoked upon completion of execution of the given
1263     * Runnable. If non-null, the Throwable is the uncaught exception
1264 dl 1.5 * that caused execution to terminate abruptly. Note: To properly
1265     * nest multiple overridings, subclasses should generally invoke
1266     * <tt>super.afterExecute</tt> at the beginning of this method.
1267 tim 1.1 *
1268 dl 1.2 * @param r the runnable that has completed.
1269 dl 1.24 * @param t the exception that caused termination, or null if
1270 dl 1.2 * execution completed normally.
1271 tim 1.1 */
1272 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1273 tim 1.1
1274 dl 1.2 /**
1275     * Method invoked when the Executor has terminated. Default
1276 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1277     * overridings, subclasses should generally invoke
1278     * <tt>super.terminated</tt> within this method.
1279 dl 1.2 */
1280     protected void terminated() { }
1281 tim 1.1
1282     /**
1283 dl 1.21 * A handler for rejected tasks that runs the rejected task
1284     * directly in the calling thread of the <tt>execute</tt> method,
1285     * unless the executor has been shut down, in which case the task
1286     * is discarded.
1287 tim 1.1 */
1288 dl 1.2 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1289 tim 1.1
1290     /**
1291 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1292 tim 1.1 */
1293     public CallerRunsPolicy() { }
1294    
1295 dl 1.24 /**
1296     * Executes task r in the caller's thread, unless the executor
1297     * has been shut down, in which case the task is discarded.
1298     * @param r the runnable task requested to be executed
1299     * @param e the executor attempting to execute this task
1300     */
1301 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1302     if (!e.isShutdown()) {
1303 tim 1.1 r.run();
1304     }
1305     }
1306     }
1307    
1308     /**
1309 dl 1.21 * A handler for rejected tasks that throws a
1310 dl 1.8 * <tt>RejectedExecutionException</tt>.
1311 tim 1.1 */
1312 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1313 tim 1.1
1314     /**
1315 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1316 tim 1.1 */
1317     public AbortPolicy() { }
1318    
1319 dl 1.24 /**
1320     * Always throws RejectedExecutionException
1321     * @param r the runnable task requested to be executed
1322     * @param e the executor attempting to execute this task
1323     * @throws RejectedExecutionException always.
1324     */
1325 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1326     throw new RejectedExecutionException();
1327 tim 1.1 }
1328     }
1329    
1330     /**
1331 dl 1.21 * A handler for rejected tasks that silently discards the
1332     * rejected task.
1333 tim 1.1 */
1334 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1335 tim 1.1
1336     /**
1337 dl 1.24 * Creates <tt>DiscardPolicy</tt>.
1338 tim 1.1 */
1339     public DiscardPolicy() { }
1340    
1341 dl 1.24 /**
1342     * Does nothing, which has the effect of discarding task r.
1343     * @param r the runnable task requested to be executed
1344     * @param e the executor attempting to execute this task
1345     */
1346 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1347 tim 1.1 }
1348     }
1349    
1350     /**
1351 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1352     * request and then retries <tt>execute</tt>, unless the executor
1353     * is shut down, in which case the task is discarded.
1354 tim 1.1 */
1355 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1356 tim 1.1 /**
1357 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1358 tim 1.1 */
1359     public DiscardOldestPolicy() { }
1360    
1361 dl 1.24 /**
1362     * Obtains and ignores the next task that the executor
1363     * would otherwise execute, if one is immediately available,
1364     * and then retries execution of task r, unless the executor
1365     * is shut down, in which case task r is instead discarded.
1366     * @param r the runnable task requested to be executed
1367     * @param e the executor attempting to execute this task
1368     */
1369 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1370     if (!e.isShutdown()) {
1371     e.getQueue().poll();
1372     e.execute(r);
1373 tim 1.1 }
1374     }
1375     }
1376     }