ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.6
Committed: Fri Jun 6 18:42:18 2003 UTC (21 years ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRELIMINARY_TEST_RELEASE_1
Changes since 1.5: +15 -14 lines
Log Message:
Added to emulation
Fixed some javadoc format errors

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/03 16:44:36 $
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 * Sets the core number of threads. This overrides any value set
780 * in the constructor. If the new value is smaller than the
781 * current value, excess existing threads will be terminated when
782 * they next become idle.
783 *
784 * @param corePoolSize the new core size
785 * @throws IllegalArgumentException if <tt>corePoolSize</tt> less than zero
786 */
787 public void setCorePoolSize(int corePoolSize) {
788 if (corePoolSize < 0)
789 throw new IllegalArgumentException();
790 mainLock.lock();
791 try {
792 int extra = this.corePoolSize - corePoolSize;
793 this.corePoolSize = corePoolSize;
794 if (extra > 0 && poolSize > corePoolSize) {
795 Iterator<Worker> it = workers.iterator();
796 while (it.hasNext() &&
797 extra > 0 &&
798 poolSize > corePoolSize &&
799 workQueue.remainingCapacity() == 0) {
800 it.next().interruptIfIdle();
801 --extra;
802 }
803 }
804
805 }
806 finally {
807 mainLock.unlock();
808 }
809 }
810
811 /**
812 * Returns the core number of threads.
813 *
814 * @return the core number of threads
815 */
816 public int getCorePoolSize() {
817 return corePoolSize;
818 }
819
820 /**
821 * Sets the maximum allowed number of threads. This overrides any
822 * value set in the constructor. If the new value is smaller than
823 * the current value, excess existing threads will be
824 * terminated when they next become idle.
825 *
826 * @param maximumPoolSize the new maximum
827 * @throws IllegalArgumentException if maximumPoolSize less than zero or
828 * the {@link #getCorePoolSize core pool size}
829 */
830 public void setMaximumPoolSize(int maximumPoolSize) {
831 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
832 throw new IllegalArgumentException();
833 mainLock.lock();
834 try {
835 int extra = this.maximumPoolSize - maximumPoolSize;
836 this.maximumPoolSize = maximumPoolSize;
837 if (extra > 0 && poolSize > maximumPoolSize) {
838 Iterator<Worker> it = workers.iterator();
839 while (it.hasNext() &&
840 extra > 0 &&
841 poolSize > maximumPoolSize) {
842 it.next().interruptIfIdle();
843 --extra;
844 }
845 }
846 }
847 finally {
848 mainLock.unlock();
849 }
850 }
851
852 /**
853 * Returns the maximum allowed number of threads.
854 *
855 * @return the maximum allowed number of threads
856 */
857 public int getMaximumPoolSize() {
858 return maximumPoolSize;
859 }
860
861 /**
862 * Sets the time limit for which threads may remain idle before
863 * being terminated. If there are more than the core number of
864 * threads currently in the pool, after waiting this amount of
865 * time without processing a task, excess threads will be
866 * terminated. This overrides any value set in the constructor.
867 * @param time the time to wait. A time value of zero will cause
868 * excess threads to terminate immediately after executing tasks.
869 * @param unit the time unit of the time argument
870 * @throws IllegalArgumentException if msecs less than zero
871 */
872 public void setKeepAliveTime(long time, TimeUnit unit) {
873 if (time < 0)
874 throw new IllegalArgumentException();
875 this.keepAliveTime = unit.toNanos(time);
876 }
877
878 /**
879 * Returns the thread keep-alive time, which is the amount of time
880 * which threads in excess of the core pool size may remain
881 * idle before being terminated.
882 *
883 * @param unit the desired time unit of the result
884 * @return the time limit
885 */
886 public long getKeepAliveTime(TimeUnit unit) {
887 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
888 }
889
890 /* Statistics */
891
892 /**
893 * Returns the current number of threads in the pool.
894 *
895 * @return the number of threads
896 */
897 public int getPoolSize() {
898 return poolSize;
899 }
900
901 /**
902 * Returns the approximate number of threads that are actively
903 * executing tasks.
904 *
905 * @return the number of threads
906 */
907 public int getActiveCount() {
908 mainLock.lock();
909 try {
910 int n = 0;
911 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
912 if (it.next().isActive())
913 ++n;
914 }
915 return n;
916 }
917 finally {
918 mainLock.unlock();
919 }
920 }
921
922 /**
923 * Returns the largest number of threads that have ever
924 * simultaneously been in the pool.
925 *
926 * @return the number of threads
927 */
928 public int getLargestPoolSize() {
929 mainLock.lock();
930 try {
931 return largestPoolSize;
932 }
933 finally {
934 mainLock.unlock();
935 }
936 }
937
938 /**
939 * Returns the approximate total number of tasks that have been
940 * scheduled for execution. Because the states of tasks and
941 * threads may change dynamically during computation, the returned
942 * value is only an approximation.
943 *
944 * @return the number of tasks
945 */
946 public long getTaskCount() {
947 mainLock.lock();
948 try {
949 long n = completedTaskCount;
950 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
951 Worker w = it.next();
952 n += w.completedTasks;
953 if (w.isActive())
954 ++n;
955 }
956 return n + workQueue.size();
957 }
958 finally {
959 mainLock.unlock();
960 }
961 }
962
963 /**
964 * Returns the approximate total number of tasks that have
965 * completed execution. Because the states of tasks and threads
966 * may change dynamically during computation, the returned value
967 * is only an approximation.
968 *
969 * @return the number of tasks
970 */
971 public long getCompletedTaskCount() {
972 mainLock.lock();
973 try {
974 long n = completedTaskCount;
975 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
976 n += it.next().completedTasks;
977 return n;
978 }
979 finally {
980 mainLock.unlock();
981 }
982 }
983
984 /**
985 * Method invoked prior to executing the given Runnable in given
986 * thread. This method may be used to re-initialize ThreadLocals,
987 * or to perform logging. Note: To properly nest multiple
988 * overridings, subclasses should generally invoke
989 * <tt>super.beforeExecute</tt> at the end of this method.
990 *
991 * @param t the thread that will run task r.
992 * @param r the task that will be executed.
993 */
994 protected void beforeExecute(Thread t, Runnable r) { }
995
996 /**
997 * Method invoked upon completion of execution of the given
998 * Runnable. If non-null, the Throwable is the uncaught exception
999 * that caused execution to terminate abruptly. Note: To properly
1000 * nest multiple overridings, subclasses should generally invoke
1001 * <tt>super.afterExecute</tt> at the beginning of this method.
1002 *
1003 * @param r the runnable that has completed.
1004 * @param t the exception that cause termination, or null if
1005 * execution completed normally.
1006 */
1007 protected void afterExecute(Runnable r, Throwable t) { }
1008
1009 /**
1010 * Method invoked when the Executor has terminated. Default
1011 * implementation does nothing.
1012 */
1013 protected void terminated() { }
1014
1015 /**
1016 * A handler for unexecutable tasks that runs these tasks directly in the
1017 * calling thread of the <tt>execute</tt> method. This is the default
1018 * <tt>RejectedExecutionHandler</tt>.
1019 */
1020 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1021
1022 /**
1023 * Constructs a <tt>CallerRunsPolicy</tt>.
1024 */
1025 public CallerRunsPolicy() { }
1026
1027 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1028 if (!e.isShutdown()) {
1029 r.run();
1030 }
1031 }
1032 }
1033
1034 /**
1035 * A handler for unexecutable tasks that throws a <tt>RejectedExecutionException</tt>.
1036 */
1037 public static class AbortPolicy implements RejectedExecutionHandler {
1038
1039 /**
1040 * Constructs a <tt>AbortPolicy</tt>.
1041 */
1042 public AbortPolicy() { }
1043
1044 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1045 throw new RejectedExecutionException();
1046 }
1047 }
1048
1049 /**
1050 * A handler for unexecutable tasks that waits until the task can be
1051 * submitted for execution.
1052 */
1053 public static class WaitPolicy implements RejectedExecutionHandler {
1054 /**
1055 * Constructs a <tt>WaitPolicy</tt>.
1056 */
1057 public WaitPolicy() { }
1058
1059 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1060 if (!e.isShutdown()) {
1061 try {
1062 e.getQueue().put(r);
1063 }
1064 catch (InterruptedException ie) {
1065 Thread.currentThread().interrupt();
1066 throw new RejectedExecutionException(ie);
1067 }
1068 }
1069 }
1070 }
1071
1072 /**
1073 * A handler for unexecutable tasks that silently discards these tasks.
1074 */
1075 public static class DiscardPolicy implements RejectedExecutionHandler {
1076
1077 /**
1078 * Constructs <tt>DiscardPolicy</tt>.
1079 */
1080 public DiscardPolicy() { }
1081
1082 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1083 }
1084 }
1085
1086 /**
1087 * A handler for unexecutable tasks that discards the oldest unhandled request.
1088 */
1089 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1090 /**
1091 * Constructs a <tt>DiscardOldestPolicy</tt> for the given executor.
1092 */
1093 public DiscardOldestPolicy() { }
1094
1095 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1096 if (!e.isShutdown()) {
1097 e.getQueue().poll();
1098 e.execute(r);
1099 }
1100 }
1101 }
1102 }