ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.7
Committed: Wed Jun 11 13:17:21 2003 UTC (21 years ago) by dl
Branch: MAIN
Changes since 1.6: +23 -1 lines
Log Message:
Removed automatic queue removal on cancel; Added TPE purge; Fixed RL typo

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