ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.33
Committed: Sat Oct 25 13:15:18 2003 UTC (20 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.32: +68 -19 lines
Log Message:
added DefaultThreadPoolFactory as static protected class

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     * {@link DefaultThreadFactory} is used, that creates threads to all
77     * 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     * Timeout in nanosecods for idle threads waiting for work.
250     * 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     * The default rejectect execution handler
314     */
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     /**
326 dl 1.33 * The default thread factory used to create new threads. This
327     * factory creates all new threads used by the Executor in the
328     * same {@link ThreadGroup}. If there is a {@link
329     * java.lang.SecurityManager}, it uses the group of {@link
330     * System#getSecurityManager}, else the group of the thread
331     * creating the Executor. Each new thread is created as a
332     * non-daemon thread with priority
333     * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
334     * accessible via {@link Thread#getName} of
335     * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
336     * number of this factory, and <em>M</em> is the sequence number
337     * of the thread created by this factory.
338     */
339     protected static class DefaultThreadFactory implements ThreadFactory {
340     private static final AtomicInteger poolNumber = new AtomicInteger(1);
341     private final ThreadGroup group;
342     private final AtomicInteger threadNumber = new AtomicInteger(1);
343     private final String namePrefix;
344    
345     /**
346     * Create a new DefaultThreadFactory that will create Threads
347     * with the group of the current System SecurityManager's
348     * ThreadGroup if it exists, else the group of the
349     * thread invoking this constructor.
350     */
351     public DefaultThreadFactory() {
352     SecurityManager s = System.getSecurityManager();
353     group = (s != null)? s.getThreadGroup() :
354     Thread.currentThread().getThreadGroup();
355     namePrefix = "pool-" +
356     poolNumber.getAndIncrement() +
357     "-thread-";
358     }
359    
360     /**
361     * Create and return a new Thread with ThreadGroup established
362     * in constructor, with non-daemon status, with normal
363     * priority, and with name displaying the factory and thread
364     * sequence numbers.
365     * @param r a runnable to be executed by new thread instance
366     * @return constructed thread
367     */
368     public Thread newThread(Runnable r) {
369     Thread t = new Thread(group, r,
370     namePrefix + threadNumber.getAndIncrement(),
371     0);
372     if (t.isDaemon())
373     t.setDaemon(false);
374     if (t.getPriority() != Thread.NORM_PRIORITY)
375     t.setPriority(Thread.NORM_PRIORITY);
376     return t;
377     }
378     }
379    
380    
381     /**
382 dl 1.2 * Create and return a new thread running firstTask as its first
383     * task. Call only while holding mainLock
384 dl 1.8 * @param firstTask the task the new thread should run first (or
385     * null if none)
386     * @return the new thread
387 dl 1.2 */
388     private Thread addThread(Runnable firstTask) {
389     Worker w = new Worker(firstTask);
390     Thread t = threadFactory.newThread(w);
391     w.thread = t;
392     workers.add(w);
393     int nt = ++poolSize;
394     if (nt > largestPoolSize)
395     largestPoolSize = nt;
396     return t;
397     }
398    
399 dl 1.16
400 dl 1.15
401 dl 1.2 /**
402     * Create and start a new thread running firstTask as its first
403     * task, only if less than corePoolSize threads are running.
404 dl 1.8 * @param firstTask the task the new thread should run first (or
405     * null if none)
406 dl 1.2 * @return true if successful.
407     */
408 dl 1.16 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
409 dl 1.2 Thread t = null;
410     mainLock.lock();
411     try {
412 tim 1.10 if (poolSize < corePoolSize)
413 dl 1.8 t = addThread(firstTask);
414 tim 1.14 } finally {
415 dl 1.2 mainLock.unlock();
416     }
417     if (t == null)
418     return false;
419     t.start();
420     return true;
421     }
422    
423     /**
424     * Create and start a new thread only if less than maximumPoolSize
425     * threads are running. The new thread runs as its first task the
426     * next task in queue, or if there is none, the given task.
427 dl 1.8 * @param firstTask the task the new thread should run first (or
428     * null if none)
429 dl 1.2 * @return null on failure, else the first task to be run by new thread.
430     */
431 dl 1.8 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
432 dl 1.2 Thread t = null;
433     Runnable next = null;
434     mainLock.lock();
435     try {
436     if (poolSize < maximumPoolSize) {
437     next = workQueue.poll();
438     if (next == null)
439 dl 1.8 next = firstTask;
440 dl 1.2 t = addThread(next);
441     }
442 tim 1.14 } finally {
443 dl 1.2 mainLock.unlock();
444     }
445     if (t == null)
446     return null;
447     t.start();
448     return next;
449     }
450    
451    
452     /**
453     * Get the next task for a worker thread to run.
454 dl 1.8 * @return the task
455     * @throws InterruptedException if interrupted while waiting for task
456 dl 1.2 */
457     private Runnable getTask() throws InterruptedException {
458     for (;;) {
459 dl 1.16 switch(runState) {
460     case RUNNING: {
461     if (poolSize <= corePoolSize) // untimed wait if core
462     return workQueue.take();
463    
464     long timeout = keepAliveTime;
465     if (timeout <= 0) // die immediately for 0 timeout
466     return null;
467     Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
468     if (r != null)
469     return r;
470     if (poolSize > corePoolSize) // timed out
471     return null;
472     // else, after timeout, pool shrank so shouldn't die, so retry
473     break;
474     }
475    
476     case SHUTDOWN: {
477     // Help drain queue
478     Runnable r = workQueue.poll();
479     if (r != null)
480     return r;
481    
482     // Check if can terminate
483     if (workQueue.isEmpty()) {
484     interruptIdleWorkers();
485     return null;
486     }
487    
488     // There could still be delayed tasks in queue.
489     // Wait for one, re-checking state upon interruption
490     try {
491     return workQueue.take();
492     }
493     catch(InterruptedException ignore) {
494     }
495     break;
496     }
497    
498     case STOP:
499 dl 1.2 return null;
500 dl 1.16 default:
501     assert false;
502     }
503     }
504     }
505    
506     /**
507     * Wake up all threads that might be waiting for tasks.
508     */
509     void interruptIdleWorkers() {
510     mainLock.lock();
511     try {
512     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
513     it.next().interruptIfIdle();
514     } finally {
515     mainLock.unlock();
516 dl 1.2 }
517     }
518    
519     /**
520     * Perform bookkeeping for a terminated worker thread.
521 tim 1.10 * @param w the worker
522 dl 1.2 */
523     private void workerDone(Worker w) {
524     mainLock.lock();
525     try {
526     completedTaskCount += w.completedTasks;
527     workers.remove(w);
528 tim 1.10 if (--poolSize > 0)
529 dl 1.2 return;
530    
531 dl 1.16 // Else, this is the last thread. Deal with potential shutdown.
532    
533     int state = runState;
534     assert state != TERMINATED;
535 tim 1.10
536 dl 1.16 if (state != STOP) {
537     // If there are queued tasks but no threads, create
538     // replacement.
539 dl 1.2 Runnable r = workQueue.poll();
540     if (r != null) {
541     addThread(r).start();
542     return;
543     }
544 dl 1.16
545     // If there are some (presumably delayed) tasks but
546     // none pollable, create an idle replacement to wait.
547     if (!workQueue.isEmpty()) {
548     addThread(null).start();
549     return;
550     }
551    
552     // Otherwise, we can exit without replacement
553     if (state == RUNNING)
554     return;
555 dl 1.2 }
556    
557 dl 1.16 // Either state is STOP, or state is SHUTDOWN and there is
558     // no work to do. So we can terminate.
559     runState = TERMINATED;
560 dl 1.2 termination.signalAll();
561 dl 1.16 // fall through to call terminate() outside of lock.
562 tim 1.14 } finally {
563 dl 1.2 mainLock.unlock();
564     }
565    
566 dl 1.16 assert runState == TERMINATED;
567     terminated();
568 dl 1.2 }
569    
570     /**
571 tim 1.10 * Worker threads
572 dl 1.2 */
573     private class Worker implements Runnable {
574    
575     /**
576     * The runLock is acquired and released surrounding each task
577     * execution. It mainly protects against interrupts that are
578     * intended to cancel the worker thread from instead
579     * interrupting the task being run.
580     */
581     private final ReentrantLock runLock = new ReentrantLock();
582    
583     /**
584     * Initial task to run before entering run loop
585     */
586     private Runnable firstTask;
587    
588     /**
589     * Per thread completed task counter; accumulated
590     * into completedTaskCount upon termination.
591     */
592     volatile long completedTasks;
593    
594     /**
595     * Thread this worker is running in. Acts as a final field,
596     * but cannot be set until thread is created.
597     */
598     Thread thread;
599    
600     Worker(Runnable firstTask) {
601     this.firstTask = firstTask;
602     }
603    
604     boolean isActive() {
605     return runLock.isLocked();
606     }
607    
608     /**
609     * Interrupt thread if not running a task
610 tim 1.10 */
611 dl 1.2 void interruptIfIdle() {
612     if (runLock.tryLock()) {
613     try {
614     thread.interrupt();
615 tim 1.14 } finally {
616 dl 1.2 runLock.unlock();
617     }
618     }
619     }
620    
621     /**
622     * Cause thread to die even if running a task.
623 tim 1.10 */
624 dl 1.2 void interruptNow() {
625     thread.interrupt();
626     }
627    
628     /**
629     * Run a single task between before/after methods.
630     */
631     private void runTask(Runnable task) {
632     runLock.lock();
633     try {
634     // Abort now if immediate cancel. Otherwise, we have
635     // committed to run this task.
636 dl 1.16 if (runState == STOP)
637 dl 1.2 return;
638    
639     Thread.interrupted(); // clear interrupt status on entry
640     boolean ran = false;
641     beforeExecute(thread, task);
642     try {
643     task.run();
644     ran = true;
645     afterExecute(task, null);
646     ++completedTasks;
647 tim 1.14 } catch(RuntimeException ex) {
648 dl 1.2 if (!ran)
649     afterExecute(task, ex);
650 dl 1.17 // Else the exception occurred within
651 dl 1.2 // afterExecute itself in which case we don't
652     // want to call it again.
653     throw ex;
654     }
655 tim 1.14 } finally {
656 dl 1.2 runLock.unlock();
657     }
658     }
659    
660     /**
661     * Main run loop
662     */
663     public void run() {
664     try {
665     for (;;) {
666     Runnable task;
667     if (firstTask != null) {
668     task = firstTask;
669     firstTask = null;
670 tim 1.14 } else {
671 dl 1.2 task = getTask();
672     if (task == null)
673     break;
674     }
675     runTask(task);
676     task = null; // unnecessary but can help GC
677     }
678 tim 1.14 } catch(InterruptedException ie) {
679 dl 1.2 // fall through
680 tim 1.14 } finally {
681 dl 1.2 workerDone(this);
682     }
683     }
684     }
685 tim 1.1
686 dl 1.17 // Public methods
687    
688 tim 1.1 /**
689 dl 1.17 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
690     * initial parameters. It may be more convenient to use one of
691 dholmes 1.18 * the {@link Executors} factory methods instead of this general
692 dl 1.17 * purpose constructor.
693 tim 1.1 *
694 dl 1.2 * @param corePoolSize the number of threads to keep in the
695 tim 1.1 * pool, even if they are idle.
696 dl 1.2 * @param maximumPoolSize the maximum number of threads to allow in the
697 tim 1.1 * pool.
698     * @param keepAliveTime when the number of threads is greater than
699 dl 1.2 * the core, this is the maximum time that excess idle threads
700 tim 1.1 * will wait for new tasks before terminating.
701 dl 1.2 * @param unit the time unit for the keepAliveTime
702 tim 1.1 * argument.
703     * @param workQueue the queue to use for holding tasks before the
704     * are executed. This queue will hold only the <tt>Runnable</tt>
705     * tasks submitted by the <tt>execute</tt> method.
706 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
707     * keepAliveTime less than zero, or if maximumPoolSize less than or
708     * equal to zero, or if corePoolSize greater than maximumPoolSize.
709 tim 1.1 * @throws NullPointerException if <tt>workQueue</tt> is null
710     */
711 dl 1.2 public ThreadPoolExecutor(int corePoolSize,
712     int maximumPoolSize,
713 tim 1.1 long keepAliveTime,
714 dl 1.2 TimeUnit unit,
715     BlockingQueue<Runnable> workQueue) {
716 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
717 dl 1.33 new DefaultThreadFactory(), defaultHandler);
718 dl 1.2 }
719 tim 1.1
720 dl 1.2 /**
721     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
722     * parameters.
723     *
724     * @param corePoolSize the number of threads to keep in the
725     * pool, even if they are idle.
726     * @param maximumPoolSize the maximum number of threads to allow in the
727     * pool.
728     * @param keepAliveTime when the number of threads is greater than
729     * the core, this is the maximum time that excess idle threads
730     * will wait for new tasks before terminating.
731     * @param unit the time unit for the keepAliveTime
732     * argument.
733     * @param workQueue the queue to use for holding tasks before the
734     * are executed. This queue will hold only the <tt>Runnable</tt>
735     * tasks submitted by the <tt>execute</tt> method.
736     * @param threadFactory the factory to use when the executor
737 tim 1.10 * creates a new thread.
738 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
739     * keepAliveTime less than zero, or if maximumPoolSize less than or
740     * equal to zero, or if corePoolSize greater than maximumPoolSize.
741 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
742 dl 1.2 * or <tt>threadFactory</tt> are null.
743     */
744     public ThreadPoolExecutor(int corePoolSize,
745     int maximumPoolSize,
746     long keepAliveTime,
747     TimeUnit unit,
748     BlockingQueue<Runnable> workQueue,
749     ThreadFactory threadFactory) {
750 tim 1.1
751 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
752 dl 1.2 threadFactory, defaultHandler);
753     }
754 tim 1.1
755 dl 1.2 /**
756     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
757     * parameters.
758     *
759     * @param corePoolSize the number of threads to keep in the
760     * pool, even if they are idle.
761     * @param maximumPoolSize the maximum number of threads to allow in the
762     * pool.
763     * @param keepAliveTime when the number of threads is greater than
764     * the core, this is the maximum time that excess idle threads
765     * will wait for new tasks before terminating.
766     * @param unit the time unit for the keepAliveTime
767     * argument.
768     * @param workQueue the queue to use for holding tasks before the
769     * are executed. This queue will hold only the <tt>Runnable</tt>
770     * tasks submitted by the <tt>execute</tt> method.
771     * @param handler the handler to use when execution is blocked
772     * because the thread bounds and queue capacities are reached.
773     * @throws IllegalArgumentException if corePoolSize, or
774     * keepAliveTime less than zero, or if maximumPoolSize less than or
775     * equal to zero, or if corePoolSize greater than maximumPoolSize.
776 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
777 dl 1.2 * or <tt>handler</tt> are null.
778     */
779     public ThreadPoolExecutor(int corePoolSize,
780     int maximumPoolSize,
781     long keepAliveTime,
782     TimeUnit unit,
783     BlockingQueue<Runnable> workQueue,
784     RejectedExecutionHandler handler) {
785 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
786 dl 1.33 new DefaultThreadFactory(), handler);
787 dl 1.2 }
788 tim 1.1
789 dl 1.2 /**
790     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
791     * parameters.
792     *
793     * @param corePoolSize the number of threads to keep in the
794     * pool, even if they are idle.
795     * @param maximumPoolSize the maximum number of threads to allow in the
796     * pool.
797     * @param keepAliveTime when the number of threads is greater than
798     * the core, this is the maximum time that excess idle threads
799     * will wait for new tasks before terminating.
800     * @param unit the time unit for the keepAliveTime
801     * argument.
802     * @param workQueue the queue to use for holding tasks before the
803     * are executed. This queue will hold only the <tt>Runnable</tt>
804     * tasks submitted by the <tt>execute</tt> method.
805     * @param threadFactory the factory to use when the executor
806 tim 1.10 * creates a new thread.
807 dl 1.2 * @param handler the handler to use when execution is blocked
808     * because the thread bounds and queue capacities are reached.
809     * @throws IllegalArgumentException if corePoolSize, or
810     * keepAliveTime less than zero, or if maximumPoolSize less than or
811     * equal to zero, or if corePoolSize greater than maximumPoolSize.
812 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
813 dl 1.2 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
814     */
815     public ThreadPoolExecutor(int corePoolSize,
816     int maximumPoolSize,
817     long keepAliveTime,
818     TimeUnit unit,
819     BlockingQueue<Runnable> workQueue,
820     ThreadFactory threadFactory,
821     RejectedExecutionHandler handler) {
822 tim 1.10 if (corePoolSize < 0 ||
823 dl 1.2 maximumPoolSize <= 0 ||
824 tim 1.10 maximumPoolSize < corePoolSize ||
825 dl 1.2 keepAliveTime < 0)
826     throw new IllegalArgumentException();
827     if (workQueue == null || threadFactory == null || handler == null)
828     throw new NullPointerException();
829     this.corePoolSize = corePoolSize;
830     this.maximumPoolSize = maximumPoolSize;
831     this.workQueue = workQueue;
832     this.keepAliveTime = unit.toNanos(keepAliveTime);
833     this.threadFactory = threadFactory;
834     this.handler = handler;
835 tim 1.1 }
836    
837 dl 1.2
838     /**
839     * Executes the given task sometime in the future. The task
840     * may execute in a new thread or in an existing pooled thread.
841     *
842     * If the task cannot be submitted for execution, either because this
843     * executor has been shutdown or because its capacity has been reached,
844 tim 1.10 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
845 dl 1.2 *
846     * @param command the task to execute
847     * @throws RejectedExecutionException at discretion of
848 dl 1.8 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
849     * for execution
850 dl 1.26 * @throws NullPointerException if command is null
851 dl 1.2 */
852 tim 1.10 public void execute(Runnable command) {
853 dl 1.26 if (command == null)
854     throw new NullPointerException();
855 dl 1.2 for (;;) {
856 dl 1.16 if (runState != RUNNING) {
857 dl 1.13 reject(command);
858 dl 1.2 return;
859     }
860     if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
861     return;
862     if (workQueue.offer(command))
863     return;
864     Runnable r = addIfUnderMaximumPoolSize(command);
865     if (r == command)
866     return;
867     if (r == null) {
868 dl 1.13 reject(command);
869 dl 1.2 return;
870     }
871     // else retry
872     }
873 tim 1.1 }
874 dl 1.4
875 dl 1.2 public void shutdown() {
876 dl 1.25 boolean fullyTerminated = false;
877 dl 1.2 mainLock.lock();
878     try {
879 dl 1.25 if (workers.size() > 0) {
880     if (runState == RUNNING) // don't override shutdownNow
881     runState = SHUTDOWN;
882     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
883     it.next().interruptIfIdle();
884     }
885     else { // If no workers, trigger full termination now
886     fullyTerminated = true;
887     runState = TERMINATED;
888     termination.signalAll();
889     }
890 tim 1.14 } finally {
891 dl 1.2 mainLock.unlock();
892     }
893 dl 1.25 if (fullyTerminated)
894     terminated();
895 tim 1.1 }
896    
897 dl 1.16
898 dl 1.2 public List shutdownNow() {
899 dl 1.25 boolean fullyTerminated = false;
900 dl 1.2 mainLock.lock();
901     try {
902 dl 1.25 if (workers.size() > 0) {
903     if (runState != TERMINATED)
904     runState = STOP;
905     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
906     it.next().interruptNow();
907     }
908     else { // If no workers, trigger full termination now
909     fullyTerminated = true;
910     runState = TERMINATED;
911     termination.signalAll();
912     }
913 tim 1.14 } finally {
914 dl 1.2 mainLock.unlock();
915     }
916 dl 1.25 if (fullyTerminated)
917     terminated();
918 dl 1.2 return Arrays.asList(workQueue.toArray());
919 tim 1.1 }
920    
921 dl 1.2 public boolean isShutdown() {
922 dl 1.16 return runState != RUNNING;
923     }
924    
925     /**
926     * Return true if this executor is in the process of terminating
927     * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
928     * completely terminated. This method may be useful for
929     * debugging. A return of <tt>true</tt> reported a sufficient
930     * period after shutdown may indicate that submitted tasks have
931     * ignored or suppressed interruption, causing this executor not
932     * to properly terminate.
933     * @return true if terminating but not yet terminated.
934     */
935     public boolean isTerminating() {
936     return runState == STOP;
937 tim 1.1 }
938    
939 dl 1.2 public boolean isTerminated() {
940 dl 1.16 return runState == TERMINATED;
941 dl 1.2 }
942 tim 1.1
943 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
944     throws InterruptedException {
945     mainLock.lock();
946     try {
947 dl 1.25 long nanos = unit.toNanos(timeout);
948     for (;;) {
949     if (runState == TERMINATED)
950     return true;
951     if (nanos <= 0)
952     return false;
953     nanos = termination.awaitNanos(nanos);
954     }
955 tim 1.14 } finally {
956 dl 1.2 mainLock.unlock();
957     }
958 dl 1.15 }
959    
960     /**
961     * Invokes <tt>shutdown</tt> when this executor is no longer
962     * referenced.
963     */
964     protected void finalize() {
965     shutdown();
966 dl 1.2 }
967 tim 1.10
968 dl 1.2 /**
969     * Sets the thread factory used to create new threads.
970     *
971     * @param threadFactory the new thread factory
972 dl 1.30 * @throws NullPointerException if threadFactory is null
973 tim 1.11 * @see #getThreadFactory
974 dl 1.2 */
975     public void setThreadFactory(ThreadFactory threadFactory) {
976 dl 1.30 if (threadFactory == null)
977     throw new NullPointerException();
978 dl 1.2 this.threadFactory = threadFactory;
979 tim 1.1 }
980    
981 dl 1.2 /**
982     * Returns the thread factory used to create new threads.
983     *
984     * @return the current thread factory
985 tim 1.11 * @see #setThreadFactory
986 dl 1.2 */
987     public ThreadFactory getThreadFactory() {
988     return threadFactory;
989 tim 1.1 }
990    
991 dl 1.2 /**
992     * Sets a new handler for unexecutable tasks.
993     *
994     * @param handler the new handler
995 dl 1.31 * @throws NullPointerException if handler is null
996 tim 1.11 * @see #getRejectedExecutionHandler
997 dl 1.2 */
998     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
999 dl 1.31 if (handler == null)
1000     throw new NullPointerException();
1001 dl 1.2 this.handler = handler;
1002     }
1003 tim 1.1
1004 dl 1.2 /**
1005     * Returns the current handler for unexecutable tasks.
1006     *
1007     * @return the current handler
1008 tim 1.11 * @see #setRejectedExecutionHandler
1009 dl 1.2 */
1010     public RejectedExecutionHandler getRejectedExecutionHandler() {
1011     return handler;
1012 tim 1.1 }
1013    
1014 dl 1.2 /**
1015 dl 1.17 * Returns the task queue used by this executor. Access to the
1016     * task queue is intended primarily for debugging and monitoring.
1017 dl 1.27 * This queue may be in active use. Retrieving the task queue
1018 dl 1.2 * does not prevent queued tasks from executing.
1019     *
1020     * @return the task queue
1021     */
1022     public BlockingQueue<Runnable> getQueue() {
1023     return workQueue;
1024 tim 1.1 }
1025 dl 1.4
1026     /**
1027     * Removes this task from internal queue if it is present, thus
1028     * causing it not to be run if it has not already started. This
1029     * method may be useful as one part of a cancellation scheme.
1030 tim 1.10 *
1031 dl 1.8 * @param task the task to remove
1032     * @return true if the task was removed
1033 dl 1.4 */
1034 dl 1.5 public boolean remove(Runnable task) {
1035 dl 1.4 return getQueue().remove(task);
1036     }
1037    
1038 dl 1.7
1039     /**
1040 dl 1.16 * Tries to remove from the work queue all {@link Cancellable}
1041     * tasks that have been cancelled. This method can be useful as a
1042     * storage reclamation operation, that has no other impact on
1043     * functionality. Cancelled tasks are never executed, but may
1044     * accumulate in work queues until worker threads can actively
1045     * remove them. Invoking this method instead tries to remove them now.
1046 dl 1.23 * However, this method may fail to remove tasks in
1047 dl 1.16 * the presence of interference by other threads.
1048 dl 1.7 */
1049    
1050     public void purge() {
1051 dl 1.16 // Fail if we encounter interference during traversal
1052     try {
1053     Iterator<Runnable> it = getQueue().iterator();
1054     while (it.hasNext()) {
1055     Runnable r = it.next();
1056     if (r instanceof Cancellable) {
1057     Cancellable c = (Cancellable)r;
1058     if (c.isCancelled())
1059     it.remove();
1060     }
1061 dl 1.7 }
1062     }
1063 dl 1.16 catch(ConcurrentModificationException ex) {
1064     return;
1065     }
1066 dl 1.7 }
1067 tim 1.1
1068     /**
1069 dl 1.2 * Sets the core number of threads. This overrides any value set
1070     * in the constructor. If the new value is smaller than the
1071     * current value, excess existing threads will be terminated when
1072     * they next become idle.
1073 tim 1.1 *
1074 dl 1.2 * @param corePoolSize the new core size
1075 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1076 dl 1.8 * less than zero
1077 tim 1.11 * @see #getCorePoolSize
1078 tim 1.1 */
1079 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1080     if (corePoolSize < 0)
1081     throw new IllegalArgumentException();
1082     mainLock.lock();
1083     try {
1084     int extra = this.corePoolSize - corePoolSize;
1085     this.corePoolSize = corePoolSize;
1086     if (extra > 0 && poolSize > corePoolSize) {
1087     Iterator<Worker> it = workers.iterator();
1088 tim 1.10 while (it.hasNext() &&
1089     extra > 0 &&
1090 dl 1.2 poolSize > corePoolSize &&
1091     workQueue.remainingCapacity() == 0) {
1092     it.next().interruptIfIdle();
1093     --extra;
1094     }
1095     }
1096 tim 1.10
1097 tim 1.14 } finally {
1098 dl 1.2 mainLock.unlock();
1099     }
1100     }
1101 tim 1.1
1102     /**
1103 dl 1.2 * Returns the core number of threads.
1104 tim 1.1 *
1105 dl 1.2 * @return the core number of threads
1106 tim 1.11 * @see #setCorePoolSize
1107 tim 1.1 */
1108 tim 1.10 public int getCorePoolSize() {
1109 dl 1.2 return corePoolSize;
1110 dl 1.16 }
1111    
1112     /**
1113     * Start a core thread, causing it to idly wait for work. This
1114     * overrides the default policy of starting core threads only when
1115     * new tasks are executed. This method will return <tt>false</tt>
1116     * if all core threads have already been started.
1117     * @return true if a thread was started
1118     */
1119     public boolean prestartCoreThread() {
1120     return addIfUnderCorePoolSize(null);
1121     }
1122    
1123     /**
1124     * Start all core threads, causing them to idly wait for work. This
1125     * overrides the default policy of starting core threads only when
1126     * new tasks are executed.
1127     * @return the number of threads started.
1128     */
1129     public int prestartAllCoreThreads() {
1130     int n = 0;
1131     while (addIfUnderCorePoolSize(null))
1132     ++n;
1133     return n;
1134 dl 1.2 }
1135 tim 1.1
1136     /**
1137     * Sets the maximum allowed number of threads. This overrides any
1138 dl 1.2 * value set in the constructor. If the new value is smaller than
1139     * the current value, excess existing threads will be
1140     * terminated when they next become idle.
1141 tim 1.1 *
1142 dl 1.2 * @param maximumPoolSize the new maximum
1143     * @throws IllegalArgumentException if maximumPoolSize less than zero or
1144     * the {@link #getCorePoolSize core pool size}
1145 tim 1.11 * @see #getMaximumPoolSize
1146 dl 1.2 */
1147     public void setMaximumPoolSize(int maximumPoolSize) {
1148     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1149     throw new IllegalArgumentException();
1150     mainLock.lock();
1151     try {
1152     int extra = this.maximumPoolSize - maximumPoolSize;
1153     this.maximumPoolSize = maximumPoolSize;
1154     if (extra > 0 && poolSize > maximumPoolSize) {
1155     Iterator<Worker> it = workers.iterator();
1156 tim 1.10 while (it.hasNext() &&
1157     extra > 0 &&
1158 dl 1.2 poolSize > maximumPoolSize) {
1159     it.next().interruptIfIdle();
1160     --extra;
1161     }
1162     }
1163 tim 1.14 } finally {
1164 dl 1.2 mainLock.unlock();
1165     }
1166     }
1167 tim 1.1
1168     /**
1169     * Returns the maximum allowed number of threads.
1170     *
1171 dl 1.2 * @return the maximum allowed number of threads
1172 tim 1.11 * @see #setMaximumPoolSize
1173 tim 1.1 */
1174 tim 1.10 public int getMaximumPoolSize() {
1175 dl 1.2 return maximumPoolSize;
1176     }
1177 tim 1.1
1178     /**
1179     * Sets the time limit for which threads may remain idle before
1180 dl 1.2 * being terminated. If there are more than the core number of
1181 tim 1.1 * threads currently in the pool, after waiting this amount of
1182     * time without processing a task, excess threads will be
1183     * terminated. This overrides any value set in the constructor.
1184     * @param time the time to wait. A time value of zero will cause
1185     * excess threads to terminate immediately after executing tasks.
1186 dl 1.2 * @param unit the time unit of the time argument
1187 dl 1.17 * @throws IllegalArgumentException if time less than zero
1188 tim 1.11 * @see #getKeepAliveTime
1189 tim 1.1 */
1190 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1191     if (time < 0)
1192     throw new IllegalArgumentException();
1193     this.keepAliveTime = unit.toNanos(time);
1194     }
1195 tim 1.1
1196     /**
1197     * Returns the thread keep-alive time, which is the amount of time
1198 dl 1.2 * which threads in excess of the core pool size may remain
1199 tim 1.10 * idle before being terminated.
1200 tim 1.1 *
1201 dl 1.2 * @param unit the desired time unit of the result
1202 tim 1.1 * @return the time limit
1203 tim 1.11 * @see #setKeepAliveTime
1204 tim 1.1 */
1205 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1206 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1207     }
1208 tim 1.1
1209     /* Statistics */
1210    
1211     /**
1212     * Returns the current number of threads in the pool.
1213     *
1214     * @return the number of threads
1215     */
1216 tim 1.10 public int getPoolSize() {
1217 dl 1.2 return poolSize;
1218     }
1219 tim 1.1
1220     /**
1221 dl 1.2 * Returns the approximate number of threads that are actively
1222 tim 1.1 * executing tasks.
1223     *
1224     * @return the number of threads
1225     */
1226 tim 1.10 public int getActiveCount() {
1227 dl 1.2 mainLock.lock();
1228     try {
1229     int n = 0;
1230     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1231     if (it.next().isActive())
1232     ++n;
1233     }
1234     return n;
1235 tim 1.14 } finally {
1236 dl 1.2 mainLock.unlock();
1237     }
1238     }
1239 tim 1.1
1240     /**
1241 dl 1.2 * Returns the largest number of threads that have ever
1242     * simultaneously been in the pool.
1243 tim 1.1 *
1244     * @return the number of threads
1245     */
1246 tim 1.10 public int getLargestPoolSize() {
1247 dl 1.2 mainLock.lock();
1248     try {
1249     return largestPoolSize;
1250 tim 1.14 } finally {
1251 dl 1.2 mainLock.unlock();
1252     }
1253     }
1254 tim 1.1
1255     /**
1256 dl 1.2 * Returns the approximate total number of tasks that have been
1257     * scheduled for execution. Because the states of tasks and
1258     * threads may change dynamically during computation, the returned
1259 dl 1.17 * value is only an approximation, but one that does not ever
1260     * decrease across successive calls.
1261 tim 1.1 *
1262     * @return the number of tasks
1263     */
1264 tim 1.10 public long getTaskCount() {
1265 dl 1.2 mainLock.lock();
1266     try {
1267     long n = completedTaskCount;
1268     for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1269     Worker w = it.next();
1270     n += w.completedTasks;
1271     if (w.isActive())
1272     ++n;
1273     }
1274     return n + workQueue.size();
1275 tim 1.14 } finally {
1276 dl 1.2 mainLock.unlock();
1277     }
1278     }
1279 tim 1.1
1280     /**
1281 dl 1.2 * Returns the approximate total number of tasks that have
1282     * completed execution. Because the states of tasks and threads
1283     * may change dynamically during computation, the returned value
1284 dl 1.17 * is only an approximation, but one that does not ever decrease
1285     * across successive calls.
1286 tim 1.1 *
1287     * @return the number of tasks
1288     */
1289 tim 1.10 public long getCompletedTaskCount() {
1290 dl 1.2 mainLock.lock();
1291     try {
1292     long n = completedTaskCount;
1293 tim 1.10 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
1294 dl 1.2 n += it.next().completedTasks;
1295     return n;
1296 tim 1.14 } finally {
1297 dl 1.2 mainLock.unlock();
1298     }
1299     }
1300 tim 1.1
1301     /**
1302 dl 1.17 * Method invoked prior to executing the given Runnable in the
1303     * given thread. This method may be used to re-initialize
1304     * ThreadLocals, or to perform logging. Note: To properly nest
1305     * multiple overridings, subclasses should generally invoke
1306 dl 1.5 * <tt>super.beforeExecute</tt> at the end of this method.
1307 tim 1.1 *
1308 dl 1.2 * @param t the thread that will run task r.
1309     * @param r the task that will be executed.
1310 tim 1.1 */
1311 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1312 tim 1.1
1313     /**
1314 dl 1.2 * Method invoked upon completion of execution of the given
1315     * Runnable. If non-null, the Throwable is the uncaught exception
1316 dl 1.5 * that caused execution to terminate abruptly. Note: To properly
1317     * nest multiple overridings, subclasses should generally invoke
1318     * <tt>super.afterExecute</tt> at the beginning of this method.
1319 tim 1.1 *
1320 dl 1.2 * @param r the runnable that has completed.
1321 dl 1.24 * @param t the exception that caused termination, or null if
1322 dl 1.2 * execution completed normally.
1323 tim 1.1 */
1324 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1325 tim 1.1
1326 dl 1.2 /**
1327     * Method invoked when the Executor has terminated. Default
1328 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1329     * overridings, subclasses should generally invoke
1330     * <tt>super.terminated</tt> within this method.
1331 dl 1.2 */
1332     protected void terminated() { }
1333 tim 1.1
1334     /**
1335 dl 1.21 * A handler for rejected tasks that runs the rejected task
1336     * directly in the calling thread of the <tt>execute</tt> method,
1337     * unless the executor has been shut down, in which case the task
1338     * is discarded.
1339 tim 1.1 */
1340 dl 1.2 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1341 tim 1.1
1342     /**
1343 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1344 tim 1.1 */
1345     public CallerRunsPolicy() { }
1346    
1347 dl 1.24 /**
1348     * Executes task r in the caller's thread, unless the executor
1349     * has been shut down, in which case the task is discarded.
1350     * @param r the runnable task requested to be executed
1351     * @param e the executor attempting to execute this task
1352     */
1353 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1354     if (!e.isShutdown()) {
1355 tim 1.1 r.run();
1356     }
1357     }
1358     }
1359    
1360     /**
1361 dl 1.21 * A handler for rejected tasks that throws a
1362 dl 1.8 * <tt>RejectedExecutionException</tt>.
1363 tim 1.1 */
1364 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1365 tim 1.1
1366     /**
1367 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1368 tim 1.1 */
1369     public AbortPolicy() { }
1370    
1371 dl 1.24 /**
1372     * Always throws RejectedExecutionException
1373     * @param r the runnable task requested to be executed
1374     * @param e the executor attempting to execute this task
1375     * @throws RejectedExecutionException always.
1376     */
1377 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1378     throw new RejectedExecutionException();
1379 tim 1.1 }
1380     }
1381    
1382     /**
1383 dl 1.21 * A handler for rejected tasks that silently discards the
1384     * rejected task.
1385 tim 1.1 */
1386 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1387 tim 1.1
1388     /**
1389 dl 1.24 * Creates <tt>DiscardPolicy</tt>.
1390 tim 1.1 */
1391     public DiscardPolicy() { }
1392    
1393 dl 1.24 /**
1394     * Does nothing, which has the effect of discarding task r.
1395     * @param r the runnable task requested to be executed
1396     * @param e the executor attempting to execute this task
1397     */
1398 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1399 tim 1.1 }
1400     }
1401    
1402     /**
1403 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1404     * request and then retries <tt>execute</tt>, unless the executor
1405     * is shut down, in which case the task is discarded.
1406 tim 1.1 */
1407 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1408 tim 1.1 /**
1409 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1410 tim 1.1 */
1411     public DiscardOldestPolicy() { }
1412    
1413 dl 1.24 /**
1414     * Obtains and ignores the next task that the executor
1415     * would otherwise execute, if one is immediately available,
1416     * and then retries execution of task r, unless the executor
1417     * is shut down, in which case task r is instead discarded.
1418     * @param r the runnable task requested to be executed
1419     * @param e the executor attempting to execute this task
1420     */
1421 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1422     if (!e.isShutdown()) {
1423     e.getQueue().poll();
1424     e.execute(r);
1425 tim 1.1 }
1426     }
1427     }
1428     }