ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.74
Committed: Tue Aug 23 12:49:57 2005 UTC (18 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.73: +18 -11 lines
Log Message:
Allow recycling of rejected tasks

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 0 if a new thread cannot be created, a positive number
448 * if firstTask will be run in a new thread, or a negative number
449 * if a new thread was created but is running some other task, in
450 * which case the caller must try some other way to run firstTask
451 * (perhaps by calling this method again).
452 */
453 private int addIfUnderMaximumPoolSize(Runnable firstTask) {
454 Thread t = null;
455 int status = 0;
456 final ReentrantLock mainLock = this.mainLock;
457 mainLock.lock();
458 try {
459 if (poolSize < maximumPoolSize) {
460 Runnable next = workQueue.poll();
461 if (next == null) {
462 next = firstTask;
463 status = 1;
464 } else
465 status = -1;
466 t = addThread(next);
467 }
468 } finally {
469 mainLock.unlock();
470 }
471 if (t == null)
472 return 0;
473 t.start();
474 return status;
475 }
476
477
478 /**
479 * Gets the next task for a worker thread to run.
480 * @return the task
481 */
482 Runnable getTask() {
483 for (;;) {
484 try {
485 switch (runState) {
486 case RUNNING: {
487 // untimed wait if core and not allowing core timeout
488 if (poolSize <= corePoolSize && !allowCoreThreadTimeOut)
489 return workQueue.take();
490
491 long timeout = keepAliveTime;
492 if (timeout <= 0) // die immediately for 0 timeout
493 return null;
494 Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
495 if (r != null)
496 return r;
497 if (poolSize > corePoolSize || allowCoreThreadTimeOut)
498 return null; // timed out
499 // Else, after timeout, the pool shrank. Retry
500 break;
501 }
502
503 case SHUTDOWN: {
504 // Help drain queue
505 Runnable r = workQueue.poll();
506 if (r != null)
507 return r;
508
509 // Check if can terminate
510 if (workQueue.isEmpty()) {
511 interruptIdleWorkers();
512 return null;
513 }
514
515 // Else there could still be delayed tasks in queue.
516 return workQueue.take();
517 }
518
519 case STOP:
520 return null;
521 default:
522 assert false;
523 }
524 } catch (InterruptedException ie) {
525 // On interruption, re-check runstate
526 }
527 }
528 }
529
530 /**
531 * Wakes up all threads that might be waiting for tasks.
532 */
533 void interruptIdleWorkers() {
534 final ReentrantLock mainLock = this.mainLock;
535 mainLock.lock();
536 try {
537 for (Worker w : workers)
538 w.interruptIfIdle();
539 } finally {
540 mainLock.unlock();
541 }
542 }
543
544 /**
545 * Performs bookkeeping for a terminated worker thread.
546 * @param w the worker
547 */
548 void workerDone(Worker w) {
549 final ReentrantLock mainLock = this.mainLock;
550 mainLock.lock();
551 try {
552 completedTaskCount += w.completedTasks;
553 workers.remove(w);
554 if (--poolSize > 0)
555 return;
556
557 // Else, this is the last thread. Deal with potential shutdown.
558
559 int state = runState;
560 assert state != TERMINATED;
561
562 if (state != STOP) {
563 // If there are queued tasks but no threads, create
564 // replacement thread. We must create it initially
565 // idle to avoid orphaned tasks in case addThread
566 // fails. This also handles case of delayed tasks
567 // that will sometime later become runnable.
568 if (!workQueue.isEmpty()) {
569 Thread t = addThread(null);
570 if (t != null)
571 t.start();
572 return;
573 }
574
575 // Otherwise, we can exit without replacement
576 if (state == RUNNING)
577 return;
578 }
579
580 // Either state is STOP, or state is SHUTDOWN and there is
581 // no work to do. So we can terminate.
582 termination.signalAll();
583 runState = TERMINATED;
584 // fall through to call terminate() outside of lock.
585 } finally {
586 mainLock.unlock();
587 }
588
589 assert runState == TERMINATED;
590 terminated();
591 }
592
593 /**
594 * Worker threads
595 */
596 private class Worker implements Runnable {
597
598 /**
599 * The runLock is acquired and released surrounding each task
600 * execution. It mainly protects against interrupts that are
601 * intended to cancel the worker thread from instead
602 * interrupting the task being run.
603 */
604 private final ReentrantLock runLock = new ReentrantLock();
605
606 /**
607 * Initial task to run before entering run loop
608 */
609 private Runnable firstTask;
610
611 /**
612 * Per thread completed task counter; accumulated
613 * into completedTaskCount upon termination.
614 */
615 volatile long completedTasks;
616
617 /**
618 * Thread this worker is running in. Acts as a final field,
619 * but cannot be set until thread is created.
620 */
621 Thread thread;
622
623 Worker(Runnable firstTask) {
624 this.firstTask = firstTask;
625 }
626
627 boolean isActive() {
628 return runLock.isLocked();
629 }
630
631 /**
632 * Interrupts thread if not running a task.
633 */
634 void interruptIfIdle() {
635 final ReentrantLock runLock = this.runLock;
636 if (runLock.tryLock()) {
637 try {
638 thread.interrupt();
639 } finally {
640 runLock.unlock();
641 }
642 }
643 }
644
645 /**
646 * Interrupts thread even if running a task.
647 */
648 void interruptNow() {
649 thread.interrupt();
650 }
651
652 /**
653 * Runs a single task between before/after methods.
654 */
655 private void runTask(Runnable task) {
656 final ReentrantLock runLock = this.runLock;
657 runLock.lock();
658 try {
659 Thread.interrupted(); // clear interrupt status on entry
660 // Abort now if immediate cancel. Otherwise, we have
661 // committed to run this task.
662 if (runState == STOP)
663 return;
664
665 boolean ran = false;
666 beforeExecute(thread, task);
667 try {
668 task.run();
669 ran = true;
670 afterExecute(task, null);
671 ++completedTasks;
672 } catch (RuntimeException ex) {
673 if (!ran)
674 afterExecute(task, ex);
675 // Else the exception occurred within
676 // afterExecute itself in which case we don't
677 // want to call it again.
678 throw ex;
679 }
680 } finally {
681 runLock.unlock();
682 }
683 }
684
685 /**
686 * Main run loop
687 */
688 public void run() {
689 try {
690 Runnable task = firstTask;
691 firstTask = null;
692 while (task != null || (task = getTask()) != null) {
693 runTask(task);
694 task = null; // unnecessary but can help GC
695 }
696 } finally {
697 workerDone(this);
698 }
699 }
700 }
701
702 // Public methods
703
704 /**
705 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
706 * parameters and default thread factory and rejected execution handler.
707 * It may be more convenient to use one of the {@link Executors} factory
708 * methods instead of this general purpose constructor.
709 *
710 * @param corePoolSize the number of threads to keep in the
711 * pool, even if they are idle.
712 * @param maximumPoolSize the maximum number of threads to allow in the
713 * pool.
714 * @param keepAliveTime when the number of threads is greater than
715 * the core, this is the maximum time that excess idle threads
716 * will wait for new tasks before terminating.
717 * @param unit the time unit for the keepAliveTime
718 * argument.
719 * @param workQueue the queue to use for holding tasks before they
720 * are executed. This queue will hold only the <tt>Runnable</tt>
721 * tasks submitted by the <tt>execute</tt> method.
722 * @throws IllegalArgumentException if corePoolSize, or
723 * keepAliveTime less than zero, or if maximumPoolSize less than or
724 * equal to zero, or if corePoolSize greater than maximumPoolSize.
725 * @throws NullPointerException if <tt>workQueue</tt> is null
726 */
727 public ThreadPoolExecutor(int corePoolSize,
728 int maximumPoolSize,
729 long keepAliveTime,
730 TimeUnit unit,
731 BlockingQueue<Runnable> workQueue) {
732 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
733 Executors.defaultThreadFactory(), defaultHandler);
734 }
735
736 /**
737 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
738 * parameters and default rejected execution handler.
739 *
740 * @param corePoolSize the number of threads to keep in the
741 * pool, even if they are idle.
742 * @param maximumPoolSize the maximum number of threads to allow in the
743 * pool.
744 * @param keepAliveTime when the number of threads is greater than
745 * the core, this is the maximum time that excess idle threads
746 * will wait for new tasks before terminating.
747 * @param unit the time unit for the keepAliveTime
748 * argument.
749 * @param workQueue the queue to use for holding tasks before they
750 * are executed. This queue will hold only the <tt>Runnable</tt>
751 * tasks submitted by the <tt>execute</tt> method.
752 * @param threadFactory the factory to use when the executor
753 * creates a new thread.
754 * @throws IllegalArgumentException if corePoolSize, or
755 * keepAliveTime less than zero, or if maximumPoolSize less than or
756 * equal to zero, or if corePoolSize greater than maximumPoolSize.
757 * @throws NullPointerException if <tt>workQueue</tt>
758 * or <tt>threadFactory</tt> are null.
759 */
760 public ThreadPoolExecutor(int corePoolSize,
761 int maximumPoolSize,
762 long keepAliveTime,
763 TimeUnit unit,
764 BlockingQueue<Runnable> workQueue,
765 ThreadFactory threadFactory) {
766 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
767 threadFactory, defaultHandler);
768 }
769
770 /**
771 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
772 * parameters and default thread factory.
773 *
774 * @param corePoolSize the number of threads to keep in the
775 * pool, even if they are idle.
776 * @param maximumPoolSize the maximum number of threads to allow in the
777 * pool.
778 * @param keepAliveTime when the number of threads is greater than
779 * the core, this is the maximum time that excess idle threads
780 * will wait for new tasks before terminating.
781 * @param unit the time unit for the keepAliveTime
782 * argument.
783 * @param workQueue the queue to use for holding tasks before they
784 * are executed. This queue will hold only the <tt>Runnable</tt>
785 * tasks submitted by the <tt>execute</tt> method.
786 * @param handler the handler to use when execution is blocked
787 * because the thread bounds and queue capacities are reached.
788 * @throws IllegalArgumentException if corePoolSize, or
789 * keepAliveTime less than zero, or if maximumPoolSize less than or
790 * equal to zero, or if corePoolSize greater than maximumPoolSize.
791 * @throws NullPointerException if <tt>workQueue</tt>
792 * or <tt>handler</tt> are null.
793 */
794 public ThreadPoolExecutor(int corePoolSize,
795 int maximumPoolSize,
796 long keepAliveTime,
797 TimeUnit unit,
798 BlockingQueue<Runnable> workQueue,
799 RejectedExecutionHandler handler) {
800 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
801 Executors.defaultThreadFactory(), handler);
802 }
803
804 /**
805 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
806 * parameters.
807 *
808 * @param corePoolSize the number of threads to keep in the
809 * pool, even if they are idle.
810 * @param maximumPoolSize the maximum number of threads to allow in the
811 * pool.
812 * @param keepAliveTime when the number of threads is greater than
813 * the core, this is the maximum time that excess idle threads
814 * will wait for new tasks before terminating.
815 * @param unit the time unit for the keepAliveTime
816 * argument.
817 * @param workQueue the queue to use for holding tasks before they
818 * are executed. This queue will hold only the <tt>Runnable</tt>
819 * tasks submitted by the <tt>execute</tt> method.
820 * @param threadFactory the factory to use when the executor
821 * creates a new thread.
822 * @param handler the handler to use when execution is blocked
823 * because the thread bounds and queue capacities are reached.
824 * @throws IllegalArgumentException if corePoolSize, or
825 * keepAliveTime less than zero, or if maximumPoolSize less than or
826 * equal to zero, or if corePoolSize greater than maximumPoolSize.
827 * @throws NullPointerException if <tt>workQueue</tt>
828 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
829 */
830 public ThreadPoolExecutor(int corePoolSize,
831 int maximumPoolSize,
832 long keepAliveTime,
833 TimeUnit unit,
834 BlockingQueue<Runnable> workQueue,
835 ThreadFactory threadFactory,
836 RejectedExecutionHandler handler) {
837 if (corePoolSize < 0 ||
838 maximumPoolSize <= 0 ||
839 maximumPoolSize < corePoolSize ||
840 keepAliveTime < 0)
841 throw new IllegalArgumentException();
842 if (workQueue == null || threadFactory == null || handler == null)
843 throw new NullPointerException();
844 this.corePoolSize = corePoolSize;
845 this.maximumPoolSize = maximumPoolSize;
846 this.workQueue = workQueue;
847 this.keepAliveTime = unit.toNanos(keepAliveTime);
848 this.threadFactory = threadFactory;
849 this.handler = handler;
850 }
851
852
853 /**
854 * Executes the given task sometime in the future. The task
855 * may execute in a new thread or in an existing pooled thread.
856 *
857 * If the task cannot be submitted for execution, either because this
858 * executor has been shutdown or because its capacity has been reached,
859 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
860 *
861 * @param command the task to execute
862 * @throws RejectedExecutionException at discretion of
863 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
864 * for execution
865 * @throws NullPointerException if command is null
866 */
867 public void execute(Runnable command) {
868 if (command == null)
869 throw new NullPointerException();
870 for (;;) {
871 if (runState != RUNNING) {
872 reject(command);
873 return;
874 }
875 if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
876 return;
877 if (workQueue.offer(command))
878 return;
879 int status = addIfUnderMaximumPoolSize(command);
880 if (status > 0) // created new thread
881 return;
882 if (status == 0) { // failed to create thread
883 reject(command);
884 return;
885 }
886 // Retry if created a new thread but it is busy with another task
887 }
888 }
889
890 /**
891 * Initiates an orderly shutdown in which previously submitted
892 * tasks are executed, but no new tasks will be
893 * accepted. Invocation has no additional effect if already shut
894 * down.
895 * @throws SecurityException if a security manager exists and
896 * shutting down this ExecutorService may manipulate threads that
897 * the caller is not permitted to modify because it does not hold
898 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
899 * or the security manager's <tt>checkAccess</tt> method denies access.
900 */
901 public void shutdown() {
902 // Fail if caller doesn't have modifyThread permission. We
903 // explicitly check permissions directly because we can't trust
904 // implementations of SecurityManager to correctly override
905 // the "check access" methods such that our documented
906 // security policy is implemented.
907 SecurityManager security = System.getSecurityManager();
908 if (security != null)
909 java.security.AccessController.checkPermission(shutdownPerm);
910
911 boolean fullyTerminated = false;
912 final ReentrantLock mainLock = this.mainLock;
913 mainLock.lock();
914 try {
915 if (workers.size() > 0) {
916 // Check if caller can modify worker threads. This
917 // might not be true even if passed above check, if
918 // the SecurityManager treats some threads specially.
919 if (security != null) {
920 for (Worker w: workers)
921 security.checkAccess(w.thread);
922 }
923
924 int state = runState;
925 if (state == RUNNING) // don't override shutdownNow
926 runState = SHUTDOWN;
927
928 try {
929 for (Worker w: workers)
930 w.interruptIfIdle();
931 } catch (SecurityException se) {
932 // If SecurityManager allows above checks, but
933 // then unexpectedly throws exception when
934 // interrupting threads (which it ought not do),
935 // back out as cleanly as we can. Some threads may
936 // have been killed but we remain in non-shutdown
937 // state.
938 runState = state;
939 throw se;
940 }
941 }
942 else { // If no workers, trigger full termination now
943 fullyTerminated = true;
944 runState = TERMINATED;
945 termination.signalAll();
946 }
947 } finally {
948 mainLock.unlock();
949 }
950 if (fullyTerminated)
951 terminated();
952 }
953
954
955 /**
956 * Attempts to stop all actively executing tasks, halts the
957 * processing of waiting tasks, and returns a list of the tasks that were
958 * awaiting execution.
959 *
960 * <p>This implementation cancels tasks via {@link
961 * Thread#interrupt}, so if any tasks mask or fail to respond to
962 * interrupts, they may never terminate.
963 *
964 * @return list of tasks that never commenced execution
965 * @throws SecurityException if a security manager exists and
966 * shutting down this ExecutorService may manipulate threads that
967 * the caller is not permitted to modify because it does not hold
968 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
969 * or the security manager's <tt>checkAccess</tt> method denies access.
970 */
971 public List<Runnable> shutdownNow() {
972 // Almost the same code as shutdown()
973 SecurityManager security = System.getSecurityManager();
974 if (security != null)
975 java.security.AccessController.checkPermission(shutdownPerm);
976
977 boolean fullyTerminated = false;
978 final ReentrantLock mainLock = this.mainLock;
979 mainLock.lock();
980 try {
981 if (workers.size() > 0) {
982 if (security != null) {
983 for (Worker w: workers)
984 security.checkAccess(w.thread);
985 }
986
987 int state = runState;
988 if (state != TERMINATED)
989 runState = STOP;
990 try {
991 for (Worker w : workers)
992 w.interruptNow();
993 } catch (SecurityException se) {
994 runState = state; // back out;
995 throw se;
996 }
997 }
998 else { // If no workers, trigger full termination now
999 fullyTerminated = true;
1000 runState = TERMINATED;
1001 termination.signalAll();
1002 }
1003 } finally {
1004 mainLock.unlock();
1005 }
1006 if (fullyTerminated)
1007 terminated();
1008 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
1009 }
1010
1011 public boolean isShutdown() {
1012 return runState != RUNNING;
1013 }
1014
1015 /**
1016 * Returns true if this executor is in the process of terminating
1017 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1018 * completely terminated. This method may be useful for
1019 * debugging. A return of <tt>true</tt> reported a sufficient
1020 * period after shutdown may indicate that submitted tasks have
1021 * ignored or suppressed interruption, causing this executor not
1022 * to properly terminate.
1023 * @return true if terminating but not yet terminated.
1024 */
1025 public boolean isTerminating() {
1026 return runState == STOP;
1027 }
1028
1029 public boolean isTerminated() {
1030 return runState == TERMINATED;
1031 }
1032
1033 public boolean awaitTermination(long timeout, TimeUnit unit)
1034 throws InterruptedException {
1035 long nanos = unit.toNanos(timeout);
1036 final ReentrantLock mainLock = this.mainLock;
1037 mainLock.lock();
1038 try {
1039 for (;;) {
1040 if (runState == TERMINATED)
1041 return true;
1042 if (nanos <= 0)
1043 return false;
1044 nanos = termination.awaitNanos(nanos);
1045 }
1046 } finally {
1047 mainLock.unlock();
1048 }
1049 }
1050
1051 /**
1052 * Invokes <tt>shutdown</tt> when this executor is no longer
1053 * referenced.
1054 */
1055 protected void finalize() {
1056 shutdown();
1057 }
1058
1059 /**
1060 * Sets the thread factory used to create new threads.
1061 *
1062 * @param threadFactory the new thread factory
1063 * @throws NullPointerException if threadFactory is null
1064 * @see #getThreadFactory
1065 */
1066 public void setThreadFactory(ThreadFactory threadFactory) {
1067 if (threadFactory == null)
1068 throw new NullPointerException();
1069 this.threadFactory = threadFactory;
1070 }
1071
1072 /**
1073 * Returns the thread factory used to create new threads.
1074 *
1075 * @return the current thread factory
1076 * @see #setThreadFactory
1077 */
1078 public ThreadFactory getThreadFactory() {
1079 return threadFactory;
1080 }
1081
1082 /**
1083 * Sets a new handler for unexecutable tasks.
1084 *
1085 * @param handler the new handler
1086 * @throws NullPointerException if handler is null
1087 * @see #getRejectedExecutionHandler
1088 */
1089 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1090 if (handler == null)
1091 throw new NullPointerException();
1092 this.handler = handler;
1093 }
1094
1095 /**
1096 * Returns the current handler for unexecutable tasks.
1097 *
1098 * @return the current handler
1099 * @see #setRejectedExecutionHandler
1100 */
1101 public RejectedExecutionHandler getRejectedExecutionHandler() {
1102 return handler;
1103 }
1104
1105 /**
1106 * Returns the task queue used by this executor. Access to the
1107 * task queue is intended primarily for debugging and monitoring.
1108 * This queue may be in active use. Retrieving the task queue
1109 * does not prevent queued tasks from executing.
1110 *
1111 * @return the task queue
1112 */
1113 public BlockingQueue<Runnable> getQueue() {
1114 return workQueue;
1115 }
1116
1117 /**
1118 * Removes this task from the executor's internal queue if it is
1119 * present, thus causing it not to be run if it has not already
1120 * started.
1121 *
1122 * <p> This method may be useful as one part of a cancellation
1123 * scheme. It may fail to remove tasks that have been converted
1124 * into other forms before being placed on the internal queue. For
1125 * example, a task entered using <tt>submit</tt> might be
1126 * converted into a form that maintains <tt>Future</tt> status.
1127 * However, in such cases, method {@link ThreadPoolExecutor#purge}
1128 * may be used to remove those Futures that have been cancelled.
1129 *
1130 *
1131 * @param task the task to remove
1132 * @return true if the task was removed
1133 */
1134 public boolean remove(Runnable task) {
1135 return getQueue().remove(task);
1136 }
1137
1138
1139 /**
1140 * Tries to remove from the work queue all {@link Future}
1141 * tasks that have been cancelled. This method can be useful as a
1142 * storage reclamation operation, that has no other impact on
1143 * functionality. Cancelled tasks are never executed, but may
1144 * accumulate in work queues until worker threads can actively
1145 * remove them. Invoking this method instead tries to remove them now.
1146 * However, this method may fail to remove tasks in
1147 * the presence of interference by other threads.
1148 */
1149 public void purge() {
1150 // Fail if we encounter interference during traversal
1151 try {
1152 Iterator<Runnable> it = getQueue().iterator();
1153 while (it.hasNext()) {
1154 Runnable r = it.next();
1155 if (r instanceof Future<?>) {
1156 Future<?> c = (Future<?>)r;
1157 if (c.isCancelled())
1158 it.remove();
1159 }
1160 }
1161 }
1162 catch (ConcurrentModificationException ex) {
1163 return;
1164 }
1165 }
1166
1167 /**
1168 * Sets the core number of threads. This overrides any value set
1169 * in the constructor. If the new value is smaller than the
1170 * current value, excess existing threads will be terminated when
1171 * they next become idle. If larger, new threads will, if needed,
1172 * be started to execute any queued tasks.
1173 *
1174 * @param corePoolSize the new core size
1175 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1176 * less than zero
1177 * @see #getCorePoolSize
1178 */
1179 public void setCorePoolSize(int corePoolSize) {
1180 if (corePoolSize < 0)
1181 throw new IllegalArgumentException();
1182 final ReentrantLock mainLock = this.mainLock;
1183 mainLock.lock();
1184 try {
1185 int extra = this.corePoolSize - corePoolSize;
1186 this.corePoolSize = corePoolSize;
1187 if (extra < 0) {
1188 int n = workQueue.size();
1189 // We have to create initially-idle threads here
1190 // because we otherwise have no recourse about
1191 // what to do with a dequeued task if addThread fails.
1192 while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize ) {
1193 Thread t = addThread(null);
1194 if (t != null)
1195 t.start();
1196 else
1197 break;
1198 }
1199 }
1200 else if (extra > 0 && poolSize > corePoolSize) {
1201 Iterator<Worker> it = workers.iterator();
1202 while (it.hasNext() &&
1203 extra-- > 0 &&
1204 poolSize > corePoolSize &&
1205 workQueue.remainingCapacity() == 0)
1206 it.next().interruptIfIdle();
1207 }
1208 } finally {
1209 mainLock.unlock();
1210 }
1211 }
1212
1213 /**
1214 * Returns the core number of threads.
1215 *
1216 * @return the core number of threads
1217 * @see #setCorePoolSize
1218 */
1219 public int getCorePoolSize() {
1220 return corePoolSize;
1221 }
1222
1223 /**
1224 * Starts a core thread, causing it to idly wait for work. This
1225 * overrides the default policy of starting core threads only when
1226 * new tasks are executed. This method will return <tt>false</tt>
1227 * if all core threads have already been started.
1228 * @return true if a thread was started
1229 */
1230 public boolean prestartCoreThread() {
1231 return addIfUnderCorePoolSize(null);
1232 }
1233
1234 /**
1235 * Starts all core threads, causing them to idly wait for work. This
1236 * overrides the default policy of starting core threads only when
1237 * new tasks are executed.
1238 * @return the number of threads started.
1239 */
1240 public int prestartAllCoreThreads() {
1241 int n = 0;
1242 while (addIfUnderCorePoolSize(null))
1243 ++n;
1244 return n;
1245 }
1246
1247 /**
1248 * Returns true if this pool allows core threads to time out and
1249 * terminate if no tasks arrive within the keepAlive time, being
1250 * replaced if needed when new tasks arrive. When true, the same
1251 * keep-alive policy applying to non-core threads applies also to
1252 * core threads. When false (the default), core threads are never
1253 * terminated due to lack of incoming tasks.
1254 * @return <tt>true</tt> if core threads are allowed to time out,
1255 * else <tt>false</tt>
1256 *
1257 * @since 1.6
1258 */
1259 public boolean allowsCoreThreadTimeOut() {
1260 return allowCoreThreadTimeOut;
1261 }
1262
1263 /**
1264 * Sets the policy governing whether core threads may time out and
1265 * terminate if no tasks arrive within the keep-alive time, being
1266 * replaced if needed when new tasks arrive. When false, core
1267 * threads are never terminated due to lack of incoming
1268 * tasks. When true, the same keep-alive policy applying to
1269 * non-core threads applies also to core threads. To avoid
1270 * continual thread replacement, the keep-alive time must be
1271 * greater than zero when setting <tt>true</tt>. This method
1272 * should in general be called before the pool is actively used.
1273 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1274 * @throws IllegalArgumentException if value is <tt>true</tt>
1275 * and the current keep-alive time is not greater than zero.
1276 *
1277 * @since 1.6
1278 */
1279 public void allowCoreThreadTimeOut(boolean value) {
1280 if (value && keepAliveTime <= 0)
1281 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1282
1283 allowCoreThreadTimeOut = value;
1284 }
1285
1286 /**
1287 * Sets the maximum allowed number of threads. This overrides any
1288 * value set in the constructor. If the new value is smaller than
1289 * the current value, excess existing threads will be
1290 * terminated when they next become idle.
1291 *
1292 * @param maximumPoolSize the new maximum
1293 * @throws IllegalArgumentException if maximumPoolSize less than zero or
1294 * the {@link #getCorePoolSize core pool size}
1295 * @see #getMaximumPoolSize
1296 */
1297 public void setMaximumPoolSize(int maximumPoolSize) {
1298 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1299 throw new IllegalArgumentException();
1300 final ReentrantLock mainLock = this.mainLock;
1301 mainLock.lock();
1302 try {
1303 int extra = this.maximumPoolSize - maximumPoolSize;
1304 this.maximumPoolSize = maximumPoolSize;
1305 if (extra > 0 && poolSize > maximumPoolSize) {
1306 Iterator<Worker> it = workers.iterator();
1307 while (it.hasNext() &&
1308 extra > 0 &&
1309 poolSize > maximumPoolSize) {
1310 it.next().interruptIfIdle();
1311 --extra;
1312 }
1313 }
1314 } finally {
1315 mainLock.unlock();
1316 }
1317 }
1318
1319 /**
1320 * Returns the maximum allowed number of threads.
1321 *
1322 * @return the maximum allowed number of threads
1323 * @see #setMaximumPoolSize
1324 */
1325 public int getMaximumPoolSize() {
1326 return maximumPoolSize;
1327 }
1328
1329 /**
1330 * Sets the time limit for which threads may remain idle before
1331 * being terminated. If there are more than the core number of
1332 * threads currently in the pool, after waiting this amount of
1333 * time without processing a task, excess threads will be
1334 * terminated. This overrides any value set in the constructor.
1335 * @param time the time to wait. A time value of zero will cause
1336 * excess threads to terminate immediately after executing tasks.
1337 * @param unit the time unit of the time argument
1338 * @throws IllegalArgumentException if time less than zero or
1339 * if time is zero and allowsCoreThreadTimeOut
1340 * @see #getKeepAliveTime
1341 */
1342 public void setKeepAliveTime(long time, TimeUnit unit) {
1343 if (time < 0)
1344 throw new IllegalArgumentException();
1345 if (time == 0 && allowsCoreThreadTimeOut())
1346 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1347 this.keepAliveTime = unit.toNanos(time);
1348 }
1349
1350 /**
1351 * Returns the thread keep-alive time, which is the amount of time
1352 * which threads in excess of the core pool size may remain
1353 * idle before being terminated.
1354 *
1355 * @param unit the desired time unit of the result
1356 * @return the time limit
1357 * @see #setKeepAliveTime
1358 */
1359 public long getKeepAliveTime(TimeUnit unit) {
1360 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1361 }
1362
1363 /* Statistics */
1364
1365 /**
1366 * Returns the current number of threads in the pool.
1367 *
1368 * @return the number of threads
1369 */
1370 public int getPoolSize() {
1371 return poolSize;
1372 }
1373
1374 /**
1375 * Returns the approximate number of threads that are actively
1376 * executing tasks.
1377 *
1378 * @return the number of threads
1379 */
1380 public int getActiveCount() {
1381 final ReentrantLock mainLock = this.mainLock;
1382 mainLock.lock();
1383 try {
1384 int n = 0;
1385 for (Worker w : workers) {
1386 if (w.isActive())
1387 ++n;
1388 }
1389 return n;
1390 } finally {
1391 mainLock.unlock();
1392 }
1393 }
1394
1395 /**
1396 * Returns the largest number of threads that have ever
1397 * simultaneously been in the pool.
1398 *
1399 * @return the number of threads
1400 */
1401 public int getLargestPoolSize() {
1402 final ReentrantLock mainLock = this.mainLock;
1403 mainLock.lock();
1404 try {
1405 return largestPoolSize;
1406 } finally {
1407 mainLock.unlock();
1408 }
1409 }
1410
1411 /**
1412 * Returns the approximate total number of tasks that have been
1413 * scheduled for execution. Because the states of tasks and
1414 * threads may change dynamically during computation, the returned
1415 * value is only an approximation, but one that does not ever
1416 * decrease across successive calls.
1417 *
1418 * @return the number of tasks
1419 */
1420 public long getTaskCount() {
1421 final ReentrantLock mainLock = this.mainLock;
1422 mainLock.lock();
1423 try {
1424 long n = completedTaskCount;
1425 for (Worker w : workers) {
1426 n += w.completedTasks;
1427 if (w.isActive())
1428 ++n;
1429 }
1430 return n + workQueue.size();
1431 } finally {
1432 mainLock.unlock();
1433 }
1434 }
1435
1436 /**
1437 * Returns the approximate total number of tasks that have
1438 * completed execution. Because the states of tasks and threads
1439 * may change dynamically during computation, the returned value
1440 * is only an approximation, but one that does not ever decrease
1441 * across successive calls.
1442 *
1443 * @return the number of tasks
1444 */
1445 public long getCompletedTaskCount() {
1446 final ReentrantLock mainLock = this.mainLock;
1447 mainLock.lock();
1448 try {
1449 long n = completedTaskCount;
1450 for (Worker w : workers)
1451 n += w.completedTasks;
1452 return n;
1453 } finally {
1454 mainLock.unlock();
1455 }
1456 }
1457
1458 /**
1459 * Method invoked prior to executing the given Runnable in the
1460 * given thread. This method is invoked by thread <tt>t</tt> that
1461 * will execute task <tt>r</tt>, and may be used to re-initialize
1462 * ThreadLocals, or to perform logging.
1463 *
1464 * <p>This implementation does nothing, but may be customized in
1465 * subclasses. Note: To properly nest multiple overridings, subclasses
1466 * should generally invoke <tt>super.beforeExecute</tt> at the end of
1467 * this method.
1468 *
1469 * @param t the thread that will run task r.
1470 * @param r the task that will be executed.
1471 */
1472 protected void beforeExecute(Thread t, Runnable r) { }
1473
1474 /**
1475 * Method invoked upon completion of execution of the given Runnable.
1476 * This method is invoked by the thread that executed the task. If
1477 * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1478 * or <tt>Error</tt> that caused execution to terminate abruptly.
1479 *
1480 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1481 * {@link FutureTask}) either explicitly or via methods such as
1482 * <tt>submit</tt>, these task objects catch and maintain
1483 * computational exceptions, and so they do not cause abrupt
1484 * termination, and the internal exceptions are <em>not</em>
1485 * passed to this method.
1486 *
1487 * <p>This implementation does nothing, but may be customized in
1488 * subclasses. Note: To properly nest multiple overridings, subclasses
1489 * should generally invoke <tt>super.afterExecute</tt> at the
1490 * beginning of this method.
1491 *
1492 * @param r the runnable that has completed.
1493 * @param t the exception that caused termination, or null if
1494 * execution completed normally.
1495 */
1496 protected void afterExecute(Runnable r, Throwable t) { }
1497
1498 /**
1499 * Method invoked when the Executor has terminated. Default
1500 * implementation does nothing. Note: To properly nest multiple
1501 * overridings, subclasses should generally invoke
1502 * <tt>super.terminated</tt> within this method.
1503 */
1504 protected void terminated() { }
1505
1506 /**
1507 * A handler for rejected tasks that runs the rejected task
1508 * directly in the calling thread of the <tt>execute</tt> method,
1509 * unless the executor has been shut down, in which case the task
1510 * is discarded.
1511 */
1512 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1513 /**
1514 * Creates a <tt>CallerRunsPolicy</tt>.
1515 */
1516 public CallerRunsPolicy() { }
1517
1518 /**
1519 * Executes task r in the caller's thread, unless the executor
1520 * has been shut down, in which case the task is discarded.
1521 * @param r the runnable task requested to be executed
1522 * @param e the executor attempting to execute this task
1523 */
1524 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1525 if (!e.isShutdown()) {
1526 r.run();
1527 }
1528 }
1529 }
1530
1531 /**
1532 * A handler for rejected tasks that throws a
1533 * <tt>RejectedExecutionException</tt>.
1534 */
1535 public static class AbortPolicy implements RejectedExecutionHandler {
1536 /**
1537 * Creates an <tt>AbortPolicy</tt>.
1538 */
1539 public AbortPolicy() { }
1540
1541 /**
1542 * Always throws RejectedExecutionException.
1543 * @param r the runnable task requested to be executed
1544 * @param e the executor attempting to execute this task
1545 * @throws RejectedExecutionException always.
1546 */
1547 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1548 throw new RejectedExecutionException();
1549 }
1550 }
1551
1552 /**
1553 * A handler for rejected tasks that silently discards the
1554 * rejected task.
1555 */
1556 public static class DiscardPolicy implements RejectedExecutionHandler {
1557 /**
1558 * Creates a <tt>DiscardPolicy</tt>.
1559 */
1560 public DiscardPolicy() { }
1561
1562 /**
1563 * Does nothing, which has the effect of discarding task r.
1564 * @param r the runnable task requested to be executed
1565 * @param e the executor attempting to execute this task
1566 */
1567 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1568 }
1569 }
1570
1571 /**
1572 * A handler for rejected tasks that discards the oldest unhandled
1573 * request and then retries <tt>execute</tt>, unless the executor
1574 * is shut down, in which case the task is discarded.
1575 */
1576 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1577 /**
1578 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1579 */
1580 public DiscardOldestPolicy() { }
1581
1582 /**
1583 * Obtains and ignores the next task that the executor
1584 * would otherwise execute, if one is immediately available,
1585 * and then retries execution of task r, unless the executor
1586 * is shut down, in which case task r is instead discarded.
1587 * @param r the runnable task requested to be executed
1588 * @param e the executor attempting to execute this task
1589 */
1590 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1591 if (!e.isShutdown()) {
1592 e.getQueue().poll();
1593 e.execute(r);
1594 }
1595 }
1596 }
1597 }