ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.29
Committed: Mon Sep 29 23:21:38 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.28: +1 -1 lines
Log Message:
fixed typos

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 tim 1.11 * @see #getThreadFactory
924 dl 1.2 */
925     public void setThreadFactory(ThreadFactory threadFactory) {
926     this.threadFactory = threadFactory;
927 tim 1.1 }
928    
929 dl 1.2 /**
930     * Returns the thread factory used to create new threads.
931     *
932     * @return the current thread factory
933 tim 1.11 * @see #setThreadFactory
934 dl 1.2 */
935     public ThreadFactory getThreadFactory() {
936     return threadFactory;
937 tim 1.1 }
938    
939 dl 1.2 /**
940     * Sets a new handler for unexecutable tasks.
941     *
942     * @param handler the new handler
943 tim 1.11 * @see #getRejectedExecutionHandler
944 dl 1.2 */
945     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
946     this.handler = handler;
947     }
948 tim 1.1
949 dl 1.2 /**
950     * Returns the current handler for unexecutable tasks.
951     *
952     * @return the current handler
953 tim 1.11 * @see #setRejectedExecutionHandler
954 dl 1.2 */
955     public RejectedExecutionHandler getRejectedExecutionHandler() {
956     return handler;
957 tim 1.1 }
958    
959 dl 1.2 /**
960 dl 1.17 * Returns the task queue used by this executor. Access to the
961     * task queue is intended primarily for debugging and monitoring.
962 dl 1.27 * This queue may be in active use. Retrieving the task queue
963 dl 1.2 * does not prevent queued tasks from executing.
964     *
965     * @return the task queue
966     */
967     public BlockingQueue<Runnable> getQueue() {
968     return workQueue;
969 tim 1.1 }
970 dl 1.4
971     /**
972     * Removes this task from internal queue if it is present, thus
973     * causing it not to be run if it has not already started. This
974     * method may be useful as one part of a cancellation scheme.
975 tim 1.10 *
976 dl 1.8 * @param task the task to remove
977     * @return true if the task was removed
978 dl 1.4 */
979 dl 1.5 public boolean remove(Runnable task) {
980 dl 1.4 return getQueue().remove(task);
981     }
982    
983 dl 1.7
984     /**
985 dl 1.16 * Tries to remove from the work queue all {@link Cancellable}
986     * tasks that have been cancelled. This method can be useful as a
987     * storage reclamation operation, that has no other impact on
988     * functionality. Cancelled tasks are never executed, but may
989     * accumulate in work queues until worker threads can actively
990     * remove them. Invoking this method instead tries to remove them now.
991 dl 1.23 * However, this method may fail to remove tasks in
992 dl 1.16 * the presence of interference by other threads.
993 dl 1.7 */
994    
995     public void purge() {
996 dl 1.16 // Fail if we encounter interference during traversal
997     try {
998     Iterator<Runnable> it = getQueue().iterator();
999     while (it.hasNext()) {
1000     Runnable r = it.next();
1001     if (r instanceof Cancellable) {
1002     Cancellable c = (Cancellable)r;
1003     if (c.isCancelled())
1004     it.remove();
1005     }
1006 dl 1.7 }
1007     }
1008 dl 1.16 catch(ConcurrentModificationException ex) {
1009     return;
1010     }
1011 dl 1.7 }
1012 tim 1.1
1013     /**
1014 dl 1.2 * Sets the core number of threads. This overrides any value set
1015     * in the constructor. If the new value is smaller than the
1016     * current value, excess existing threads will be terminated when
1017     * they next become idle.
1018 tim 1.1 *
1019 dl 1.2 * @param corePoolSize the new core size
1020 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1021 dl 1.8 * less than zero
1022 tim 1.11 * @see #getCorePoolSize
1023 tim 1.1 */
1024 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1025     if (corePoolSize < 0)
1026     throw new IllegalArgumentException();
1027     mainLock.lock();
1028     try {
1029     int extra = this.corePoolSize - corePoolSize;
1030     this.corePoolSize = corePoolSize;
1031     if (extra > 0 && poolSize > corePoolSize) {
1032     Iterator<Worker> it = workers.iterator();
1033 tim 1.10 while (it.hasNext() &&
1034     extra > 0 &&
1035 dl 1.2 poolSize > corePoolSize &&
1036     workQueue.remainingCapacity() == 0) {
1037     it.next().interruptIfIdle();
1038     --extra;
1039     }
1040     }
1041 tim 1.10
1042 tim 1.14 } finally {
1043 dl 1.2 mainLock.unlock();
1044     }
1045     }
1046 tim 1.1
1047     /**
1048 dl 1.2 * Returns the core number of threads.
1049 tim 1.1 *
1050 dl 1.2 * @return the core number of threads
1051 tim 1.11 * @see #setCorePoolSize
1052 tim 1.1 */
1053 tim 1.10 public int getCorePoolSize() {
1054 dl 1.2 return corePoolSize;
1055 dl 1.16 }
1056    
1057     /**
1058     * Start a core thread, causing it to idly wait for work. This
1059     * overrides the default policy of starting core threads only when
1060     * new tasks are executed. This method will return <tt>false</tt>
1061     * if all core threads have already been started.
1062     * @return true if a thread was started
1063     */
1064     public boolean prestartCoreThread() {
1065     return addIfUnderCorePoolSize(null);
1066     }
1067    
1068     /**
1069     * Start all core threads, causing them to idly wait for work. This
1070     * overrides the default policy of starting core threads only when
1071     * new tasks are executed.
1072     * @return the number of threads started.
1073     */
1074     public int prestartAllCoreThreads() {
1075     int n = 0;
1076     while (addIfUnderCorePoolSize(null))
1077     ++n;
1078     return n;
1079 dl 1.2 }
1080 tim 1.1
1081     /**
1082     * Sets the maximum allowed number of threads. This overrides any
1083 dl 1.2 * value set in the constructor. If the new value is smaller than
1084     * the current value, excess existing threads will be
1085     * terminated when they next become idle.
1086 tim 1.1 *
1087 dl 1.2 * @param maximumPoolSize the new maximum
1088     * @throws IllegalArgumentException if maximumPoolSize less than zero or
1089     * the {@link #getCorePoolSize core pool size}
1090 tim 1.11 * @see #getMaximumPoolSize
1091 dl 1.2 */
1092     public void setMaximumPoolSize(int maximumPoolSize) {
1093     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1094     throw new IllegalArgumentException();
1095     mainLock.lock();
1096     try {
1097     int extra = this.maximumPoolSize - maximumPoolSize;
1098     this.maximumPoolSize = maximumPoolSize;
1099     if (extra > 0 && poolSize > maximumPoolSize) {
1100     Iterator<Worker> it = workers.iterator();
1101 tim 1.10 while (it.hasNext() &&
1102     extra > 0 &&
1103 dl 1.2 poolSize > maximumPoolSize) {
1104     it.next().interruptIfIdle();
1105     --extra;
1106     }
1107     }
1108 tim 1.14 } finally {
1109 dl 1.2 mainLock.unlock();
1110     }
1111     }
1112 tim 1.1
1113     /**
1114     * Returns the maximum allowed number of threads.
1115     *
1116 dl 1.2 * @return the maximum allowed number of threads
1117 tim 1.11 * @see #setMaximumPoolSize
1118 tim 1.1 */
1119 tim 1.10 public int getMaximumPoolSize() {
1120 dl 1.2 return maximumPoolSize;
1121     }
1122 tim 1.1
1123     /**
1124     * Sets the time limit for which threads may remain idle before
1125 dl 1.2 * being terminated. If there are more than the core number of
1126 tim 1.1 * threads currently in the pool, after waiting this amount of
1127     * time without processing a task, excess threads will be
1128     * terminated. This overrides any value set in the constructor.
1129     * @param time the time to wait. A time value of zero will cause
1130     * excess threads to terminate immediately after executing tasks.
1131 dl 1.2 * @param unit the time unit of the time argument
1132 dl 1.17 * @throws IllegalArgumentException if time less than zero
1133 tim 1.11 * @see #getKeepAliveTime
1134 tim 1.1 */
1135 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1136     if (time < 0)
1137     throw new IllegalArgumentException();
1138     this.keepAliveTime = unit.toNanos(time);
1139     }
1140 tim 1.1
1141     /**
1142     * Returns the thread keep-alive time, which is the amount of time
1143 dl 1.2 * which threads in excess of the core pool size may remain
1144 tim 1.10 * idle before being terminated.
1145 tim 1.1 *
1146 dl 1.2 * @param unit the desired time unit of the result
1147 tim 1.1 * @return the time limit
1148 tim 1.11 * @see #setKeepAliveTime
1149 tim 1.1 */
1150 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1151 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1152     }
1153 tim 1.1
1154     /* Statistics */
1155    
1156     /**
1157     * Returns the current number of threads in the pool.
1158     *
1159     * @return the number of threads
1160     */
1161 tim 1.10 public int getPoolSize() {
1162 dl 1.2 return poolSize;
1163     }
1164 tim 1.1
1165     /**
1166 dl 1.2 * Returns the approximate number of threads that are actively
1167 tim 1.1 * executing tasks.
1168     *
1169     * @return the number of threads
1170     */
1171 tim 1.10 public int getActiveCount() {
1172 dl 1.2 mainLock.lock();
1173     try {
1174     int n = 0;
1175     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1176     if (it.next().isActive())
1177     ++n;
1178     }
1179     return n;
1180 tim 1.14 } finally {
1181 dl 1.2 mainLock.unlock();
1182     }
1183     }
1184 tim 1.1
1185     /**
1186 dl 1.2 * Returns the largest number of threads that have ever
1187     * simultaneously been in the pool.
1188 tim 1.1 *
1189     * @return the number of threads
1190     */
1191 tim 1.10 public int getLargestPoolSize() {
1192 dl 1.2 mainLock.lock();
1193     try {
1194     return largestPoolSize;
1195 tim 1.14 } finally {
1196 dl 1.2 mainLock.unlock();
1197     }
1198     }
1199 tim 1.1
1200     /**
1201 dl 1.2 * Returns the approximate total number of tasks that have been
1202     * scheduled for execution. Because the states of tasks and
1203     * threads may change dynamically during computation, the returned
1204 dl 1.17 * value is only an approximation, but one that does not ever
1205     * decrease across successive calls.
1206 tim 1.1 *
1207     * @return the number of tasks
1208     */
1209 tim 1.10 public long getTaskCount() {
1210 dl 1.2 mainLock.lock();
1211     try {
1212     long n = completedTaskCount;
1213     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1214     Worker w = it.next();
1215     n += w.completedTasks;
1216     if (w.isActive())
1217     ++n;
1218     }
1219     return n + workQueue.size();
1220 tim 1.14 } finally {
1221 dl 1.2 mainLock.unlock();
1222     }
1223     }
1224 tim 1.1
1225     /**
1226 dl 1.2 * Returns the approximate total number of tasks that have
1227     * completed execution. Because the states of tasks and threads
1228     * may change dynamically during computation, the returned value
1229 dl 1.17 * is only an approximation, but one that does not ever decrease
1230     * across successive calls.
1231 tim 1.1 *
1232     * @return the number of tasks
1233     */
1234 tim 1.10 public long getCompletedTaskCount() {
1235 dl 1.2 mainLock.lock();
1236     try {
1237     long n = completedTaskCount;
1238 tim 1.10 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
1239 dl 1.2 n += it.next().completedTasks;
1240     return n;
1241 tim 1.14 } finally {
1242 dl 1.2 mainLock.unlock();
1243     }
1244     }
1245 tim 1.1
1246     /**
1247 dl 1.17 * Method invoked prior to executing the given Runnable in the
1248     * given thread. This method may be used to re-initialize
1249     * ThreadLocals, or to perform logging. Note: To properly nest
1250     * multiple overridings, subclasses should generally invoke
1251 dl 1.5 * <tt>super.beforeExecute</tt> at the end of this method.
1252 tim 1.1 *
1253 dl 1.2 * @param t the thread that will run task r.
1254     * @param r the task that will be executed.
1255 tim 1.1 */
1256 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1257 tim 1.1
1258     /**
1259 dl 1.2 * Method invoked upon completion of execution of the given
1260     * Runnable. If non-null, the Throwable is the uncaught exception
1261 dl 1.5 * that caused execution to terminate abruptly. Note: To properly
1262     * nest multiple overridings, subclasses should generally invoke
1263     * <tt>super.afterExecute</tt> at the beginning of this method.
1264 tim 1.1 *
1265 dl 1.2 * @param r the runnable that has completed.
1266 dl 1.24 * @param t the exception that caused termination, or null if
1267 dl 1.2 * execution completed normally.
1268 tim 1.1 */
1269 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1270 tim 1.1
1271 dl 1.2 /**
1272     * Method invoked when the Executor has terminated. Default
1273 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1274     * overridings, subclasses should generally invoke
1275     * <tt>super.terminated</tt> within this method.
1276 dl 1.2 */
1277     protected void terminated() { }
1278 tim 1.1
1279     /**
1280 dl 1.21 * A handler for rejected tasks that runs the rejected task
1281     * directly in the calling thread of the <tt>execute</tt> method,
1282     * unless the executor has been shut down, in which case the task
1283     * is discarded.
1284 tim 1.1 */
1285 dl 1.2 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1286 tim 1.1
1287     /**
1288 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1289 tim 1.1 */
1290     public CallerRunsPolicy() { }
1291    
1292 dl 1.24 /**
1293     * Executes task r in the caller's thread, unless the executor
1294     * has been shut down, in which case the task is discarded.
1295     * @param r the runnable task requested to be executed
1296     * @param e the executor attempting to execute this task
1297     */
1298 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1299     if (!e.isShutdown()) {
1300 tim 1.1 r.run();
1301     }
1302     }
1303     }
1304    
1305     /**
1306 dl 1.21 * A handler for rejected tasks that throws a
1307 dl 1.8 * <tt>RejectedExecutionException</tt>.
1308 tim 1.1 */
1309 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1310 tim 1.1
1311     /**
1312 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1313 tim 1.1 */
1314     public AbortPolicy() { }
1315    
1316 dl 1.24 /**
1317     * Always throws RejectedExecutionException
1318     * @param r the runnable task requested to be executed
1319     * @param e the executor attempting to execute this task
1320     * @throws RejectedExecutionException always.
1321     */
1322 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1323     throw new RejectedExecutionException();
1324 tim 1.1 }
1325     }
1326    
1327     /**
1328 dl 1.21 * A handler for rejected tasks that silently discards the
1329     * rejected task.
1330 tim 1.1 */
1331 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1332 tim 1.1
1333     /**
1334 dl 1.24 * Creates <tt>DiscardPolicy</tt>.
1335 tim 1.1 */
1336     public DiscardPolicy() { }
1337    
1338 dl 1.24 /**
1339     * Does nothing, which has the effect of discarding task r.
1340     * @param r the runnable task requested to be executed
1341     * @param e the executor attempting to execute this task
1342     */
1343 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1344 tim 1.1 }
1345     }
1346    
1347     /**
1348 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1349     * request and then retries <tt>execute</tt>, unless the executor
1350     * is shut down, in which case the task is discarded.
1351 tim 1.1 */
1352 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1353 tim 1.1 /**
1354 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1355 tim 1.1 */
1356     public DiscardOldestPolicy() { }
1357    
1358 dl 1.24 /**
1359     * Obtains and ignores the next task that the executor
1360     * would otherwise execute, if one is immediately available,
1361     * and then retries execution of task r, unless the executor
1362     * is shut down, in which case task r is instead discarded.
1363     * @param r the runnable task requested to be executed
1364     * @param e the executor attempting to execute this task
1365     */
1366 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1367     if (!e.isShutdown()) {
1368     e.getQueue().poll();
1369     e.execute(r);
1370 tim 1.1 }
1371     }
1372     }
1373     }