ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.19
Committed: Sun Aug 31 13:33:14 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.18: +41 -58 lines
Log Message:
Removed non-standard tags and misc javadoc cleanup

File Contents

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