ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.25
Committed: Sun Sep 14 14:25:22 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.24: +36 -9 lines
Log Message:
Fix termination when never started

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