ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.73
Committed: Mon Aug 15 20:51:15 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.72: +10 -8 lines
Log Message:
doc fixes

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