ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.28
Committed: Sat Sep 27 12:22:40 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.27: +2 -1 lines
Log Message:
Use "unit" instead of "granularity"; add Executors link to first sentence of TPE

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.*;
10
11 /**
12 * An {@link ExecutorService} that executes each submitted task using
13 * one of possibly several pooled threads, normally configured
14 * using {@link Executors} factory methods.
15 *
16 * <p>Thread pools address two different problems: they usually
17 * provide improved performance when executing large numbers of
18 * asynchronous tasks, due to reduced per-task invocation overhead,
19 * and they provide a means of bounding and managing the resources,
20 * including threads, consumed when executing a collection of tasks.
21 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
22 * statistics, such as the number of completed tasks.
23 *
24 * <p>To be useful across a wide range of contexts, this class
25 * provides many adjustable parameters and extensibility
26 * hooks. However, programmers are urged to use the more convenient
27 * {@link Executors} factory methods {@link
28 * Executors#newCachedThreadPool} (unbounded thread pool, with
29 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
30 * (fixed size thread pool) and {@link
31 * Executors#newSingleThreadExecutor} (single background thread), that
32 * preconfigure settings for the most common usage
33 * scenarios. Otherwise, use the following guide when manually
34 * configuring and tuning this class:
35 *
36 * <dl>
37 *
38 * <dt>Core and maximum pool sizes</dt>
39 *
40 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
41 * pool size
42 * (see {@link ThreadPoolExecutor#getPoolSize})
43 * according to the bounds set by corePoolSize
44 * (see {@link ThreadPoolExecutor#getCorePoolSize})
45 * and
46 * maximumPoolSize
47 * (see {@link ThreadPoolExecutor#getMaximumPoolSize}).
48 * When a new task is submitted in method {@link
49 * ThreadPoolExecutor#execute}, and fewer than corePoolSize threads
50 * are running, a new thread is created to handle the request, even if
51 * other worker threads are idle. If there are more than
52 * corePoolSize but less than maximumPoolSize threads running, a new
53 * thread will be created only if the queue is full. By setting
54 * corePoolSize and maximumPoolSize the same, you create a fixed-size
55 * thread pool. By setting maximumPoolSize to an essentially unbounded
56 * value such as <tt>Integer.MAX_VALUE</tt>, you allow the pool to
57 * accommodate an arbitrary number of concurrent tasks. Most typically,
58 * core and maximum pool sizes are set only upon construction, but they
59 * may also be changed dynamically using {@link
60 * ThreadPoolExecutor#setCorePoolSize} and {@link
61 * ThreadPoolExecutor#setMaximumPoolSize}. <dd>
62 *
63 * <dt> On-demand construction
64 *
65 * <dd> By default, even core threads are initially created and
66 * started only when needed by new tasks, but this can be overridden
67 * dynamically using method {@link
68 * ThreadPoolExecutor#prestartCoreThread} or
69 * {@link ThreadPoolExecutor#prestartAllCoreThreads}. </dd>
70 *
71 * <dt>Creating new threads</dt>
72 *
73 * <dd>New threads are created using a {@link ThreadFactory}. By
74 * default, threads are created simply with the <tt>new
75 * Thread(Runnable)</tt> constructor, but by supplying a different
76 * ThreadFactory, you can alter the thread's name, thread group,
77 * priority, daemon status, etc. </dd>
78 *
79 * <dt>Keep-alive times</dt>
80 *
81 * <dd>If the pool currently has more than corePoolSize threads,
82 * excess threads will be terminated if they have been idle for more
83 * than the keepAliveTime (see {@link
84 * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
85 * reducing resource consumption when the pool is not being actively
86 * used. If the pool becomes more active later, new threads will be
87 * constructed. This parameter can also be changed dynamically
88 * using method {@link ThreadPoolExecutor#setKeepAliveTime}. Using
89 * a value of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS}
90 * effectively disables idle threads from ever terminating prior
91 * to shut down.
92 * </dd>
93 *
94 * <dt>Queueing</dt>
95 *
96 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
97 * submitted tasks. The use of this queue interacts with pool sizing:
98 *
99 * <ul>
100 *
101 * <li> If fewer than corePoolSize threads are running, the Executor
102 * always prefers adding a new thread
103 * rather than queueing.</li>
104 *
105 * <li> If corePoolSize or more threads are running, the Executor
106 * always prefers queuing a request rather than adding a new
107 * thread.</li>
108 *
109 * <li> If a request cannot be queued, a new thread is created unless
110 * this would exceed maximumPoolSize, in which case, the task will be
111 * rejected.</li>
112 *
113 * </ul>
114 *
115 * There are three general strategies for queuing:
116 * <ol>
117 *
118 * <li> <em> Direct handoffs.</em> A good default choice for a work
119 * queue is a {@link SynchronousQueue} that hands off tasks to threads
120 * without otherwise holding them. Here, an attempt to queue a task
121 * will fail if no threads are immediately available to run it, so a
122 * new thread will be constructed. This policy avoids lockups when
123 * handling sets of requests that might have internal dependencies.
124 * Direct handoffs generally require unbounded maximumPoolSizes to
125 * avoid rejection of new submitted tasks. This in turn admits the
126 * possibility of unbounded thread growth when commands continue to
127 * arrive on average faster than they can be processed. </li>
128 *
129 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
130 * example a {@link LinkedBlockingQueue} without a predefined
131 * capacity) will cause new tasks to be queued in cases where all
132 * corePoolSize threads are busy. Thus, no more than corePoolSize
133 * threads will ever be created. (And the value of the maximumPoolSize
134 * therefore doesn't have any effect.) This may be appropriate when
135 * each task is completely independent of others, so tasks cannot
136 * affect each others execution; for example, in a web page server.
137 * While this style of queuing can be useful in smoothing out
138 * transient bursts of requests, it admits the possibility of
139 * unbounded work queue growth when commands continue to arrive on
140 * average faster than they can be processed. </li>
141 *
142 * <li><em>Bounded queues.</em> A bounded queue (for example, an
143 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
144 * used with finite maximumPoolSizes, but can be more difficult to
145 * tune and control. Queue sizes and maximum pool sizes may be traded
146 * off for each other: Using large queues and small pools minimizes
147 * CPU usage, OS resources, and context-switching overhead, but can
148 * lead to artificially low throughput. If tasks frequently block (for
149 * example if they are I/O bound), a system may be able to schedule
150 * time for more threads than you otherwise allow. Use of small queues
151 * generally requires larger pool sizes, which keeps CPUs busier but
152 * may encounter unacceptable scheduling overhead, which also
153 * decreases throughput. </li>
154 *
155 * </ol>
156 *
157 * </dd>
158 *
159 * <dt>Rejected tasks</dt>
160 *
161 * <dd> New tasks submitted in method {@link
162 * ThreadPoolExecutor#execute} will be <em>rejected</em> when the
163 * Executor has been shut down, and also when the Executor uses finite
164 * bounds for both maximum threads and work queue capacity, and is
165 * saturated. In either case, the <tt>execute</tt> method invokes the
166 * {@link RejectedExecutionHandler#rejectedExecution} method of its
167 * {@link RejectedExecutionHandler}. Four predefined handler policies
168 * are provided:
169 *
170 * <ol>
171 *
172 * <li> In the
173 * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
174 * runtime {@link RejectedExecutionException} upon rejection. </li>
175 *
176 * <li> In {@link
177 * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
178 * <tt>execute</tt> itself runs the task. This provides a simple
179 * feedback control mechanism that will slow down the rate that new
180 * tasks are submitted. </li>
181 *
182 * <li> In {@link ThreadPoolExecutor.DiscardPolicy},
183 * a task that cannot be executed is simply dropped. </li>
184 *
185 * <li>In {@link
186 * ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not
187 * shut down, the task at the head of the work queue is dropped, and
188 * then execution is retried (which can fail again, causing this to be
189 * repeated.) </li>
190 *
191 * </ol>
192 *
193 * It is possible to define and use other kinds of {@link
194 * RejectedExecutionHandler} classes. Doing so requires some care
195 * especially when policies are designed to work only under particular
196 * capacity or queueing policies. </dd>
197 *
198 * <dt>Hook methods</dt>
199 *
200 * <dd>This class provides <tt>protected</tt> overridable {@link
201 * ThreadPoolExecutor#beforeExecute} and {@link
202 * ThreadPoolExecutor#afterExecute} methods that are called before and
203 * after execution of each task. These can be used to manipulate the
204 * execution environment, for example, reinitializing ThreadLocals,
205 * gathering statistics, or adding log entries. Additionally, method
206 * {@link ThreadPoolExecutor#terminated} can be overridden to perform
207 * any special processing that needs to be done once the Executor has
208 * fully terminated.</dd>
209 *
210 * <dt>Queue maintenance</dt>
211 *
212 * <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to
213 * the work queue for purposes of monitoring and debugging. Use of
214 * this method for any other purpose is strongly discouraged. Two
215 * supplied methods, {@link ThreadPoolExecutor#remove} and {@link
216 * ThreadPoolExecutor#purge} are available to assist in storage
217 * reclamation when large numbers of queued tasks become
218 * cancelled.</dd> </dl>
219 *
220 * @since 1.5
221 * @author Doug Lea
222 */
223 public class ThreadPoolExecutor implements ExecutorService {
224 /**
225 * Queue used for holding tasks and handing off to worker threads.
226 */
227 private final BlockingQueue<Runnable> workQueue;
228
229 /**
230 * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
231 * workers set.
232 */
233 private final ReentrantLock mainLock = new ReentrantLock();
234
235 /**
236 * Wait condition to support awaitTermination
237 */
238 private final Condition termination = mainLock.newCondition();
239
240 /**
241 * Set containing all worker threads in pool.
242 */
243 private final HashSet<Worker> workers = new HashSet<Worker>();
244
245 /**
246 * Timeout in nanosecods for idle threads waiting for work.
247 * Threads use this timeout only when there are more than
248 * corePoolSize present. Otherwise they wait forever for new work.
249 */
250 private volatile long keepAliveTime;
251
252 /**
253 * Core pool size, updated only while holding mainLock,
254 * but volatile to allow concurrent readability even
255 * during updates.
256 */
257 private volatile int corePoolSize;
258
259 /**
260 * Maximum pool size, updated only while holding mainLock
261 * but volatile to allow concurrent readability even
262 * during updates.
263 */
264 private volatile int maximumPoolSize;
265
266 /**
267 * Current pool size, updated only while holding mainLock
268 * but volatile to allow concurrent readability even
269 * during updates.
270 */
271 private volatile int poolSize;
272
273 /**
274 * Lifecycle state
275 */
276 private volatile int runState;
277
278 // Special values for runState
279 /** Normal, not-shutdown mode */
280 private static final int RUNNING = 0;
281 /** Controlled shutdown mode */
282 private static final int SHUTDOWN = 1;
283 /** Immediate shutdown mode */
284 private static final int STOP = 2;
285 /** Final state */
286 private static final int TERMINATED = 3;
287
288 /**
289 * Handler called when saturated or shutdown in execute.
290 */
291 private volatile RejectedExecutionHandler handler = defaultHandler;
292
293 /**
294 * Factory for new threads.
295 */
296 private volatile ThreadFactory threadFactory = defaultThreadFactory;
297
298 /**
299 * Tracks largest attained pool size.
300 */
301 private int largestPoolSize;
302
303 /**
304 * Counter for completed tasks. Updated only on termination of
305 * worker threads.
306 */
307 private long completedTaskCount;
308
309 /**
310 * The default thread factory
311 */
312 private static final ThreadFactory defaultThreadFactory =
313 new ThreadFactory() {
314 public Thread newThread(Runnable r) {
315 return new Thread(r);
316 }
317 };
318
319 /**
320 * The default rejectect execution handler
321 */
322 private static final RejectedExecutionHandler defaultHandler =
323 new AbortPolicy();
324
325 /**
326 * Invoke the rejected execution handler for the given command.
327 */
328 void reject(Runnable command) {
329 handler.rejectedExecution(command, this);
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 (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
464 it.next().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. It may be more convenient to use one of
642 * the {@link Executors} factory methods instead of this general
643 * 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 the
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 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 the
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 the
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 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 the
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 (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
834 it.next().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 shutdownNow() {
850 boolean fullyTerminated = false;
851 mainLock.lock();
852 try {
853 if (workers.size() > 0) {
854 if (runState != TERMINATED)
855 runState = STOP;
856 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
857 it.next().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 return Arrays.asList(workQueue.toArray());
870 }
871
872 public boolean isShutdown() {
873 return runState != RUNNING;
874 }
875
876 /**
877 * Return true if this executor is in the process of terminating
878 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
879 * completely terminated. This method may be useful for
880 * debugging. A return of <tt>true</tt> reported a sufficient
881 * period after shutdown may indicate that submitted tasks have
882 * ignored or suppressed interruption, causing this executor not
883 * to properly terminate.
884 * @return true if terminating but not yet terminated.
885 */
886 public boolean isTerminating() {
887 return runState == STOP;
888 }
889
890 public boolean isTerminated() {
891 return runState == TERMINATED;
892 }
893
894 public boolean awaitTermination(long timeout, TimeUnit unit)
895 throws InterruptedException {
896 mainLock.lock();
897 try {
898 long nanos = unit.toNanos(timeout);
899 for (;;) {
900 if (runState == TERMINATED)
901 return true;
902 if (nanos <= 0)
903 return false;
904 nanos = termination.awaitNanos(nanos);
905 }
906 } finally {
907 mainLock.unlock();
908 }
909 }
910
911 /**
912 * Invokes <tt>shutdown</tt> when this executor is no longer
913 * referenced.
914 */
915 protected void finalize() {
916 shutdown();
917 }
918
919 /**
920 * Sets the thread factory used to create new threads.
921 *
922 * @param threadFactory the new thread factory
923 * @see #getThreadFactory
924 */
925 public void setThreadFactory(ThreadFactory threadFactory) {
926 this.threadFactory = threadFactory;
927 }
928
929 /**
930 * Returns the thread factory used to create new threads.
931 *
932 * @return the current thread factory
933 * @see #setThreadFactory
934 */
935 public ThreadFactory getThreadFactory() {
936 return threadFactory;
937 }
938
939 /**
940 * Sets a new handler for unexecutable tasks.
941 *
942 * @param handler the new handler
943 * @see #getRejectedExecutionHandler
944 */
945 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
946 this.handler = handler;
947 }
948
949 /**
950 * Returns the current handler for unexecutable tasks.
951 *
952 * @return the current handler
953 * @see #setRejectedExecutionHandler
954 */
955 public RejectedExecutionHandler getRejectedExecutionHandler() {
956 return handler;
957 }
958
959 /**
960 * Returns the task queue used by this executor. Access to the
961 * task queue is intended primarily for debugging and monitoring.
962 * This queue may be in active use. Retrieving the task queue
963 * does not prevent queued tasks from executing.
964 *
965 * @return the task queue
966 */
967 public BlockingQueue<Runnable> getQueue() {
968 return workQueue;
969 }
970
971 /**
972 * Removes this task from internal queue if it is present, thus
973 * causing it not to be run if it has not already started. This
974 * method may be useful as one part of a cancellation scheme.
975 *
976 * @param task the task to remove
977 * @return true if the task was removed
978 */
979 public boolean remove(Runnable task) {
980 return getQueue().remove(task);
981 }
982
983
984 /**
985 * Tries to remove from the work queue all {@link Cancellable}
986 * tasks that have been cancelled. This method can be useful as a
987 * storage reclamation operation, that has no other impact on
988 * functionality. Cancelled tasks are never executed, but may
989 * accumulate in work queues until worker threads can actively
990 * remove them. Invoking this method instead tries to remove them now.
991 * However, this method may fail to remove tasks in
992 * the presence of interference by other threads.
993 */
994
995 public void purge() {
996 // Fail if we encounter interference during traversal
997 try {
998 Iterator<Runnable> it = getQueue().iterator();
999 while (it.hasNext()) {
1000 Runnable r = it.next();
1001 if (r instanceof Cancellable) {
1002 Cancellable c = (Cancellable)r;
1003 if (c.isCancelled())
1004 it.remove();
1005 }
1006 }
1007 }
1008 catch(ConcurrentModificationException ex) {
1009 return;
1010 }
1011 }
1012
1013 /**
1014 * Sets the core number of threads. This overrides any value set
1015 * in the constructor. If the new value is smaller than the
1016 * current value, excess existing threads will be terminated when
1017 * they next become idle.
1018 *
1019 * @param corePoolSize the new core size
1020 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1021 * less than zero
1022 * @see #getCorePoolSize
1023 */
1024 public void setCorePoolSize(int corePoolSize) {
1025 if (corePoolSize < 0)
1026 throw new IllegalArgumentException();
1027 mainLock.lock();
1028 try {
1029 int extra = this.corePoolSize - corePoolSize;
1030 this.corePoolSize = corePoolSize;
1031 if (extra > 0 && poolSize > corePoolSize) {
1032 Iterator<Worker> it = workers.iterator();
1033 while (it.hasNext() &&
1034 extra > 0 &&
1035 poolSize > corePoolSize &&
1036 workQueue.remainingCapacity() == 0) {
1037 it.next().interruptIfIdle();
1038 --extra;
1039 }
1040 }
1041
1042 } finally {
1043 mainLock.unlock();
1044 }
1045 }
1046
1047 /**
1048 * Returns the core number of threads.
1049 *
1050 * @return the core number of threads
1051 * @see #setCorePoolSize
1052 */
1053 public int getCorePoolSize() {
1054 return corePoolSize;
1055 }
1056
1057 /**
1058 * Start a core thread, causing it to idly wait for work. This
1059 * overrides the default policy of starting core threads only when
1060 * new tasks are executed. This method will return <tt>false</tt>
1061 * if all core threads have already been started.
1062 * @return true if a thread was started
1063 */
1064 public boolean prestartCoreThread() {
1065 return addIfUnderCorePoolSize(null);
1066 }
1067
1068 /**
1069 * Start all core threads, causing them to idly wait for work. This
1070 * overrides the default policy of starting core threads only when
1071 * new tasks are executed.
1072 * @return the number of threads started.
1073 */
1074 public int prestartAllCoreThreads() {
1075 int n = 0;
1076 while (addIfUnderCorePoolSize(null))
1077 ++n;
1078 return n;
1079 }
1080
1081 /**
1082 * Sets the maximum allowed number of threads. This overrides any
1083 * value set in the constructor. If the new value is smaller than
1084 * the current value, excess existing threads will be
1085 * terminated when they next become idle.
1086 *
1087 * @param maximumPoolSize the new maximum
1088 * @throws IllegalArgumentException if maximumPoolSize less than zero or
1089 * the {@link #getCorePoolSize core pool size}
1090 * @see #getMaximumPoolSize
1091 */
1092 public void setMaximumPoolSize(int maximumPoolSize) {
1093 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1094 throw new IllegalArgumentException();
1095 mainLock.lock();
1096 try {
1097 int extra = this.maximumPoolSize - maximumPoolSize;
1098 this.maximumPoolSize = maximumPoolSize;
1099 if (extra > 0 && poolSize > maximumPoolSize) {
1100 Iterator<Worker> it = workers.iterator();
1101 while (it.hasNext() &&
1102 extra > 0 &&
1103 poolSize > maximumPoolSize) {
1104 it.next().interruptIfIdle();
1105 --extra;
1106 }
1107 }
1108 } finally {
1109 mainLock.unlock();
1110 }
1111 }
1112
1113 /**
1114 * Returns the maximum allowed number of threads.
1115 *
1116 * @return the maximum allowed number of threads
1117 * @see #setMaximumPoolSize
1118 */
1119 public int getMaximumPoolSize() {
1120 return maximumPoolSize;
1121 }
1122
1123 /**
1124 * Sets the time limit for which threads may remain idle before
1125 * being terminated. If there are more than the core number of
1126 * threads currently in the pool, after waiting this amount of
1127 * time without processing a task, excess threads will be
1128 * terminated. This overrides any value set in the constructor.
1129 * @param time the time to wait. A time value of zero will cause
1130 * excess threads to terminate immediately after executing tasks.
1131 * @param unit the time unit of the time argument
1132 * @throws IllegalArgumentException if time less than zero
1133 * @see #getKeepAliveTime
1134 */
1135 public void setKeepAliveTime(long time, TimeUnit unit) {
1136 if (time < 0)
1137 throw new IllegalArgumentException();
1138 this.keepAliveTime = unit.toNanos(time);
1139 }
1140
1141 /**
1142 * Returns the thread keep-alive time, which is the amount of time
1143 * which threads in excess of the core pool size may remain
1144 * idle before being terminated.
1145 *
1146 * @param unit the desired time unit of the result
1147 * @return the time limit
1148 * @see #setKeepAliveTime
1149 */
1150 public long getKeepAliveTime(TimeUnit unit) {
1151 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1152 }
1153
1154 /* Statistics */
1155
1156 /**
1157 * Returns the current number of threads in the pool.
1158 *
1159 * @return the number of threads
1160 */
1161 public int getPoolSize() {
1162 return poolSize;
1163 }
1164
1165 /**
1166 * Returns the approximate number of threads that are actively
1167 * executing tasks.
1168 *
1169 * @return the number of threads
1170 */
1171 public int getActiveCount() {
1172 mainLock.lock();
1173 try {
1174 int n = 0;
1175 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1176 if (it.next().isActive())
1177 ++n;
1178 }
1179 return n;
1180 } finally {
1181 mainLock.unlock();
1182 }
1183 }
1184
1185 /**
1186 * Returns the largest number of threads that have ever
1187 * simultaneously been in the pool.
1188 *
1189 * @return the number of threads
1190 */
1191 public int getLargestPoolSize() {
1192 mainLock.lock();
1193 try {
1194 return largestPoolSize;
1195 } finally {
1196 mainLock.unlock();
1197 }
1198 }
1199
1200 /**
1201 * Returns the approximate total number of tasks that have been
1202 * scheduled for execution. Because the states of tasks and
1203 * threads may change dynamically during computation, the returned
1204 * value is only an approximation, but one that does not ever
1205 * decrease across successive calls.
1206 *
1207 * @return the number of tasks
1208 */
1209 public long getTaskCount() {
1210 mainLock.lock();
1211 try {
1212 long n = completedTaskCount;
1213 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
1214 Worker w = it.next();
1215 n += w.completedTasks;
1216 if (w.isActive())
1217 ++n;
1218 }
1219 return n + workQueue.size();
1220 } finally {
1221 mainLock.unlock();
1222 }
1223 }
1224
1225 /**
1226 * Returns the approximate total number of tasks that have
1227 * completed execution. Because the states of tasks and threads
1228 * may change dynamically during computation, the returned value
1229 * is only an approximation, but one that does not ever decrease
1230 * across successive calls.
1231 *
1232 * @return the number of tasks
1233 */
1234 public long getCompletedTaskCount() {
1235 mainLock.lock();
1236 try {
1237 long n = completedTaskCount;
1238 for (Iterator<Worker> it = workers.iterator(); it.hasNext(); )
1239 n += it.next().completedTasks;
1240 return n;
1241 } finally {
1242 mainLock.unlock();
1243 }
1244 }
1245
1246 /**
1247 * Method invoked prior to executing the given Runnable in the
1248 * given thread. This method may be used to re-initialize
1249 * ThreadLocals, or to perform logging. Note: To properly nest
1250 * multiple overridings, subclasses should generally invoke
1251 * <tt>super.beforeExecute</tt> at the end of this method.
1252 *
1253 * @param t the thread that will run task r.
1254 * @param r the task that will be executed.
1255 */
1256 protected void beforeExecute(Thread t, Runnable r) { }
1257
1258 /**
1259 * Method invoked upon completion of execution of the given
1260 * Runnable. If non-null, the Throwable is the uncaught exception
1261 * that caused execution to terminate abruptly. Note: To properly
1262 * nest multiple overridings, subclasses should generally invoke
1263 * <tt>super.afterExecute</tt> at the beginning of this method.
1264 *
1265 * @param r the runnable that has completed.
1266 * @param t the exception that caused termination, or null if
1267 * execution completed normally.
1268 */
1269 protected void afterExecute(Runnable r, Throwable t) { }
1270
1271 /**
1272 * Method invoked when the Executor has terminated. Default
1273 * implementation does nothing. Note: To properly nest multiple
1274 * overridings, subclasses should generally invoke
1275 * <tt>super.terminated</tt> within this method.
1276 */
1277 protected void terminated() { }
1278
1279 /**
1280 * A handler for rejected tasks that runs the rejected task
1281 * directly in the calling thread of the <tt>execute</tt> method,
1282 * unless the executor has been shut down, in which case the task
1283 * is discarded.
1284 */
1285 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1286
1287 /**
1288 * Creates a <tt>CallerRunsPolicy</tt>.
1289 */
1290 public CallerRunsPolicy() { }
1291
1292 /**
1293 * Executes task r in the caller's thread, unless the executor
1294 * has been shut down, in which case the task is discarded.
1295 * @param r the runnable task requested to be executed
1296 * @param e the executor attempting to execute this task
1297 */
1298 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1299 if (!e.isShutdown()) {
1300 r.run();
1301 }
1302 }
1303 }
1304
1305 /**
1306 * A handler for rejected tasks that throws a
1307 * <tt>RejectedExecutionException</tt>.
1308 */
1309 public static class AbortPolicy implements RejectedExecutionHandler {
1310
1311 /**
1312 * Creates a <tt>AbortPolicy</tt>.
1313 */
1314 public AbortPolicy() { }
1315
1316 /**
1317 * Always throws RejectedExecutionException
1318 * @param r the runnable task requested to be executed
1319 * @param e the executor attempting to execute this task
1320 * @throws RejectedExecutionException always.
1321 */
1322 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1323 throw new RejectedExecutionException();
1324 }
1325 }
1326
1327 /**
1328 * A handler for rejected tasks that silently discards the
1329 * rejected task.
1330 */
1331 public static class DiscardPolicy implements RejectedExecutionHandler {
1332
1333 /**
1334 * Creates <tt>DiscardPolicy</tt>.
1335 */
1336 public DiscardPolicy() { }
1337
1338 /**
1339 * Does nothing, which has the effect of discarding task r.
1340 * @param r the runnable task requested to be executed
1341 * @param e the executor attempting to execute this task
1342 */
1343 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1344 }
1345 }
1346
1347 /**
1348 * A handler for rejected tasks that discards the oldest unhandled
1349 * request and then retries <tt>execute</tt>, unless the executor
1350 * is shut down, in which case the task is discarded.
1351 */
1352 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1353 /**
1354 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1355 */
1356 public DiscardOldestPolicy() { }
1357
1358 /**
1359 * Obtains and ignores the next task that the executor
1360 * would otherwise execute, if one is immediately available,
1361 * and then retries execution of task r, unless the executor
1362 * is shut down, in which case task r is instead discarded.
1363 * @param r the runnable task requested to be executed
1364 * @param e the executor attempting to execute this task
1365 */
1366 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1367 if (!e.isShutdown()) {
1368 e.getQueue().poll();
1369 e.execute(r);
1370 }
1371 }
1372 }
1373 }