ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.41
Committed: Wed Dec 10 14:57:13 2003 UTC (20 years, 5 months ago) by tim
Branch: MAIN
Changes since 1.40: +7 -2 lines
Log Message:
Don't allocate an empty Runnable[] each time toArray() is called.

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 boolean fullyTerminated = false;
828 mainLock.lock();
829 try {
830 if (workers.size() > 0) {
831 if (runState == RUNNING) // don't override shutdownNow
832 runState = SHUTDOWN;
833 for (Worker w: workers)
834 w.interruptIfIdle();
835 }
836 else { // If no workers, trigger full termination now
837 fullyTerminated = true;
838 runState = TERMINATED;
839 termination.signalAll();
840 }
841 } finally {
842 mainLock.unlock();
843 }
844 if (fullyTerminated)
845 terminated();
846 }
847
848
849 public List<Runnable> shutdownNow() {
850 boolean fullyTerminated = false;
851 mainLock.lock();
852 try {
853 if (workers.size() > 0) {
854 if (runState != TERMINATED)
855 runState = STOP;
856 for (Worker w : workers)
857 w.interruptNow();
858 }
859 else { // If no workers, trigger full termination now
860 fullyTerminated = true;
861 runState = TERMINATED;
862 termination.signalAll();
863 }
864 } finally {
865 mainLock.unlock();
866 }
867 if (fullyTerminated)
868 terminated();
869
870 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
871 }
872
873 public boolean isShutdown() {
874 return runState != RUNNING;
875 }
876
877 /**
878 * Return true if this executor is in the process of terminating
879 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
880 * completely terminated. This method may be useful for
881 * debugging. A return of <tt>true</tt> reported a sufficient
882 * period after shutdown may indicate that submitted tasks have
883 * ignored or suppressed interruption, causing this executor not
884 * to properly terminate.
885 * @return true if terminating but not yet terminated.
886 */
887 public boolean isTerminating() {
888 return runState == STOP;
889 }
890
891 public boolean isTerminated() {
892 return runState == TERMINATED;
893 }
894
895 public boolean awaitTermination(long timeout, TimeUnit unit)
896 throws InterruptedException {
897 mainLock.lock();
898 try {
899 long nanos = unit.toNanos(timeout);
900 for (;;) {
901 if (runState == TERMINATED)
902 return true;
903 if (nanos <= 0)
904 return false;
905 nanos = termination.awaitNanos(nanos);
906 }
907 } finally {
908 mainLock.unlock();
909 }
910 }
911
912 /**
913 * Invokes <tt>shutdown</tt> when this executor is no longer
914 * referenced.
915 */
916 protected void finalize() {
917 shutdown();
918 }
919
920 /**
921 * Sets the thread factory used to create new threads.
922 *
923 * @param threadFactory the new thread factory
924 * @throws NullPointerException if threadFactory is null
925 * @see #getThreadFactory
926 */
927 public void setThreadFactory(ThreadFactory threadFactory) {
928 if (threadFactory == null)
929 throw new NullPointerException();
930 this.threadFactory = threadFactory;
931 }
932
933 /**
934 * Returns the thread factory used to create new threads.
935 *
936 * @return the current thread factory
937 * @see #setThreadFactory
938 */
939 public ThreadFactory getThreadFactory() {
940 return threadFactory;
941 }
942
943 /**
944 * Sets a new handler for unexecutable tasks.
945 *
946 * @param handler the new handler
947 * @throws NullPointerException if handler is null
948 * @see #getRejectedExecutionHandler
949 */
950 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
951 if (handler == null)
952 throw new NullPointerException();
953 this.handler = handler;
954 }
955
956 /**
957 * Returns the current handler for unexecutable tasks.
958 *
959 * @return the current handler
960 * @see #setRejectedExecutionHandler
961 */
962 public RejectedExecutionHandler getRejectedExecutionHandler() {
963 return handler;
964 }
965
966 /**
967 * Returns the task queue used by this executor. Access to the
968 * task queue is intended primarily for debugging and monitoring.
969 * This queue may be in active use. Retrieving the task queue
970 * does not prevent queued tasks from executing.
971 *
972 * @return the task queue
973 */
974 public BlockingQueue<Runnable> getQueue() {
975 return workQueue;
976 }
977
978 /**
979 * Removes this task from internal queue if it is present, thus
980 * causing it not to be run if it has not already started. This
981 * method may be useful as one part of a cancellation scheme.
982 *
983 * @param task the task to remove
984 * @return true if the task was removed
985 */
986 public boolean remove(Runnable task) {
987 return getQueue().remove(task);
988 }
989
990
991 /**
992 * Tries to remove from the work queue all {@link Future}
993 * tasks that have been cancelled. This method can be useful as a
994 * storage reclamation operation, that has no other impact on
995 * functionality. Cancelled tasks are never executed, but may
996 * accumulate in work queues until worker threads can actively
997 * remove them. Invoking this method instead tries to remove them now.
998 * However, this method may fail to remove tasks in
999 * the presence of interference by other threads.
1000 */
1001
1002 public void purge() {
1003 // Fail if we encounter interference during traversal
1004 try {
1005 Iterator<Runnable> it = getQueue().iterator();
1006 while (it.hasNext()) {
1007 Runnable r = it.next();
1008 if (r instanceof Future<?>) {
1009 Future<?> c = (Future<?>)r;
1010 if (c.isCancelled())
1011 it.remove();
1012 }
1013 }
1014 }
1015 catch(ConcurrentModificationException ex) {
1016 return;
1017 }
1018 }
1019
1020 /**
1021 * Sets the core number of threads. This overrides any value set
1022 * in the constructor. If the new value is smaller than the
1023 * current value, excess existing threads will be terminated when
1024 * they next become idle. If larger, new threads will, if needed,
1025 * be started to execute any queued tasks.
1026 *
1027 * @param corePoolSize the new core size
1028 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1029 * less than zero
1030 * @see #getCorePoolSize
1031 */
1032 public void setCorePoolSize(int corePoolSize) {
1033 if (corePoolSize < 0)
1034 throw new IllegalArgumentException();
1035 mainLock.lock();
1036 try {
1037 int extra = this.corePoolSize - corePoolSize;
1038 this.corePoolSize = corePoolSize;
1039 if (extra < 0) {
1040 Runnable r;
1041 while (extra++ < 0 && poolSize < corePoolSize &&
1042 (r = workQueue.poll()) != null)
1043 addThread(r).start();
1044 }
1045 else if (extra > 0 && poolSize > corePoolSize) {
1046 Iterator<Worker> it = workers.iterator();
1047 while (it.hasNext() &&
1048 extra-- > 0 &&
1049 poolSize > corePoolSize &&
1050 workQueue.remainingCapacity() == 0)
1051 it.next().interruptIfIdle();
1052 }
1053 } finally {
1054 mainLock.unlock();
1055 }
1056 }
1057
1058 /**
1059 * Returns the core number of threads.
1060 *
1061 * @return the core number of threads
1062 * @see #setCorePoolSize
1063 */
1064 public int getCorePoolSize() {
1065 return corePoolSize;
1066 }
1067
1068 /**
1069 * Start a core thread, causing it to idly wait for work. This
1070 * overrides the default policy of starting core threads only when
1071 * new tasks are executed. This method will return <tt>false</tt>
1072 * if all core threads have already been started.
1073 * @return true if a thread was started
1074 */
1075 public boolean prestartCoreThread() {
1076 return addIfUnderCorePoolSize(null);
1077 }
1078
1079 /**
1080 * Start all core threads, causing them to idly wait for work. This
1081 * overrides the default policy of starting core threads only when
1082 * new tasks are executed.
1083 * @return the number of threads started.
1084 */
1085 public int prestartAllCoreThreads() {
1086 int n = 0;
1087 while (addIfUnderCorePoolSize(null))
1088 ++n;
1089 return n;
1090 }
1091
1092 /**
1093 * Sets the maximum allowed number of threads. This overrides any
1094 * value set in the constructor. If the new value is smaller than
1095 * the current value, excess existing threads will be
1096 * terminated when they next become idle.
1097 *
1098 * @param maximumPoolSize the new maximum
1099 * @throws IllegalArgumentException if maximumPoolSize less than zero or
1100 * the {@link #getCorePoolSize core pool size}
1101 * @see #getMaximumPoolSize
1102 */
1103 public void setMaximumPoolSize(int maximumPoolSize) {
1104 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1105 throw new IllegalArgumentException();
1106 mainLock.lock();
1107 try {
1108 int extra = this.maximumPoolSize - maximumPoolSize;
1109 this.maximumPoolSize = maximumPoolSize;
1110 if (extra > 0 && poolSize > maximumPoolSize) {
1111 Iterator<Worker> it = workers.iterator();
1112 while (it.hasNext() &&
1113 extra > 0 &&
1114 poolSize > maximumPoolSize) {
1115 it.next().interruptIfIdle();
1116 --extra;
1117 }
1118 }
1119 } finally {
1120 mainLock.unlock();
1121 }
1122 }
1123
1124 /**
1125 * Returns the maximum allowed number of threads.
1126 *
1127 * @return the maximum allowed number of threads
1128 * @see #setMaximumPoolSize
1129 */
1130 public int getMaximumPoolSize() {
1131 return maximumPoolSize;
1132 }
1133
1134 /**
1135 * Sets the time limit for which threads may remain idle before
1136 * being terminated. If there are more than the core number of
1137 * threads currently in the pool, after waiting this amount of
1138 * time without processing a task, excess threads will be
1139 * terminated. This overrides any value set in the constructor.
1140 * @param time the time to wait. A time value of zero will cause
1141 * excess threads to terminate immediately after executing tasks.
1142 * @param unit the time unit of the time argument
1143 * @throws IllegalArgumentException if time less than zero
1144 * @see #getKeepAliveTime
1145 */
1146 public void setKeepAliveTime(long time, TimeUnit unit) {
1147 if (time < 0)
1148 throw new IllegalArgumentException();
1149 this.keepAliveTime = unit.toNanos(time);
1150 }
1151
1152 /**
1153 * Returns the thread keep-alive time, which is the amount of time
1154 * which threads in excess of the core pool size may remain
1155 * idle before being terminated.
1156 *
1157 * @param unit the desired time unit of the result
1158 * @return the time limit
1159 * @see #setKeepAliveTime
1160 */
1161 public long getKeepAliveTime(TimeUnit unit) {
1162 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1163 }
1164
1165 /* Statistics */
1166
1167 /**
1168 * Returns the current number of threads in the pool.
1169 *
1170 * @return the number of threads
1171 */
1172 public int getPoolSize() {
1173 return poolSize;
1174 }
1175
1176 /**
1177 * Returns the approximate number of threads that are actively
1178 * executing tasks.
1179 *
1180 * @return the number of threads
1181 */
1182 public int getActiveCount() {
1183 mainLock.lock();
1184 try {
1185 int n = 0;
1186 for (Worker w : workers) {
1187 if (w.isActive())
1188 ++n;
1189 }
1190 return n;
1191 } finally {
1192 mainLock.unlock();
1193 }
1194 }
1195
1196 /**
1197 * Returns the largest number of threads that have ever
1198 * simultaneously been in the pool.
1199 *
1200 * @return the number of threads
1201 */
1202 public int getLargestPoolSize() {
1203 mainLock.lock();
1204 try {
1205 return largestPoolSize;
1206 } finally {
1207 mainLock.unlock();
1208 }
1209 }
1210
1211 /**
1212 * Returns the approximate total number of tasks that have been
1213 * scheduled for execution. Because the states of tasks and
1214 * threads may change dynamically during computation, the returned
1215 * value is only an approximation, but one that does not ever
1216 * decrease across successive calls.
1217 *
1218 * @return the number of tasks
1219 */
1220 public long getTaskCount() {
1221 mainLock.lock();
1222 try {
1223 long n = completedTaskCount;
1224 for (Worker w : workers) {
1225 n += w.completedTasks;
1226 if (w.isActive())
1227 ++n;
1228 }
1229 return n + workQueue.size();
1230 } finally {
1231 mainLock.unlock();
1232 }
1233 }
1234
1235 /**
1236 * Returns the approximate total number of tasks that have
1237 * completed execution. Because the states of tasks and threads
1238 * may change dynamically during computation, the returned value
1239 * is only an approximation, but one that does not ever decrease
1240 * across successive calls.
1241 *
1242 * @return the number of tasks
1243 */
1244 public long getCompletedTaskCount() {
1245 mainLock.lock();
1246 try {
1247 long n = completedTaskCount;
1248 for (Worker w : workers)
1249 n += w.completedTasks;
1250 return n;
1251 } finally {
1252 mainLock.unlock();
1253 }
1254 }
1255
1256 /**
1257 * Method invoked prior to executing the given Runnable in the
1258 * given thread. This method may be used to re-initialize
1259 * ThreadLocals, or to perform logging. Note: To properly nest
1260 * multiple overridings, subclasses should generally invoke
1261 * <tt>super.beforeExecute</tt> at the end of this method.
1262 *
1263 * @param t the thread that will run task r.
1264 * @param r the task that will be executed.
1265 */
1266 protected void beforeExecute(Thread t, Runnable r) { }
1267
1268 /**
1269 * Method invoked upon completion of execution of the given
1270 * Runnable. If non-null, the Throwable is the uncaught exception
1271 * that caused execution to terminate abruptly. Note: To properly
1272 * nest multiple overridings, subclasses should generally invoke
1273 * <tt>super.afterExecute</tt> at the beginning of this method.
1274 *
1275 * @param r the runnable that has completed.
1276 * @param t the exception that caused termination, or null if
1277 * execution completed normally.
1278 */
1279 protected void afterExecute(Runnable r, Throwable t) { }
1280
1281 /**
1282 * Method invoked when the Executor has terminated. Default
1283 * implementation does nothing. Note: To properly nest multiple
1284 * overridings, subclasses should generally invoke
1285 * <tt>super.terminated</tt> within this method.
1286 */
1287 protected void terminated() { }
1288
1289 /**
1290 * A handler for rejected tasks that runs the rejected task
1291 * directly in the calling thread of the <tt>execute</tt> method,
1292 * unless the executor has been shut down, in which case the task
1293 * is discarded.
1294 */
1295 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1296
1297 /**
1298 * Creates a <tt>CallerRunsPolicy</tt>.
1299 */
1300 public CallerRunsPolicy() { }
1301
1302 /**
1303 * Executes task r in the caller's thread, unless the executor
1304 * has been shut down, in which case the task is discarded.
1305 * @param r the runnable task requested to be executed
1306 * @param e the executor attempting to execute this task
1307 */
1308 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1309 if (!e.isShutdown()) {
1310 r.run();
1311 }
1312 }
1313 }
1314
1315 /**
1316 * A handler for rejected tasks that throws a
1317 * <tt>RejectedExecutionException</tt>.
1318 */
1319 public static class AbortPolicy implements RejectedExecutionHandler {
1320
1321 /**
1322 * Creates an <tt>AbortPolicy</tt>.
1323 */
1324 public AbortPolicy() { }
1325
1326 /**
1327 * Always throws RejectedExecutionException
1328 * @param r the runnable task requested to be executed
1329 * @param e the executor attempting to execute this task
1330 * @throws RejectedExecutionException always.
1331 */
1332 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1333 throw new RejectedExecutionException();
1334 }
1335 }
1336
1337 /**
1338 * A handler for rejected tasks that silently discards the
1339 * rejected task.
1340 */
1341 public static class DiscardPolicy implements RejectedExecutionHandler {
1342
1343 /**
1344 * Creates <tt>DiscardPolicy</tt>.
1345 */
1346 public DiscardPolicy() { }
1347
1348 /**
1349 * Does nothing, which has the effect of discarding task r.
1350 * @param r the runnable task requested to be executed
1351 * @param e the executor attempting to execute this task
1352 */
1353 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1354 }
1355 }
1356
1357 /**
1358 * A handler for rejected tasks that discards the oldest unhandled
1359 * request and then retries <tt>execute</tt>, unless the executor
1360 * is shut down, in which case the task is discarded.
1361 */
1362 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1363 /**
1364 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1365 */
1366 public DiscardOldestPolicy() { }
1367
1368 /**
1369 * Obtains and ignores the next task that the executor
1370 * would otherwise execute, if one is immediately available,
1371 * and then retries execution of task r, unless the executor
1372 * is shut down, in which case task r is instead discarded.
1373 * @param r the runnable task requested to be executed
1374 * @param e the executor attempting to execute this task
1375 */
1376 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1377 if (!e.isShutdown()) {
1378 e.getQueue().poll();
1379 e.execute(r);
1380 }
1381 }
1382 }
1383 }