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