ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.42
Committed: Wed Dec 17 17:00:24 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.41: +7 -0 lines
Log Message:
Export delegation wrappers; fix/add documentation

File Contents

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