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

# Content
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 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.locks.*;
9 import java.util.*;
10
11 /**
12 * An {@link ExecutorService} that executes each submitted task using
13 * one of possibly several pooled threads.
14 *
15 * <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 * <p>To be useful across a wide range of contexts, this class
22 * 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 * {@link Executors} factory methods <tt>newCachedThreadPool</tt>
28 * (unbounded thread pool, with automatic thread reclamation),
29 * <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 *
39 * <h3>Tuning guide</h3>
40 * <dl>
41 *
42 * <dt>Core and maximum pool size</dt>
43 *
44 * <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 * </dd>
56 *
57 * <dt>Keep-alive</dt>
58 *
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 * <dt>Queueing</dt>
65 *
66 * <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 *
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 * 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 * </dd>
95 *
96 * <dt>Creating new threads</dt>
97 *
98 * <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 *
104 * <dt>Before and after intercepts</dt>
105 *
106 * <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 *
111 * <dt>Rejected tasks</dt>
112 *
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 * 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 *
123 * </dl>
124 *
125 * @since 1.5
126 * @author Doug Lea
127 */
128 public class ThreadPoolExecutor implements ExecutorService {
129 /**
130 * Queue used for holding tasks and handing off to worker threads.
131 */
132 private final BlockingQueue<Runnable> workQueue;
133
134 /**
135 * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
136 * workers set.
137 */
138 private final ReentrantLock mainLock = new ReentrantLock();
139
140 /**
141 * Wait condition to support awaitTermination
142 */
143 private final Condition termination = mainLock.newCondition();
144
145 /**
146 * Set containing all worker threads in pool.
147 */
148 private final HashSet<Worker> workers = new HashSet<Worker>();
149
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 */
155 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 */
162 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 */
169 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 */
176 private volatile int poolSize;
177
178 /**
179 * Lifecycle state
180 */
181 private volatile int runState;
182
183 // Special values for runState
184 /** Normal, not-shutdown mode */
185 private static final int RUNNING = 0;
186 /** Controlled shutdown mode */
187 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
193 /**
194 * Handler called when saturated or shutdown in execute.
195 */
196 private volatile RejectedExecutionHandler handler = defaultHandler;
197
198 /**
199 * Factory for new threads.
200 */
201 private volatile ThreadFactory threadFactory = defaultThreadFactory;
202
203 /**
204 * Tracks largest attained pool size.
205 */
206 private int largestPoolSize;
207
208 /**
209 * Counter for completed tasks. Updated only on termination of
210 * worker threads.
211 */
212 private long completedTaskCount;
213
214 /**
215 * The default thread factory
216 */
217 private static final ThreadFactory defaultThreadFactory =
218 new ThreadFactory() {
219 public Thread newThread(Runnable r) {
220 return new Thread(r);
221 }
222 };
223
224 /**
225 * The default rejectect execution handler
226 */
227 private static final RejectedExecutionHandler defaultHandler =
228 new AbortPolicy();
229
230 /**
231 * Invoke the rejected execution handler for the given command.
232 */
233 void reject(Runnable command) {
234 handler.rejectedExecution(command, this);
235 }
236
237 /**
238 * Create and return a new thread running firstTask as its first
239 * task. Call only while holding mainLock
240 * @param firstTask the task the new thread should run first (or
241 * null if none)
242 * @return the new thread
243 */
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
256
257 /**
258 * Create and start a new thread running firstTask as its first
259 * task, only if less than corePoolSize threads are running.
260 * @param firstTask the task the new thread should run first (or
261 * null if none)
262 * @return true if successful.
263 */
264 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
265 Thread t = null;
266 mainLock.lock();
267 try {
268 if (poolSize < corePoolSize)
269 t = addThread(firstTask);
270 } finally {
271 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 * @param firstTask the task the new thread should run first (or
284 * null if none)
285 * @return null on failure, else the first task to be run by new thread.
286 */
287 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
288 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 next = firstTask;
296 t = addThread(next);
297 }
298 } finally {
299 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 * @return the task
311 * @throws InterruptedException if interrupted while waiting for task
312 */
313 private Runnable getTask() throws InterruptedException {
314 for (;;) {
315 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 return null;
356 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 }
373 }
374
375 /**
376 * Perform bookkeeping for a terminated worker thread.
377 * @param w the worker
378 */
379 private void workerDone(Worker w) {
380 mainLock.lock();
381 try {
382 completedTaskCount += w.completedTasks;
383 workers.remove(w);
384 if (--poolSize > 0)
385 return;
386
387 // Else, this is the last thread. Deal with potential shutdown.
388
389 int state = runState;
390 assert state != TERMINATED;
391
392 if (state != STOP) {
393 // If there are queued tasks but no threads, create
394 // replacement.
395 Runnable r = workQueue.poll();
396 if (r != null) {
397 addThread(r).start();
398 return;
399 }
400
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 }
412
413 // Either state is STOP, or state is SHUTDOWN and there is
414 // no work to do. So we can terminate.
415 runState = TERMINATED;
416 termination.signalAll();
417 // fall through to call terminate() outside of lock.
418 } finally {
419 mainLock.unlock();
420 }
421
422 assert runState == TERMINATED;
423 terminated();
424 }
425
426 /**
427 * Worker threads
428 */
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 */
467 void interruptIfIdle() {
468 if (runLock.tryLock()) {
469 try {
470 thread.interrupt();
471 } finally {
472 runLock.unlock();
473 }
474 }
475 }
476
477 /**
478 * Cause thread to die even if running a task.
479 */
480 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 if (runState == STOP)
493 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 } catch(RuntimeException ex) {
504 if (!ran)
505 afterExecute(task, ex);
506 // Else the exception occurred within
507 // afterExecute itself in which case we don't
508 // want to call it again.
509 throw ex;
510 }
511 } finally {
512 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 } else {
527 task = getTask();
528 if (task == null)
529 break;
530 }
531 runTask(task);
532 task = null; // unnecessary but can help GC
533 }
534 } catch(InterruptedException ie) {
535 // fall through
536 } finally {
537 workerDone(this);
538 }
539 }
540 }
541
542 // Public methods
543
544 /**
545 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
546 * initial parameters. It may be more convenient to use one of
547 * the {@link Executors} factory methods instead of this general
548 * purpose constructor.
549 *
550 * @param corePoolSize the number of threads to keep in the
551 * pool, even if they are idle.
552 * @param maximumPoolSize the maximum number of threads to allow in the
553 * pool.
554 * @param keepAliveTime when the number of threads is greater than
555 * the core, this is the maximum time that excess idle threads
556 * will wait for new tasks before terminating.
557 * @param unit the time unit for the keepAliveTime
558 * 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 * @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 * @throws NullPointerException if <tt>workQueue</tt> is null
566 */
567 public ThreadPoolExecutor(int corePoolSize,
568 int maximumPoolSize,
569 long keepAliveTime,
570 TimeUnit unit,
571 BlockingQueue<Runnable> workQueue) {
572 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
573 defaultThreadFactory, defaultHandler);
574 }
575
576 /**
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 * creates a new thread.
594 * @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 * @throws NullPointerException if <tt>workQueue</tt>
598 * 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
607 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
608 threadFactory, defaultHandler);
609 }
610
611 /**
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 * @throws NullPointerException if <tt>workQueue</tt>
633 * 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 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
642 defaultThreadFactory, handler);
643 }
644
645 /**
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 * creates a new thread.
663 * @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 * @throws NullPointerException if <tt>workQueue</tt>
669 * 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 if (corePoolSize < 0 ||
679 maximumPoolSize <= 0 ||
680 maximumPoolSize < corePoolSize ||
681 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 }
692
693
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 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
701 *
702 * @param command the task to execute
703 * @throws RejectedExecutionException at discretion of
704 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
705 * for execution
706 */
707 public void execute(Runnable command) {
708 for (;;) {
709 if (runState != RUNNING) {
710 reject(command);
711 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 reject(command);
722 return;
723 }
724 // else retry
725 }
726 }
727
728 public void shutdown() {
729 mainLock.lock();
730 try {
731 if (runState == RUNNING) // don't override shutdownNow
732 runState = SHUTDOWN;
733 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
734 it.next().interruptIfIdle();
735 } finally {
736 mainLock.unlock();
737 }
738 }
739
740
741 public List shutdownNow() {
742 mainLock.lock();
743 try {
744 if (runState != TERMINATED)
745 runState = STOP;
746 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
747 it.next().interruptNow();
748 } finally {
749 mainLock.unlock();
750 }
751 return Arrays.asList(workQueue.toArray());
752 }
753
754 public boolean isShutdown() {
755 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 }
771
772 public boolean isTerminated() {
773 return runState == TERMINATED;
774 }
775
776 public boolean awaitTermination(long timeout, TimeUnit unit)
777 throws InterruptedException {
778 mainLock.lock();
779 try {
780 return termination.await(timeout, unit);
781 } finally {
782 mainLock.unlock();
783 }
784 }
785
786 /**
787 * Invokes <tt>shutdown</tt> when this executor is no longer
788 * referenced.
789 */
790 protected void finalize() {
791 shutdown();
792 }
793
794 /**
795 * Sets the thread factory used to create new threads.
796 *
797 * @param threadFactory the new thread factory
798 * @see #getThreadFactory
799 */
800 public void setThreadFactory(ThreadFactory threadFactory) {
801 this.threadFactory = threadFactory;
802 }
803
804 /**
805 * Returns the thread factory used to create new threads.
806 *
807 * @return the current thread factory
808 * @see #setThreadFactory
809 */
810 public ThreadFactory getThreadFactory() {
811 return threadFactory;
812 }
813
814 /**
815 * Sets a new handler for unexecutable tasks.
816 *
817 * @param handler the new handler
818 * @see #getRejectedExecutionHandler
819 */
820 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
821 this.handler = handler;
822 }
823
824 /**
825 * Returns the current handler for unexecutable tasks.
826 *
827 * @return the current handler
828 * @see #setRejectedExecutionHandler
829 */
830 public RejectedExecutionHandler getRejectedExecutionHandler() {
831 return handler;
832 }
833
834 /**
835 * 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 * does not prevent queued tasks from executing.
839 *
840 * @return the task queue
841 */
842 public BlockingQueue<Runnable> getQueue() {
843 return workQueue;
844 }
845
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 *
851 * @param task the task to remove
852 * @return true if the task was removed
853 */
854 public boolean remove(Runnable task) {
855 return getQueue().remove(task);
856 }
857
858
859 /**
860 * 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 */
869
870 public void purge() {
871 // 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 }
882 }
883 catch(ConcurrentModificationException ex) {
884 return;
885 }
886 }
887
888 /**
889 * 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 *
894 * @param corePoolSize the new core size
895 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
896 * less than zero
897 * @see #getCorePoolSize
898 */
899 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 while (it.hasNext() &&
909 extra > 0 &&
910 poolSize > corePoolSize &&
911 workQueue.remainingCapacity() == 0) {
912 it.next().interruptIfIdle();
913 --extra;
914 }
915 }
916
917 } finally {
918 mainLock.unlock();
919 }
920 }
921
922 /**
923 * Returns the core number of threads.
924 *
925 * @return the core number of threads
926 * @see #setCorePoolSize
927 */
928 public int getCorePoolSize() {
929 return corePoolSize;
930 }
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 }
955
956 /**
957 * Sets the maximum allowed number of threads. This overrides any
958 * 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 *
962 * @param maximumPoolSize the new maximum
963 * @throws IllegalArgumentException if maximumPoolSize less than zero or
964 * the {@link #getCorePoolSize core pool size}
965 * @see #getMaximumPoolSize
966 */
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 while (it.hasNext() &&
977 extra > 0 &&
978 poolSize > maximumPoolSize) {
979 it.next().interruptIfIdle();
980 --extra;
981 }
982 }
983 } finally {
984 mainLock.unlock();
985 }
986 }
987
988 /**
989 * Returns the maximum allowed number of threads.
990 *
991 * @return the maximum allowed number of threads
992 * @see #setMaximumPoolSize
993 */
994 public int getMaximumPoolSize() {
995 return maximumPoolSize;
996 }
997
998 /**
999 * Sets the time limit for which threads may remain idle before
1000 * being terminated. If there are more than the core number of
1001 * 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 * @param unit the time unit of the time argument
1007 * @throws IllegalArgumentException if time less than zero
1008 * @see #getKeepAliveTime
1009 */
1010 public void setKeepAliveTime(long time, TimeUnit unit) {
1011 if (time < 0)
1012 throw new IllegalArgumentException();
1013 this.keepAliveTime = unit.toNanos(time);
1014 }
1015
1016 /**
1017 * Returns the thread keep-alive time, which is the amount of time
1018 * which threads in excess of the core pool size may remain
1019 * idle before being terminated.
1020 *
1021 * @param unit the desired time unit of the result
1022 * @return the time limit
1023 * @see #setKeepAliveTime
1024 */
1025 public long getKeepAliveTime(TimeUnit unit) {
1026 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1027 }
1028
1029 /* Statistics */
1030
1031 /**
1032 * Returns the current number of threads in the pool.
1033 *
1034 * @return the number of threads
1035 */
1036 public int getPoolSize() {
1037 return poolSize;
1038 }
1039
1040 /**
1041 * Returns the approximate number of threads that are actively
1042 * executing tasks.
1043 *
1044 * @return the number of threads
1045 */
1046 public int getActiveCount() {
1047 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 } finally {
1056 mainLock.unlock();
1057 }
1058 }
1059
1060 /**
1061 * Returns the largest number of threads that have ever
1062 * simultaneously been in the pool.
1063 *
1064 * @return the number of threads
1065 */
1066 public int getLargestPoolSize() {
1067 mainLock.lock();
1068 try {
1069 return largestPoolSize;
1070 } finally {
1071 mainLock.unlock();
1072 }
1073 }
1074
1075 /**
1076 * 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 * value is only an approximation, but one that does not ever
1080 * decrease across successive calls.
1081 *
1082 * @return the number of tasks
1083 */
1084 public long getTaskCount() {
1085 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 } finally {
1096 mainLock.unlock();
1097 }
1098 }
1099
1100 /**
1101 * 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 * is only an approximation, but one that does not ever decrease
1105 * across successive calls.
1106 *
1107 * @return the number of tasks
1108 */
1109 public long getCompletedTaskCount() {
1110 mainLock.lock();
1111 try {
1112 long n = completedTaskCount;
1113 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
1114 n += it.next().completedTasks;
1115 return n;
1116 } finally {
1117 mainLock.unlock();
1118 }
1119 }
1120
1121 /**
1122 * 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 * <tt>super.beforeExecute</tt> at the end of this method.
1127 *
1128 * @param t the thread that will run task r.
1129 * @param r the task that will be executed.
1130 */
1131 protected void beforeExecute(Thread t, Runnable r) { }
1132
1133 /**
1134 * Method invoked upon completion of execution of the given
1135 * Runnable. If non-null, the Throwable is the uncaught exception
1136 * 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 *
1140 * @param r the runnable that has completed.
1141 * @param t the exception that cause termination, or null if
1142 * execution completed normally.
1143 */
1144 protected void afterExecute(Runnable r, Throwable t) { }
1145
1146 /**
1147 * Method invoked when the Executor has terminated. Default
1148 * implementation does nothing. Note: To properly nest multiple
1149 * overridings, subclasses should generally invoke
1150 * <tt>super.terminated</tt> within this method.
1151 */
1152 protected void terminated() { }
1153
1154 /**
1155 * 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 */
1159 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1160
1161 /**
1162 * Constructs a <tt>CallerRunsPolicy</tt>.
1163 */
1164 public CallerRunsPolicy() { }
1165
1166 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1167 if (!e.isShutdown()) {
1168 r.run();
1169 }
1170 }
1171 }
1172
1173 /**
1174 * A handler for unexecutable tasks that throws a
1175 * <tt>RejectedExecutionException</tt>.
1176 */
1177 public static class AbortPolicy implements RejectedExecutionHandler {
1178
1179 /**
1180 * Constructs a <tt>AbortPolicy</tt>.
1181 */
1182 public AbortPolicy() { }
1183
1184 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1185 throw new RejectedExecutionException();
1186 }
1187 }
1188
1189 /**
1190 * A handler for unexecutable tasks that waits until the task can be
1191 * submitted for execution.
1192 */
1193 public static class WaitPolicy implements RejectedExecutionHandler {
1194 /**
1195 * Constructs a <tt>WaitPolicy</tt>.
1196 */
1197 public WaitPolicy() { }
1198
1199 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1200 if (!e.isShutdown()) {
1201 try {
1202 e.getQueue().put(r);
1203 } catch (InterruptedException ie) {
1204 Thread.currentThread().interrupt();
1205 throw new RejectedExecutionException(ie);
1206 }
1207 }
1208 }
1209 }
1210
1211 /**
1212 * A handler for unexecutable tasks that silently discards these tasks.
1213 */
1214 public static class DiscardPolicy implements RejectedExecutionHandler {
1215
1216 /**
1217 * Constructs <tt>DiscardPolicy</tt>.
1218 */
1219 public DiscardPolicy() { }
1220
1221 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1222 }
1223 }
1224
1225 /**
1226 * A handler for unexecutable tasks that discards the oldest
1227 * unhandled request.
1228 */
1229 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1230 /**
1231 * Constructs a <tt>DiscardOldestPolicy</tt> for the given executor.
1232 */
1233 public DiscardOldestPolicy() { }
1234
1235 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1236 if (!e.isShutdown()) {
1237 e.getQueue().poll();
1238 e.execute(r);
1239 }
1240 }
1241 }
1242 }