ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.63
Committed: Tue Jan 4 00:07:26 2005 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.62: +39 -44 lines
Log Message:
Reduce need for replacing interrupted worker threads

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, as explained at
4 * http://creativecommons.org/licenses/publicdomain
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, normally configured
14 * using {@link Executors} factory methods.
15 *
16 * <p>Thread pools address two different problems: they usually
17 * provide improved performance when executing large numbers of
18 * asynchronous tasks, due to reduced per-task invocation overhead,
19 * and they provide a means of bounding and managing the resources,
20 * including threads, consumed when executing a collection of tasks.
21 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
22 * statistics, such as the number of completed tasks.
23 *
24 * <p>To be useful across a wide range of contexts, this class
25 * provides many adjustable parameters and extensibility
26 * hooks. However, programmers are urged to use the more convenient
27 * {@link Executors} factory methods {@link
28 * Executors#newCachedThreadPool} (unbounded thread pool, with
29 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
30 * (fixed size thread pool) and {@link
31 * Executors#newSingleThreadExecutor} (single background thread), that
32 * preconfigure settings for the most common usage
33 * scenarios. Otherwise, use the following guide when manually
34 * configuring and tuning this class:
35 *
36 * <dl>
37 *
38 * <dt>Core and maximum pool sizes</dt>
39 *
40 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
41 * pool size
42 * (see {@link ThreadPoolExecutor#getPoolSize})
43 * according to the bounds set by corePoolSize
44 * (see {@link ThreadPoolExecutor#getCorePoolSize})
45 * and
46 * maximumPoolSize
47 * (see {@link ThreadPoolExecutor#getMaximumPoolSize}).
48 * When a new task is submitted in method {@link
49 * ThreadPoolExecutor#execute}, 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
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. By setting maximumPoolSize to an essentially unbounded
56 * value such as <tt>Integer.MAX_VALUE</tt>, you allow the pool to
57 * accommodate an arbitrary number of concurrent tasks. Most typically,
58 * core and maximum pool sizes are set only upon construction, but they
59 * may also be changed dynamically using {@link
60 * ThreadPoolExecutor#setCorePoolSize} and {@link
61 * ThreadPoolExecutor#setMaximumPoolSize}. <dd>
62 *
63 * <dt> On-demand construction
64 *
65 * <dd> By default, even core threads are initially created and
66 * started only when needed by new tasks, but this can be overridden
67 * dynamically using method {@link
68 * ThreadPoolExecutor#prestartCoreThread} or
69 * {@link ThreadPoolExecutor#prestartAllCoreThreads}. </dd>
70 *
71 * <dt>Creating new threads</dt>
72 *
73 * <dd>New threads are created using a {@link
74 * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
75 * {@link Executors#defaultThreadFactory} is used, that creates threads to all
76 * be in the same {@link ThreadGroup} and with the same
77 * <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying
78 * a different ThreadFactory, you can alter the thread's name, thread
79 * group, priority, daemon status, etc. If a <tt>ThreadFactory</tt> fails to create
80 * a thread when asked by returning null from <tt>newThread</tt>,
81 * the executor will continue, but might
82 * not be able to execute any tasks. </dd>
83 *
84 * <dt>Keep-alive times</dt>
85 *
86 * <dd>If the pool currently has more than corePoolSize threads,
87 * excess threads will be terminated if they have been idle for more
88 * than the keepAliveTime (see {@link
89 * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
90 * reducing resource consumption when the pool is not being actively
91 * used. If the pool becomes more active later, new threads will be
92 * constructed. This parameter can also be changed dynamically using
93 * method {@link ThreadPoolExecutor#setKeepAliveTime}. Using a value
94 * of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS} effectively
95 * disables idle threads from ever terminating prior to shut down. By
96 * default, the keep-alive policy applies only when there are more
97 * than corePoolSizeThreads. But method {@link
98 * ThreadPoolExecutor#allowCoreThreadTimeOut} can be used to apply
99 * this time-out policy to core threads as well. </dd>
100 *
101 * <dt>Queuing</dt>
102 *
103 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
104 * submitted tasks. The use of this queue interacts with pool sizing:
105 *
106 * <ul>
107 *
108 * <li> If fewer than corePoolSize threads are running, the Executor
109 * always prefers adding a new thread
110 * rather than queuing.</li>
111 *
112 * <li> If corePoolSize or more threads are running, the Executor
113 * always prefers queuing a request rather than adding a new
114 * thread.</li>
115 *
116 * <li> If a request cannot be queued, a new thread is created unless
117 * this would exceed maximumPoolSize, in which case, the task will be
118 * rejected.</li>
119 *
120 * </ul>
121 *
122 * There are three general strategies for queuing:
123 * <ol>
124 *
125 * <li> <em> Direct handoffs.</em> A good default choice for a work
126 * queue is a {@link SynchronousQueue} that hands off tasks to threads
127 * without otherwise holding them. Here, an attempt to queue a task
128 * will fail if no threads are immediately available to run it, so a
129 * new thread will be constructed. This policy avoids lockups when
130 * handling sets of requests that might have internal dependencies.
131 * Direct handoffs generally require unbounded maximumPoolSizes to
132 * avoid rejection of new submitted tasks. This in turn admits the
133 * possibility of unbounded thread growth when commands continue to
134 * arrive on average faster than they can be processed. </li>
135 *
136 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
137 * example a {@link LinkedBlockingQueue} without a predefined
138 * capacity) will cause new tasks to be queued in cases where all
139 * corePoolSize threads are busy. Thus, no more than corePoolSize
140 * threads will ever be created. (And the value of the maximumPoolSize
141 * therefore doesn't have any effect.) This may be appropriate when
142 * each task is completely independent of others, so tasks cannot
143 * affect each others execution; for example, in a web page server.
144 * While this style of queuing can be useful in smoothing out
145 * transient bursts of requests, it admits the possibility of
146 * unbounded work queue growth when commands continue to arrive on
147 * average faster than they can be processed. </li>
148 *
149 * <li><em>Bounded queues.</em> A bounded queue (for example, an
150 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
151 * used with finite maximumPoolSizes, but can be more difficult to
152 * tune and control. Queue sizes and maximum pool sizes may be traded
153 * off for each other: Using large queues and small pools minimizes
154 * CPU usage, OS resources, and context-switching overhead, but can
155 * lead to artificially low throughput. If tasks frequently block (for
156 * example if they are I/O bound), a system may be able to schedule
157 * time for more threads than you otherwise allow. Use of small queues
158 * generally requires larger pool sizes, which keeps CPUs busier but
159 * may encounter unacceptable scheduling overhead, which also
160 * decreases throughput. </li>
161 *
162 * </ol>
163 *
164 * </dd>
165 *
166 * <dt>Rejected tasks</dt>
167 *
168 * <dd> New tasks submitted in method {@link
169 * ThreadPoolExecutor#execute} will be <em>rejected</em> when the
170 * Executor has been shut down, and also when the Executor uses finite
171 * bounds for both maximum threads and work queue capacity, and is
172 * saturated. In either case, the <tt>execute</tt> method invokes the
173 * {@link RejectedExecutionHandler#rejectedExecution} method of its
174 * {@link RejectedExecutionHandler}. Four predefined handler policies
175 * are provided:
176 *
177 * <ol>
178 *
179 * <li> In the
180 * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
181 * runtime {@link RejectedExecutionException} upon rejection. </li>
182 *
183 * <li> In {@link
184 * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
185 * <tt>execute</tt> itself runs the task. This provides a simple
186 * feedback control mechanism that will slow down the rate that new
187 * tasks are submitted. </li>
188 *
189 * <li> In {@link ThreadPoolExecutor.DiscardPolicy},
190 * a task that cannot be executed is simply dropped. </li>
191 *
192 * <li>In {@link
193 * ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not
194 * shut down, the task at the head of the work queue is dropped, and
195 * then execution is retried (which can fail again, causing this to be
196 * repeated.) </li>
197 *
198 * </ol>
199 *
200 * It is possible to define and use other kinds of {@link
201 * RejectedExecutionHandler} classes. Doing so requires some care
202 * especially when policies are designed to work only under particular
203 * capacity or queuing policies. </dd>
204 *
205 * <dt>Hook methods</dt>
206 *
207 * <dd>This class provides <tt>protected</tt> overridable {@link
208 * ThreadPoolExecutor#beforeExecute} and {@link
209 * ThreadPoolExecutor#afterExecute} methods that are called before and
210 * after execution of each task. These can be used to manipulate the
211 * execution environment; for example, reinitializing ThreadLocals,
212 * gathering statistics, or adding log entries. Additionally, method
213 * {@link ThreadPoolExecutor#terminated} can be overridden to perform
214 * any special processing that needs to be done once the Executor has
215 * fully terminated.
216 *
217 * <p>If hook or callback methods throw
218 * exceptions, internal worker threads may in turn fail and
219 * abruptly terminate.</dd>
220 *
221 * <dt>Queue maintenance</dt>
222 *
223 * <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to
224 * the work queue for purposes of monitoring and debugging. Use of
225 * this method for any other purpose is strongly discouraged. Two
226 * supplied methods, {@link ThreadPoolExecutor#remove} and {@link
227 * ThreadPoolExecutor#purge} are available to assist in storage
228 * reclamation when large numbers of queued tasks become
229 * cancelled.</dd> </dl>
230 *
231 * <p> <b>Extension example</b>. Most extensions of this class
232 * override one or more of the protected hook methods. For example,
233 * here is a subclass that adds a simple pause/resume feature:
234 *
235 * <pre>
236 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
237 * private boolean isPaused;
238 * private ReentrantLock pauseLock = new ReentrantLock();
239 * private Condition unpaused = pauseLock.newCondition();
240 *
241 * public PausableThreadPoolExecutor(...) { super(...); }
242 *
243 * protected void beforeExecute(Thread t, Runnable r) {
244 * super.beforeExecute(t, r);
245 * pauseLock.lock();
246 * try {
247 * while (isPaused) unpaused.await();
248 * } catch(InterruptedException ie) {
249 * t.interrupt();
250 * } finally {
251 * pauseLock.unlock();
252 * }
253 * }
254 *
255 * public void pause() {
256 * pauseLock.lock();
257 * try {
258 * isPaused = true;
259 * } finally {
260 * pauseLock.unlock();
261 * }
262 * }
263 *
264 * public void resume() {
265 * pauseLock.lock();
266 * try {
267 * isPaused = false;
268 * unpaused.signalAll();
269 * } finally {
270 * pauseLock.unlock();
271 * }
272 * }
273 * }
274 * </pre>
275 * @since 1.5
276 * @author Doug Lea
277 */
278 public class ThreadPoolExecutor extends AbstractExecutorService {
279 /**
280 * Only used to force toArray() to produce a Runnable[].
281 */
282 private static final Runnable[] EMPTY_RUNNABLE_ARRAY = new Runnable[0];
283
284 /**
285 * Permission for checking shutdown
286 */
287 private static final RuntimePermission shutdownPerm =
288 new RuntimePermission("modifyThread");
289
290 /**
291 * Queue used for holding tasks and handing off to worker threads.
292 */
293 private final BlockingQueue<Runnable> workQueue;
294
295 /**
296 * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
297 * workers set.
298 */
299 private final ReentrantLock mainLock = new ReentrantLock();
300
301 /**
302 * Wait condition to support awaitTermination
303 */
304 private final Condition termination = mainLock.newCondition();
305
306 /**
307 * Set containing all worker threads in pool.
308 */
309 private final HashSet<Worker> workers = new HashSet<Worker>();
310
311 /**
312 * Timeout in nanoseconds for idle threads waiting for work.
313 * Threads use this timeout only when there are more than
314 * corePoolSize present. Otherwise they wait forever for new work.
315 */
316 private volatile long keepAliveTime;
317
318 /**
319 * If false (default) core threads stay alive even when idle.
320 * If true, core threads use keepAliveTime to time out waiting for work.
321 */
322 private boolean allowCoreThreadTimeOut;
323
324 /**
325 * Core pool size, updated only while holding mainLock,
326 * but volatile to allow concurrent readability even
327 * during updates.
328 */
329 private volatile int corePoolSize;
330
331 /**
332 * Maximum pool size, updated only while holding mainLock
333 * but volatile to allow concurrent readability even
334 * during updates.
335 */
336 private volatile int maximumPoolSize;
337
338 /**
339 * Current pool size, updated only while holding mainLock
340 * but volatile to allow concurrent readability even
341 * during updates.
342 */
343 private volatile int poolSize;
344
345 /**
346 * Lifecycle state
347 */
348 volatile int runState;
349
350 // Special values for runState
351 /** Normal, not-shutdown mode */
352 static final int RUNNING = 0;
353 /** Controlled shutdown mode */
354 static final int SHUTDOWN = 1;
355 /** Immediate shutdown mode */
356 static final int STOP = 2;
357 /** Final state */
358 static final int TERMINATED = 3;
359
360 /**
361 * Handler called when saturated or shutdown in execute.
362 */
363 private volatile RejectedExecutionHandler handler;
364
365 /**
366 * Factory for new threads.
367 */
368 private volatile ThreadFactory threadFactory;
369
370 /**
371 * Tracks largest attained pool size.
372 */
373 private int largestPoolSize;
374
375 /**
376 * Counter for completed tasks. Updated only on termination of
377 * worker threads.
378 */
379 private long completedTaskCount;
380
381 /**
382 * The default rejected execution handler
383 */
384 private static final RejectedExecutionHandler defaultHandler =
385 new AbortPolicy();
386
387 /**
388 * Invoke the rejected execution handler for the given command.
389 */
390 void reject(Runnable command) {
391 handler.rejectedExecution(command, this);
392 }
393
394 /**
395 * Create and return a new thread running firstTask as its first
396 * task. Call only while holding mainLock
397 * @param firstTask the task the new thread should run first (or
398 * null if none)
399 * @return the new thread, or null if threadFactory fails to create thread
400 */
401 private Thread addThread(Runnable firstTask) {
402 Worker w = new Worker(firstTask);
403 Thread t = threadFactory.newThread(w);
404 if (t != null) {
405 w.thread = t;
406 workers.add(w);
407 int nt = ++poolSize;
408 if (nt > largestPoolSize)
409 largestPoolSize = nt;
410 }
411 return t;
412 }
413
414 /**
415 * Create and start a new thread running firstTask as its first
416 * task, only if fewer than corePoolSize threads are running.
417 * @param firstTask the task the new thread should run first (or
418 * null if none)
419 * @return true if successful.
420 */
421 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
422 Thread t = null;
423 final ReentrantLock mainLock = this.mainLock;
424 mainLock.lock();
425 try {
426 if (poolSize < corePoolSize)
427 t = addThread(firstTask);
428 } finally {
429 mainLock.unlock();
430 }
431 if (t == null)
432 return false;
433 t.start();
434 return true;
435 }
436
437 /**
438 * Create and start a new thread only if fewer than maximumPoolSize
439 * threads are running. The new thread runs as its first task the
440 * next task in queue, or if there is none, the given task.
441 * @param firstTask the task the new thread should run first (or
442 * null if none)
443 * @return null on failure, else the first task to be run by new thread.
444 */
445 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
446 Thread t = null;
447 Runnable next = null;
448 final ReentrantLock mainLock = this.mainLock;
449 mainLock.lock();
450 try {
451 if (poolSize < maximumPoolSize) {
452 next = workQueue.poll();
453 if (next == null)
454 next = firstTask;
455 t = addThread(next);
456 }
457 } finally {
458 mainLock.unlock();
459 }
460 if (t == null)
461 return null;
462 t.start();
463 return next;
464 }
465
466
467 /**
468 * Get the next task for a worker thread to run.
469 * @return the task
470 */
471 Runnable getTask() {
472 for (;;) {
473 try {
474 switch(runState) {
475 case RUNNING: {
476 // untimed wait if core and not allowing core timeout
477 if (poolSize <= corePoolSize && !allowCoreThreadTimeOut)
478 return workQueue.take();
479
480 long timeout = keepAliveTime;
481 if (timeout <= 0) // die immediately for 0 timeout
482 return null;
483 Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
484 if (r != null)
485 return r;
486 if (poolSize > corePoolSize || allowCoreThreadTimeOut)
487 return null; // timed out
488 // Else, after timeout, the pool shrank. Retry
489 break;
490 }
491
492 case SHUTDOWN: {
493 // Help drain queue
494 Runnable r = workQueue.poll();
495 if (r != null)
496 return r;
497
498 // Check if can terminate
499 if (workQueue.isEmpty()) {
500 interruptIdleWorkers();
501 return null;
502 }
503
504 // Else there could still be delayed tasks in queue.
505 return workQueue.take();
506 }
507
508 case STOP:
509 return null;
510 default:
511 assert false;
512 }
513 } catch(InterruptedException ie) {
514 // On interruption, re-check runstate
515 }
516 }
517 }
518
519 /**
520 * Wake up all threads that might be waiting for tasks.
521 */
522 void interruptIdleWorkers() {
523 final ReentrantLock mainLock = this.mainLock;
524 mainLock.lock();
525 try {
526 for (Worker w : workers)
527 w.interruptIfIdle();
528 } finally {
529 mainLock.unlock();
530 }
531 }
532
533 /**
534 * Perform bookkeeping for a terminated worker thread.
535 * @param w the worker
536 */
537 void workerDone(Worker w) {
538 final ReentrantLock mainLock = this.mainLock;
539 mainLock.lock();
540 try {
541 completedTaskCount += w.completedTasks;
542 workers.remove(w);
543 if (--poolSize > 0)
544 return;
545
546 // Else, this is the last thread. Deal with potential shutdown.
547
548 int state = runState;
549 assert state != TERMINATED;
550
551 if (state != STOP) {
552 // If there are queued tasks but no threads, create
553 // replacement thread. We must create it initially
554 // idle to avoid orphaned tasks in case addThread
555 // fails. This also handles case of delayed tasks
556 // that will sometime later become runnable.
557 if (!workQueue.isEmpty()) {
558 Thread t = addThread(null);
559 if (t != null)
560 t.start();
561 return;
562 }
563
564 // Otherwise, we can exit without replacement
565 if (state == RUNNING)
566 return;
567 }
568
569 // Either state is STOP, or state is SHUTDOWN and there is
570 // no work to do. So we can terminate.
571 termination.signalAll();
572 runState = TERMINATED;
573 // fall through to call terminate() outside of lock.
574 } finally {
575 mainLock.unlock();
576 }
577
578 assert runState == TERMINATED;
579 terminated();
580 }
581
582 /**
583 * Worker threads
584 */
585 private class Worker implements Runnable {
586
587 /**
588 * The runLock is acquired and released surrounding each task
589 * execution. It mainly protects against interrupts that are
590 * intended to cancel the worker thread from instead
591 * interrupting the task being run.
592 */
593 private final ReentrantLock runLock = new ReentrantLock();
594
595 /**
596 * Initial task to run before entering run loop
597 */
598 private Runnable firstTask;
599
600 /**
601 * Per thread completed task counter; accumulated
602 * into completedTaskCount upon termination.
603 */
604 volatile long completedTasks;
605
606 /**
607 * Thread this worker is running in. Acts as a final field,
608 * but cannot be set until thread is created.
609 */
610 Thread thread;
611
612 Worker(Runnable firstTask) {
613 this.firstTask = firstTask;
614 }
615
616 boolean isActive() {
617 return runLock.isLocked();
618 }
619
620 /**
621 * Interrupt thread if not running a task
622 */
623 void interruptIfIdle() {
624 final ReentrantLock runLock = this.runLock;
625 if (runLock.tryLock()) {
626 try {
627 thread.interrupt();
628 } finally {
629 runLock.unlock();
630 }
631 }
632 }
633
634 /**
635 * Interrupt thread even if running a task.
636 */
637 void interruptNow() {
638 thread.interrupt();
639 }
640
641 /**
642 * Run a single task between before/after methods.
643 */
644 private void runTask(Runnable task) {
645 final ReentrantLock runLock = this.runLock;
646 runLock.lock();
647 try {
648 // Abort now if immediate cancel. Otherwise, we have
649 // committed to run this task.
650 if (runState == STOP)
651 return;
652
653 Thread.interrupted(); // clear interrupt status on entry
654 boolean ran = false;
655 beforeExecute(thread, task);
656 try {
657 task.run();
658 ran = true;
659 afterExecute(task, null);
660 ++completedTasks;
661 } catch(RuntimeException ex) {
662 if (!ran)
663 afterExecute(task, ex);
664 // Else the exception occurred within
665 // afterExecute itself in which case we don't
666 // want to call it again.
667 throw ex;
668 }
669 } finally {
670 runLock.unlock();
671 }
672 }
673
674 /**
675 * Main run loop
676 */
677 public void run() {
678 try {
679 Runnable task = firstTask;
680 firstTask = null;
681 while (task != null || (task = getTask()) != null) {
682 runTask(task);
683 task = null; // unnecessary but can help GC
684 }
685 } finally {
686 workerDone(this);
687 }
688 }
689 }
690
691 // Public methods
692
693 /**
694 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
695 * initial parameters and default thread factory and handler. It
696 * may be more convenient to use one of the {@link Executors}
697 * factory methods instead of this general purpose constructor.
698 *
699 * @param corePoolSize the number of threads to keep in the
700 * pool, even if they are idle.
701 * @param maximumPoolSize the maximum number of threads to allow in the
702 * pool.
703 * @param keepAliveTime when the number of threads is greater than
704 * the core, this is the maximum time that excess idle threads
705 * will wait for new tasks before terminating.
706 * @param unit the time unit for the keepAliveTime
707 * argument.
708 * @param workQueue the queue to use for holding tasks before they
709 * are executed. This queue will hold only the <tt>Runnable</tt>
710 * tasks submitted by the <tt>execute</tt> method.
711 * @throws IllegalArgumentException if corePoolSize, or
712 * keepAliveTime less than zero, or if maximumPoolSize less than or
713 * equal to zero, or if corePoolSize greater than maximumPoolSize.
714 * @throws NullPointerException if <tt>workQueue</tt> is null
715 */
716 public ThreadPoolExecutor(int corePoolSize,
717 int maximumPoolSize,
718 long keepAliveTime,
719 TimeUnit unit,
720 BlockingQueue<Runnable> workQueue) {
721 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
722 Executors.defaultThreadFactory(), defaultHandler);
723 }
724
725 /**
726 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
727 * parameters.
728 *
729 * @param corePoolSize the number of threads to keep in the
730 * pool, even if they are idle.
731 * @param maximumPoolSize the maximum number of threads to allow in the
732 * pool.
733 * @param keepAliveTime when the number of threads is greater than
734 * the core, this is the maximum time that excess idle threads
735 * will wait for new tasks before terminating.
736 * @param unit the time unit for the keepAliveTime
737 * argument.
738 * @param workQueue the queue to use for holding tasks before they
739 * are executed. This queue will hold only the <tt>Runnable</tt>
740 * tasks submitted by the <tt>execute</tt> method.
741 * @param threadFactory the factory to use when the executor
742 * creates a new thread.
743 * @throws IllegalArgumentException if corePoolSize, or
744 * keepAliveTime less than zero, or if maximumPoolSize less than or
745 * equal to zero, or if corePoolSize greater than maximumPoolSize.
746 * @throws NullPointerException if <tt>workQueue</tt>
747 * or <tt>threadFactory</tt> are null.
748 */
749 public ThreadPoolExecutor(int corePoolSize,
750 int maximumPoolSize,
751 long keepAliveTime,
752 TimeUnit unit,
753 BlockingQueue<Runnable> workQueue,
754 ThreadFactory threadFactory) {
755 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
756 threadFactory, defaultHandler);
757 }
758
759 /**
760 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
761 * parameters.
762 *
763 * @param corePoolSize the number of threads to keep in the
764 * pool, even if they are idle.
765 * @param maximumPoolSize the maximum number of threads to allow in the
766 * pool.
767 * @param keepAliveTime when the number of threads is greater than
768 * the core, this is the maximum time that excess idle threads
769 * will wait for new tasks before terminating.
770 * @param unit the time unit for the keepAliveTime
771 * argument.
772 * @param workQueue the queue to use for holding tasks before they
773 * are executed. This queue will hold only the <tt>Runnable</tt>
774 * tasks submitted by the <tt>execute</tt> method.
775 * @param handler the handler to use when execution is blocked
776 * because the thread bounds and queue capacities are reached.
777 * @throws IllegalArgumentException if corePoolSize, or
778 * keepAliveTime less than zero, or if maximumPoolSize less than or
779 * equal to zero, or if corePoolSize greater than maximumPoolSize.
780 * @throws NullPointerException if <tt>workQueue</tt>
781 * or <tt>handler</tt> are null.
782 */
783 public ThreadPoolExecutor(int corePoolSize,
784 int maximumPoolSize,
785 long keepAliveTime,
786 TimeUnit unit,
787 BlockingQueue<Runnable> workQueue,
788 RejectedExecutionHandler handler) {
789 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
790 Executors.defaultThreadFactory(), handler);
791 }
792
793 /**
794 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
795 * parameters.
796 *
797 * @param corePoolSize the number of threads to keep in the
798 * pool, even if they are idle.
799 * @param maximumPoolSize the maximum number of threads to allow in the
800 * pool.
801 * @param keepAliveTime when the number of threads is greater than
802 * the core, this is the maximum time that excess idle threads
803 * will wait for new tasks before terminating.
804 * @param unit the time unit for the keepAliveTime
805 * argument.
806 * @param workQueue the queue to use for holding tasks before they
807 * are executed. This queue will hold only the <tt>Runnable</tt>
808 * tasks submitted by the <tt>execute</tt> method.
809 * @param threadFactory the factory to use when the executor
810 * creates a new thread.
811 * @param handler the handler to use when execution is blocked
812 * because the thread bounds and queue capacities are reached.
813 * @throws IllegalArgumentException if corePoolSize, or
814 * keepAliveTime less than zero, or if maximumPoolSize less than or
815 * equal to zero, or if corePoolSize greater than maximumPoolSize.
816 * @throws NullPointerException if <tt>workQueue</tt>
817 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
818 */
819 public ThreadPoolExecutor(int corePoolSize,
820 int maximumPoolSize,
821 long keepAliveTime,
822 TimeUnit unit,
823 BlockingQueue<Runnable> workQueue,
824 ThreadFactory threadFactory,
825 RejectedExecutionHandler handler) {
826 if (corePoolSize < 0 ||
827 maximumPoolSize <= 0 ||
828 maximumPoolSize < corePoolSize ||
829 keepAliveTime < 0)
830 throw new IllegalArgumentException();
831 if (workQueue == null || threadFactory == null || handler == null)
832 throw new NullPointerException();
833 this.corePoolSize = corePoolSize;
834 this.maximumPoolSize = maximumPoolSize;
835 this.workQueue = workQueue;
836 this.keepAliveTime = unit.toNanos(keepAliveTime);
837 this.threadFactory = threadFactory;
838 this.handler = handler;
839 }
840
841
842 /**
843 * Executes the given task sometime in the future. The task
844 * may execute in a new thread or in an existing pooled thread.
845 *
846 * If the task cannot be submitted for execution, either because this
847 * executor has been shutdown or because its capacity has been reached,
848 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
849 *
850 * @param command the task to execute
851 * @throws RejectedExecutionException at discretion of
852 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
853 * for execution
854 * @throws NullPointerException if command is null
855 */
856 public void execute(Runnable command) {
857 if (command == null)
858 throw new NullPointerException();
859 for (;;) {
860 if (runState != RUNNING) {
861 reject(command);
862 return;
863 }
864 if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
865 return;
866 if (workQueue.offer(command))
867 return;
868 Runnable r = addIfUnderMaximumPoolSize(command);
869 if (r == command)
870 return;
871 if (r == null) {
872 reject(command);
873 return;
874 }
875 // else retry
876 }
877 }
878
879 /**
880 * Initiates an orderly shutdown in which previously submitted
881 * tasks are executed, but no new tasks will be
882 * accepted. Invocation has no additional effect if already shut
883 * down.
884 * @throws SecurityException if a security manager exists and
885 * shutting down this ExecutorService may manipulate threads that
886 * the caller is not permitted to modify because it does not hold
887 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
888 * or the security manager's <tt>checkAccess</tt> method denies access.
889 */
890 public void shutdown() {
891 // Fail if caller doesn't have modifyThread permission. We
892 // explicitly check permissions directly because we can't trust
893 // implementations of SecurityManager to correctly override
894 // the "check access" methods such that our documented
895 // security policy is implemented.
896 SecurityManager security = System.getSecurityManager();
897 if (security != null)
898 java.security.AccessController.checkPermission(shutdownPerm);
899
900 boolean fullyTerminated = false;
901 final ReentrantLock mainLock = this.mainLock;
902 mainLock.lock();
903 try {
904 if (workers.size() > 0) {
905 // Check if caller can modify worker threads. This
906 // might not be true even if passed above check, if
907 // the SecurityManager treats some threads specially.
908 if (security != null) {
909 for (Worker w: workers)
910 security.checkAccess(w.thread);
911 }
912
913 int state = runState;
914 if (state == RUNNING) // don't override shutdownNow
915 runState = SHUTDOWN;
916
917 try {
918 for (Worker w: workers)
919 w.interruptIfIdle();
920 } catch(SecurityException se) {
921 // If SecurityManager allows above checks, but
922 // then unexpectedly throws exception when
923 // interrupting threads (which it ought not do),
924 // back out as cleanly as we can. Some threads may
925 // have been killed but we remain in non-shutdown
926 // state.
927 runState = state;
928 throw se;
929 }
930 }
931 else { // If no workers, trigger full termination now
932 fullyTerminated = true;
933 runState = TERMINATED;
934 termination.signalAll();
935 }
936 } finally {
937 mainLock.unlock();
938 }
939 if (fullyTerminated)
940 terminated();
941 }
942
943
944 /**
945 * Attempts to stop all actively executing tasks, halts the
946 * processing of waiting tasks, and returns a list of the tasks that were
947 * awaiting execution.
948 *
949 * <p>This implementation cancels tasks via {@link
950 * Thread#interrupt}, so if any tasks mask or fail to respond to
951 * interrupts, they may never terminate.
952 *
953 * @return list of tasks that never commenced execution
954 * @throws SecurityException if a security manager exists and
955 * shutting down this ExecutorService may manipulate threads that
956 * the caller is not permitted to modify because it does not hold
957 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
958 * or the security manager's <tt>checkAccess</tt> method denies access.
959 */
960 public List<Runnable> shutdownNow() {
961 // Almost the same code as shutdown()
962 SecurityManager security = System.getSecurityManager();
963 if (security != null)
964 java.security.AccessController.checkPermission(shutdownPerm);
965
966 boolean fullyTerminated = false;
967 final ReentrantLock mainLock = this.mainLock;
968 mainLock.lock();
969 try {
970 if (workers.size() > 0) {
971 if (security != null) {
972 for (Worker w: workers)
973 security.checkAccess(w.thread);
974 }
975
976 int state = runState;
977 if (state != TERMINATED)
978 runState = STOP;
979 try {
980 for (Worker w : workers)
981 w.interruptNow();
982 } catch(SecurityException se) {
983 runState = state; // back out;
984 throw se;
985 }
986 }
987 else { // If no workers, trigger full termination now
988 fullyTerminated = true;
989 runState = TERMINATED;
990 termination.signalAll();
991 }
992 } finally {
993 mainLock.unlock();
994 }
995 if (fullyTerminated)
996 terminated();
997 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
998 }
999
1000 public boolean isShutdown() {
1001 return runState != RUNNING;
1002 }
1003
1004 /**
1005 * Returns true if this executor is in the process of terminating
1006 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1007 * completely terminated. This method may be useful for
1008 * debugging. A return of <tt>true</tt> reported a sufficient
1009 * period after shutdown may indicate that submitted tasks have
1010 * ignored or suppressed interruption, causing this executor not
1011 * to properly terminate.
1012 * @return true if terminating but not yet terminated.
1013 */
1014 public boolean isTerminating() {
1015 return runState == STOP;
1016 }
1017
1018 public boolean isTerminated() {
1019 return runState == TERMINATED;
1020 }
1021
1022 public boolean awaitTermination(long timeout, TimeUnit unit)
1023 throws InterruptedException {
1024 long nanos = unit.toNanos(timeout);
1025 final ReentrantLock mainLock = this.mainLock;
1026 mainLock.lock();
1027 try {
1028 for (;;) {
1029 if (runState == TERMINATED)
1030 return true;
1031 if (nanos <= 0)
1032 return false;
1033 nanos = termination.awaitNanos(nanos);
1034 }
1035 } finally {
1036 mainLock.unlock();
1037 }
1038 }
1039
1040 /**
1041 * Invokes <tt>shutdown</tt> when this executor is no longer
1042 * referenced.
1043 */
1044 protected void finalize() {
1045 shutdown();
1046 }
1047
1048 /**
1049 * Sets the thread factory used to create new threads.
1050 *
1051 * @param threadFactory the new thread factory
1052 * @throws NullPointerException if threadFactory is null
1053 * @see #getThreadFactory
1054 */
1055 public void setThreadFactory(ThreadFactory threadFactory) {
1056 if (threadFactory == null)
1057 throw new NullPointerException();
1058 this.threadFactory = threadFactory;
1059 }
1060
1061 /**
1062 * Returns the thread factory used to create new threads.
1063 *
1064 * @return the current thread factory
1065 * @see #setThreadFactory
1066 */
1067 public ThreadFactory getThreadFactory() {
1068 return threadFactory;
1069 }
1070
1071 /**
1072 * Sets a new handler for unexecutable tasks.
1073 *
1074 * @param handler the new handler
1075 * @throws NullPointerException if handler is null
1076 * @see #getRejectedExecutionHandler
1077 */
1078 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1079 if (handler == null)
1080 throw new NullPointerException();
1081 this.handler = handler;
1082 }
1083
1084 /**
1085 * Returns the current handler for unexecutable tasks.
1086 *
1087 * @return the current handler
1088 * @see #setRejectedExecutionHandler
1089 */
1090 public RejectedExecutionHandler getRejectedExecutionHandler() {
1091 return handler;
1092 }
1093
1094 /**
1095 * Returns the task queue used by this executor. Access to the
1096 * task queue is intended primarily for debugging and monitoring.
1097 * This queue may be in active use. Retrieving the task queue
1098 * does not prevent queued tasks from executing.
1099 *
1100 * @return the task queue
1101 */
1102 public BlockingQueue<Runnable> getQueue() {
1103 return workQueue;
1104 }
1105
1106 /**
1107 * Removes this task from the executor's internal queue if it is
1108 * present, thus causing it not to be run if it has not already
1109 * started.
1110 *
1111 * <p> This method may be useful as one part of a cancellation
1112 * scheme. It may fail to remove tasks that have been converted
1113 * into other forms before being placed on the internal queue. For
1114 * example, a task entered using <tt>submit</tt> might be
1115 * converted into a form that maintains <tt>Future</tt> status.
1116 * However, in such cases, method {@link ThreadPoolExecutor#purge}
1117 * may be used to remove those Futures that have been cancelled.
1118 *
1119 *
1120 * @param task the task to remove
1121 * @return true if the task was removed
1122 */
1123 public boolean remove(Runnable task) {
1124 return getQueue().remove(task);
1125 }
1126
1127
1128 /**
1129 * Tries to remove from the work queue all {@link Future}
1130 * tasks that have been cancelled. This method can be useful as a
1131 * storage reclamation operation, that has no other impact on
1132 * functionality. Cancelled tasks are never executed, but may
1133 * accumulate in work queues until worker threads can actively
1134 * remove them. Invoking this method instead tries to remove them now.
1135 * However, this method may fail to remove tasks in
1136 * the presence of interference by other threads.
1137 */
1138 public void purge() {
1139 // Fail if we encounter interference during traversal
1140 try {
1141 Iterator<Runnable> it = getQueue().iterator();
1142 while (it.hasNext()) {
1143 Runnable r = it.next();
1144 if (r instanceof Future<?>) {
1145 Future<?> c = (Future<?>)r;
1146 if (c.isCancelled())
1147 it.remove();
1148 }
1149 }
1150 }
1151 catch(ConcurrentModificationException ex) {
1152 return;
1153 }
1154 }
1155
1156 /**
1157 * Sets the core number of threads. This overrides any value set
1158 * in the constructor. If the new value is smaller than the
1159 * current value, excess existing threads will be terminated when
1160 * they next become idle. If larger, new threads will, if needed,
1161 * be started to execute any queued tasks.
1162 *
1163 * @param corePoolSize the new core size
1164 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1165 * less than zero
1166 * @see #getCorePoolSize
1167 */
1168 public void setCorePoolSize(int corePoolSize) {
1169 if (corePoolSize < 0)
1170 throw new IllegalArgumentException();
1171 final ReentrantLock mainLock = this.mainLock;
1172 mainLock.lock();
1173 try {
1174 int extra = this.corePoolSize - corePoolSize;
1175 this.corePoolSize = corePoolSize;
1176 if (extra < 0) {
1177 int n = workQueue.size();
1178 // We have to create initially-idle threads here
1179 // because we otherwise have no recourse about
1180 // what to do with a dequeued task if addThread fails.
1181 while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize ) {
1182 Thread t = addThread(null);
1183 if (t != null)
1184 t.start();
1185 else
1186 break;
1187 }
1188 }
1189 else if (extra > 0 && poolSize > corePoolSize) {
1190 Iterator<Worker> it = workers.iterator();
1191 while (it.hasNext() &&
1192 extra-- > 0 &&
1193 poolSize > corePoolSize &&
1194 workQueue.remainingCapacity() == 0)
1195 it.next().interruptIfIdle();
1196 }
1197 } finally {
1198 mainLock.unlock();
1199 }
1200 }
1201
1202 /**
1203 * Returns the core number of threads.
1204 *
1205 * @return the core number of threads
1206 * @see #setCorePoolSize
1207 */
1208 public int getCorePoolSize() {
1209 return corePoolSize;
1210 }
1211
1212 /**
1213 * Starts a core thread, causing it to idly wait for work. This
1214 * overrides the default policy of starting core threads only when
1215 * new tasks are executed. This method will return <tt>false</tt>
1216 * if all core threads have already been started.
1217 * @return true if a thread was started
1218 */
1219 public boolean prestartCoreThread() {
1220 return addIfUnderCorePoolSize(null);
1221 }
1222
1223 /**
1224 * Starts all core threads, causing them to idly wait for work. This
1225 * overrides the default policy of starting core threads only when
1226 * new tasks are executed.
1227 * @return the number of threads started.
1228 */
1229 public int prestartAllCoreThreads() {
1230 int n = 0;
1231 while (addIfUnderCorePoolSize(null))
1232 ++n;
1233 return n;
1234 }
1235
1236 /**
1237 * Returns true if this pool allows core threads to time out and
1238 * terminate if no tasks arrive within the keepAlive time, being
1239 * replaced if needed when new tasks arrive. When true, the same
1240 * keep-alive policy applying to non-core threads applies also to
1241 * core threads. When false (the default), core threads are never
1242 * terminated due to lack of incoming tasks.
1243 * @return <tt>true</tt> if core threads are allowed to time out,
1244 * else <tt>false</tt>
1245 */
1246 public boolean allowsCoreThreadTimeOut() {
1247 return allowCoreThreadTimeOut;
1248 }
1249
1250 /**
1251 * Sets the policy governing whether core threads may time out and
1252 * terminate if no tasks arrive within the keep-alive time, being
1253 * replaced if needed when new tasks arrive. When false, core
1254 * threads are never terminated due to lack of incoming
1255 * tasks. When true, the same keep-alive policy applying to
1256 * non-core threads applies also to core threads. To avoid
1257 * continual thread replacement, the keep-alive time must be
1258 * greater than zero when setting <tt>true</tt>.
1259 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1260 */
1261 public void allowCoreThreadTimeOut(boolean value) {
1262 allowCoreThreadTimeOut = value;
1263 }
1264
1265 /**
1266 * Sets the maximum allowed number of threads. This overrides any
1267 * value set in the constructor. If the new value is smaller than
1268 * the current value, excess existing threads will be
1269 * terminated when they next become idle.
1270 *
1271 * @param maximumPoolSize the new maximum
1272 * @throws IllegalArgumentException if maximumPoolSize less than zero or
1273 * the {@link #getCorePoolSize core pool size}
1274 * @see #getMaximumPoolSize
1275 */
1276 public void setMaximumPoolSize(int maximumPoolSize) {
1277 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1278 throw new IllegalArgumentException();
1279 final ReentrantLock mainLock = this.mainLock;
1280 mainLock.lock();
1281 try {
1282 int extra = this.maximumPoolSize - maximumPoolSize;
1283 this.maximumPoolSize = maximumPoolSize;
1284 if (extra > 0 && poolSize > maximumPoolSize) {
1285 Iterator<Worker> it = workers.iterator();
1286 while (it.hasNext() &&
1287 extra > 0 &&
1288 poolSize > maximumPoolSize) {
1289 it.next().interruptIfIdle();
1290 --extra;
1291 }
1292 }
1293 } finally {
1294 mainLock.unlock();
1295 }
1296 }
1297
1298 /**
1299 * Returns the maximum allowed number of threads.
1300 *
1301 * @return the maximum allowed number of threads
1302 * @see #setMaximumPoolSize
1303 */
1304 public int getMaximumPoolSize() {
1305 return maximumPoolSize;
1306 }
1307
1308 /**
1309 * Sets the time limit for which threads may remain idle before
1310 * being terminated. If there are more than the core number of
1311 * threads currently in the pool, after waiting this amount of
1312 * time without processing a task, excess threads will be
1313 * terminated. This overrides any value set in the constructor.
1314 * @param time the time to wait. A time value of zero will cause
1315 * excess threads to terminate immediately after executing tasks.
1316 * @param unit the time unit of the time argument
1317 * @throws IllegalArgumentException if time less than zero
1318 * @see #getKeepAliveTime
1319 */
1320 public void setKeepAliveTime(long time, TimeUnit unit) {
1321 if (time < 0)
1322 throw new IllegalArgumentException();
1323 this.keepAliveTime = unit.toNanos(time);
1324 }
1325
1326 /**
1327 * Returns the thread keep-alive time, which is the amount of time
1328 * which threads in excess of the core pool size may remain
1329 * idle before being terminated.
1330 *
1331 * @param unit the desired time unit of the result
1332 * @return the time limit
1333 * @see #setKeepAliveTime
1334 */
1335 public long getKeepAliveTime(TimeUnit unit) {
1336 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1337 }
1338
1339 /* Statistics */
1340
1341 /**
1342 * Returns the current number of threads in the pool.
1343 *
1344 * @return the number of threads
1345 */
1346 public int getPoolSize() {
1347 return poolSize;
1348 }
1349
1350 /**
1351 * Returns the approximate number of threads that are actively
1352 * executing tasks.
1353 *
1354 * @return the number of threads
1355 */
1356 public int getActiveCount() {
1357 final ReentrantLock mainLock = this.mainLock;
1358 mainLock.lock();
1359 try {
1360 int n = 0;
1361 for (Worker w : workers) {
1362 if (w.isActive())
1363 ++n;
1364 }
1365 return n;
1366 } finally {
1367 mainLock.unlock();
1368 }
1369 }
1370
1371 /**
1372 * Returns the largest number of threads that have ever
1373 * simultaneously been in the pool.
1374 *
1375 * @return the number of threads
1376 */
1377 public int getLargestPoolSize() {
1378 final ReentrantLock mainLock = this.mainLock;
1379 mainLock.lock();
1380 try {
1381 return largestPoolSize;
1382 } finally {
1383 mainLock.unlock();
1384 }
1385 }
1386
1387 /**
1388 * Returns the approximate total number of tasks that have been
1389 * scheduled for execution. Because the states of tasks and
1390 * threads may change dynamically during computation, the returned
1391 * value is only an approximation, but one that does not ever
1392 * decrease across successive calls.
1393 *
1394 * @return the number of tasks
1395 */
1396 public long getTaskCount() {
1397 final ReentrantLock mainLock = this.mainLock;
1398 mainLock.lock();
1399 try {
1400 long n = completedTaskCount;
1401 for (Worker w : workers) {
1402 n += w.completedTasks;
1403 if (w.isActive())
1404 ++n;
1405 }
1406 return n + workQueue.size();
1407 } finally {
1408 mainLock.unlock();
1409 }
1410 }
1411
1412 /**
1413 * Returns the approximate total number of tasks that have
1414 * completed execution. Because the states of tasks and threads
1415 * may change dynamically during computation, the returned value
1416 * is only an approximation, but one that does not ever decrease
1417 * across successive calls.
1418 *
1419 * @return the number of tasks
1420 */
1421 public long getCompletedTaskCount() {
1422 final ReentrantLock mainLock = this.mainLock;
1423 mainLock.lock();
1424 try {
1425 long n = completedTaskCount;
1426 for (Worker w : workers)
1427 n += w.completedTasks;
1428 return n;
1429 } finally {
1430 mainLock.unlock();
1431 }
1432 }
1433
1434 /**
1435 * Method invoked prior to executing the given Runnable in the
1436 * given thread. This method is invoked by thread <tt>t</tt> that
1437 * will execute task <tt>r</tt>, and may be used to re-initialize
1438 * ThreadLocals, or to perform logging. Note: To properly nest
1439 * multiple overridings, subclasses should generally invoke
1440 * <tt>super.beforeExecute</tt> at the end of this method.
1441 *
1442 * @param t the thread that will run task r.
1443 * @param r the task that will be executed.
1444 */
1445 protected void beforeExecute(Thread t, Runnable r) { }
1446
1447 /**
1448 * Method invoked upon completion of execution of the given
1449 * Runnable. This method is invoked by the thread that executed
1450 * the task. If non-null, the Throwable is the uncaught exception
1451 * that caused execution to terminate abruptly. Note: To properly
1452 * nest multiple overridings, subclasses should generally invoke
1453 * <tt>super.afterExecute</tt> at the beginning of this method.
1454 *
1455 * @param r the runnable that has completed.
1456 * @param t the exception that caused termination, or null if
1457 * execution completed normally.
1458 */
1459 protected void afterExecute(Runnable r, Throwable t) { }
1460
1461 /**
1462 * Method invoked when the Executor has terminated. Default
1463 * implementation does nothing. Note: To properly nest multiple
1464 * overridings, subclasses should generally invoke
1465 * <tt>super.terminated</tt> within this method.
1466 */
1467 protected void terminated() { }
1468
1469 /**
1470 * A handler for rejected tasks that runs the rejected task
1471 * directly in the calling thread of the <tt>execute</tt> method,
1472 * unless the executor has been shut down, in which case the task
1473 * is discarded.
1474 */
1475 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1476 /**
1477 * Creates a <tt>CallerRunsPolicy</tt>.
1478 */
1479 public CallerRunsPolicy() { }
1480
1481 /**
1482 * Executes task r in the caller's thread, unless the executor
1483 * has been shut down, in which case the task is discarded.
1484 * @param r the runnable task requested to be executed
1485 * @param e the executor attempting to execute this task
1486 */
1487 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1488 if (!e.isShutdown()) {
1489 r.run();
1490 }
1491 }
1492 }
1493
1494 /**
1495 * A handler for rejected tasks that throws a
1496 * <tt>RejectedExecutionException</tt>.
1497 */
1498 public static class AbortPolicy implements RejectedExecutionHandler {
1499 /**
1500 * Creates an <tt>AbortPolicy</tt>.
1501 */
1502 public AbortPolicy() { }
1503
1504 /**
1505 * Always throws RejectedExecutionException.
1506 * @param r the runnable task requested to be executed
1507 * @param e the executor attempting to execute this task
1508 * @throws RejectedExecutionException always.
1509 */
1510 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1511 throw new RejectedExecutionException();
1512 }
1513 }
1514
1515 /**
1516 * A handler for rejected tasks that silently discards the
1517 * rejected task.
1518 */
1519 public static class DiscardPolicy implements RejectedExecutionHandler {
1520 /**
1521 * Creates a <tt>DiscardPolicy</tt>.
1522 */
1523 public DiscardPolicy() { }
1524
1525 /**
1526 * Does nothing, which has the effect of discarding task r.
1527 * @param r the runnable task requested to be executed
1528 * @param e the executor attempting to execute this task
1529 */
1530 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1531 }
1532 }
1533
1534 /**
1535 * A handler for rejected tasks that discards the oldest unhandled
1536 * request and then retries <tt>execute</tt>, unless the executor
1537 * is shut down, in which case the task is discarded.
1538 */
1539 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1540 /**
1541 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1542 */
1543 public DiscardOldestPolicy() { }
1544
1545 /**
1546 * Obtains and ignores the next task that the executor
1547 * would otherwise execute, if one is immediately available,
1548 * and then retries execution of task r, unless the executor
1549 * is shut down, in which case task r is instead discarded.
1550 * @param r the runnable task requested to be executed
1551 * @param e the executor attempting to execute this task
1552 */
1553 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1554 if (!e.isShutdown()) {
1555 e.getQueue().poll();
1556 e.execute(r);
1557 }
1558 }
1559 }
1560 }