ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.43
Committed: Fri Dec 19 14:42:25 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.42: +96 -10 lines
Log Message:
Documentation improvements

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