ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.44
Committed: Mon Dec 22 16:25:20 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.43: +12 -3 lines
Log Message:
Simplify FutureTask and AbstractExecutorService internals; improve docs

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 * <p> <b>Extension example</b>. Most extensions of this class
224 * override one or more of the protected hook methods. For example,
225 * here is a subclass that adds a simple pause/resume feature:
226 *
227 * <pre>
228 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
229 * private boolean isPaused;
230 * private ReentrantLock pauseLock = new ReentrantLock();
231 * private Condition unpaused = pauseLock.newCondition();
232 *
233 * public PausableThreadPoolExecutor(...) { super(...); }
234 *
235 * protected void beforeExecute(Thread t, Runnable r) {
236 * super.beforeExecute(t, r);
237 * pauseLock.lock();
238 * try {
239 * while (isPaused) unpaused.await();
240 * } catch(InterruptedException ie) {
241 * Thread.currentThread().interrupt();
242 * } finally {
243 * pauseLock.unlock();
244 * }
245 * }
246 *
247 * public void pause() {
248 * pauseLock.lock();
249 * try {
250 * isPaused = true;
251 * } finally {
252 * pauseLock.unlock();
253 * }
254 * }
255 *
256 * public void resume() {
257 * pauseLock.lock();
258 * try {
259 * isPaused = false;
260 * unpaused.signalAll();
261 * } finally {
262 * pauseLock.unlock();
263 * }
264 * }
265 * }
266 * </pre>
267 * @since 1.5
268 * @author Doug Lea
269 */
270 public class ThreadPoolExecutor extends AbstractExecutorService {
271 /**
272 * Only used to force toArray() to produce a Runnable[].
273 */
274 private static final Runnable[] EMPTY_RUNNABLE_ARRAY = new Runnable[0];
275
276 /**
277 * Permission for checking shutdown
278 */
279 private static final RuntimePermission shutdownPerm =
280 new RuntimePermission("modifyThread");
281
282 /**
283 * Queue used for holding tasks and handing off to worker threads.
284 */
285 private final BlockingQueue<Runnable> workQueue;
286
287 /**
288 * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
289 * workers set.
290 */
291 private final ReentrantLock mainLock = new ReentrantLock();
292
293 /**
294 * Wait condition to support awaitTermination
295 */
296 private final ReentrantLock.ConditionObject termination = mainLock.newCondition();
297
298 /**
299 * Set containing all worker threads in pool.
300 */
301 private final HashSet<Worker> workers = new HashSet<Worker>();
302
303 /**
304 * Timeout in nanoseconds for idle threads waiting for work.
305 * Threads use this timeout only when there are more than
306 * corePoolSize present. Otherwise they wait forever for new work.
307 */
308 private volatile long keepAliveTime;
309
310 /**
311 * Core pool size, updated only while holding mainLock,
312 * but volatile to allow concurrent readability even
313 * during updates.
314 */
315 private volatile int corePoolSize;
316
317 /**
318 * Maximum pool size, updated only while holding mainLock
319 * but volatile to allow concurrent readability even
320 * during updates.
321 */
322 private volatile int maximumPoolSize;
323
324 /**
325 * Current pool size, updated only while holding mainLock
326 * but volatile to allow concurrent readability even
327 * during updates.
328 */
329 private volatile int poolSize;
330
331 /**
332 * Lifecycle state
333 */
334 private volatile int runState;
335
336 // Special values for runState
337 /** Normal, not-shutdown mode */
338 private static final int RUNNING = 0;
339 /** Controlled shutdown mode */
340 private static final int SHUTDOWN = 1;
341 /** Immediate shutdown mode */
342 private static final int STOP = 2;
343 /** Final state */
344 private static final int TERMINATED = 3;
345
346 /**
347 * Handler called when saturated or shutdown in execute.
348 */
349 private volatile RejectedExecutionHandler handler;
350
351 /**
352 * Factory for new threads.
353 */
354 private volatile ThreadFactory threadFactory;
355
356 /**
357 * Tracks largest attained pool size.
358 */
359 private int largestPoolSize;
360
361 /**
362 * Counter for completed tasks. Updated only on termination of
363 * worker threads.
364 */
365 private long completedTaskCount;
366
367 /**
368 * The default rejected execution handler
369 */
370 private static final RejectedExecutionHandler defaultHandler =
371 new AbortPolicy();
372
373 /**
374 * Invoke the rejected execution handler for the given command.
375 */
376 void reject(Runnable command) {
377 handler.rejectedExecution(command, this);
378 }
379
380
381
382 /**
383 * Create and return a new thread running firstTask as its first
384 * task. Call only while holding mainLock
385 * @param firstTask the task the new thread should run first (or
386 * null if none)
387 * @return the new thread
388 */
389 private Thread addThread(Runnable firstTask) {
390 Worker w = new Worker(firstTask);
391 Thread t = threadFactory.newThread(w);
392 w.thread = t;
393 workers.add(w);
394 int nt = ++poolSize;
395 if (nt > largestPoolSize)
396 largestPoolSize = nt;
397 return t;
398 }
399
400
401
402 /**
403 * Create and start a new thread running firstTask as its first
404 * task, only if less than corePoolSize threads are running.
405 * @param firstTask the task the new thread should run first (or
406 * null if none)
407 * @return true if successful.
408 */
409 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
410 Thread t = null;
411 mainLock.lock();
412 try {
413 if (poolSize < corePoolSize)
414 t = addThread(firstTask);
415 } finally {
416 mainLock.unlock();
417 }
418 if (t == null)
419 return false;
420 t.start();
421 return true;
422 }
423
424 /**
425 * Create and start a new thread only if less than maximumPoolSize
426 * threads are running. The new thread runs as its first task the
427 * next task in queue, or if there is none, the given task.
428 * @param firstTask the task the new thread should run first (or
429 * null if none)
430 * @return null on failure, else the first task to be run by new thread.
431 */
432 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
433 Thread t = null;
434 Runnable next = null;
435 mainLock.lock();
436 try {
437 if (poolSize < maximumPoolSize) {
438 next = workQueue.poll();
439 if (next == null)
440 next = firstTask;
441 t = addThread(next);
442 }
443 } finally {
444 mainLock.unlock();
445 }
446 if (t == null)
447 return null;
448 t.start();
449 return next;
450 }
451
452
453 /**
454 * Get the next task for a worker thread to run.
455 * @return the task
456 * @throws InterruptedException if interrupted while waiting for task
457 */
458 private Runnable getTask() throws InterruptedException {
459 for (;;) {
460 switch(runState) {
461 case RUNNING: {
462 if (poolSize <= corePoolSize) // untimed wait if core
463 return workQueue.take();
464
465 long timeout = keepAliveTime;
466 if (timeout <= 0) // die immediately for 0 timeout
467 return null;
468 Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
469 if (r != null)
470 return r;
471 if (poolSize > corePoolSize) // timed out
472 return null;
473 // else, after timeout, pool shrank so shouldn't die, so retry
474 break;
475 }
476
477 case SHUTDOWN: {
478 // Help drain queue
479 Runnable r = workQueue.poll();
480 if (r != null)
481 return r;
482
483 // Check if can terminate
484 if (workQueue.isEmpty()) {
485 interruptIdleWorkers();
486 return null;
487 }
488
489 // There could still be delayed tasks in queue.
490 // Wait for one, re-checking state upon interruption
491 try {
492 return workQueue.take();
493 }
494 catch(InterruptedException ignore) {
495 }
496 break;
497 }
498
499 case STOP:
500 return null;
501 default:
502 assert false;
503 }
504 }
505 }
506
507 /**
508 * Wake up all threads that might be waiting for tasks.
509 */
510 void interruptIdleWorkers() {
511 mainLock.lock();
512 try {
513 for (Worker w : workers)
514 w.interruptIfIdle();
515 } finally {
516 mainLock.unlock();
517 }
518 }
519
520 /**
521 * Perform bookkeeping for a terminated worker thread.
522 * @param w the worker
523 */
524 private void workerDone(Worker w) {
525 mainLock.lock();
526 try {
527 completedTaskCount += w.completedTasks;
528 workers.remove(w);
529 if (--poolSize > 0)
530 return;
531
532 // Else, this is the last thread. Deal with potential shutdown.
533
534 int state = runState;
535 assert state != TERMINATED;
536
537 if (state != STOP) {
538 // If there are queued tasks but no threads, create
539 // replacement.
540 Runnable r = workQueue.poll();
541 if (r != null) {
542 addThread(r).start();
543 return;
544 }
545
546 // If there are some (presumably delayed) tasks but
547 // none pollable, create an idle replacement to wait.
548 if (!workQueue.isEmpty()) {
549 addThread(null).start();
550 return;
551 }
552
553 // Otherwise, we can exit without replacement
554 if (state == RUNNING)
555 return;
556 }
557
558 // Either state is STOP, or state is SHUTDOWN and there is
559 // no work to do. So we can terminate.
560 runState = TERMINATED;
561 termination.signalAll();
562 // fall through to call terminate() outside of lock.
563 } finally {
564 mainLock.unlock();
565 }
566
567 assert runState == TERMINATED;
568 terminated();
569 }
570
571 /**
572 * Worker threads
573 */
574 private class Worker implements Runnable {
575
576 /**
577 * The runLock is acquired and released surrounding each task
578 * execution. It mainly protects against interrupts that are
579 * intended to cancel the worker thread from instead
580 * interrupting the task being run.
581 */
582 private final ReentrantLock runLock = new ReentrantLock();
583
584 /**
585 * Initial task to run before entering run loop
586 */
587 private Runnable firstTask;
588
589 /**
590 * Per thread completed task counter; accumulated
591 * into completedTaskCount upon termination.
592 */
593 volatile long completedTasks;
594
595 /**
596 * Thread this worker is running in. Acts as a final field,
597 * but cannot be set until thread is created.
598 */
599 Thread thread;
600
601 Worker(Runnable firstTask) {
602 this.firstTask = firstTask;
603 }
604
605 boolean isActive() {
606 return runLock.isLocked();
607 }
608
609 /**
610 * Interrupt thread if not running a task
611 */
612 void interruptIfIdle() {
613 if (runLock.tryLock()) {
614 try {
615 thread.interrupt();
616 } finally {
617 runLock.unlock();
618 }
619 }
620 }
621
622 /**
623 * Cause thread to die even if running a task.
624 */
625 void interruptNow() {
626 thread.interrupt();
627 }
628
629 /**
630 * Run a single task between before/after methods.
631 */
632 private void runTask(Runnable task) {
633 runLock.lock();
634 try {
635 // Abort now if immediate cancel. Otherwise, we have
636 // committed to run this task.
637 if (runState == STOP)
638 return;
639
640 Thread.interrupted(); // clear interrupt status on entry
641 boolean ran = false;
642 beforeExecute(thread, task);
643 try {
644 task.run();
645 ran = true;
646 afterExecute(task, null);
647 ++completedTasks;
648 } catch(RuntimeException ex) {
649 if (!ran)
650 afterExecute(task, ex);
651 // Else the exception occurred within
652 // afterExecute itself in which case we don't
653 // want to call it again.
654 throw ex;
655 }
656 } finally {
657 runLock.unlock();
658 }
659 }
660
661 /**
662 * Main run loop
663 */
664 public void run() {
665 try {
666 for (;;) {
667 Runnable task;
668 if (firstTask != null) {
669 task = firstTask;
670 firstTask = null;
671 } else {
672 task = getTask();
673 if (task == null)
674 break;
675 }
676 runTask(task);
677 task = null; // unnecessary but can help GC
678 }
679 } catch(InterruptedException ie) {
680 // fall through
681 } finally {
682 workerDone(this);
683 }
684 }
685 }
686
687 // Public methods
688
689 /**
690 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
691 * initial parameters and default thread factory and handler. It
692 * may be more convenient to use one of the {@link Executors}
693 * factory methods instead of this general purpose constructor.
694 *
695 * @param corePoolSize the number of threads to keep in the
696 * pool, even if they are idle.
697 * @param maximumPoolSize the maximum number of threads to allow in the
698 * pool.
699 * @param keepAliveTime when the number of threads is greater than
700 * the core, this is the maximum time that excess idle threads
701 * will wait for new tasks before terminating.
702 * @param unit the time unit for the keepAliveTime
703 * argument.
704 * @param workQueue the queue to use for holding tasks before they
705 * are executed. This queue will hold only the <tt>Runnable</tt>
706 * tasks submitted by the <tt>execute</tt> method.
707 * @throws IllegalArgumentException if corePoolSize, or
708 * keepAliveTime less than zero, or if maximumPoolSize less than or
709 * equal to zero, or if corePoolSize greater than maximumPoolSize.
710 * @throws NullPointerException if <tt>workQueue</tt> is null
711 */
712 public ThreadPoolExecutor(int corePoolSize,
713 int maximumPoolSize,
714 long keepAliveTime,
715 TimeUnit unit,
716 BlockingQueue<Runnable> workQueue) {
717 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
718 Executors.defaultThreadFactory(), defaultHandler);
719 }
720
721 /**
722 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
723 * parameters.
724 *
725 * @param corePoolSize the number of threads to keep in the
726 * pool, even if they are idle.
727 * @param maximumPoolSize the maximum number of threads to allow in the
728 * pool.
729 * @param keepAliveTime when the number of threads is greater than
730 * the core, this is the maximum time that excess idle threads
731 * will wait for new tasks before terminating.
732 * @param unit the time unit for the keepAliveTime
733 * argument.
734 * @param workQueue the queue to use for holding tasks before they
735 * are executed. This queue will hold only the <tt>Runnable</tt>
736 * tasks submitted by the <tt>execute</tt> method.
737 * @param threadFactory the factory to use when the executor
738 * creates a new thread.
739 * @throws IllegalArgumentException if corePoolSize, or
740 * keepAliveTime less than zero, or if maximumPoolSize less than or
741 * equal to zero, or if corePoolSize greater than maximumPoolSize.
742 * @throws NullPointerException if <tt>workQueue</tt>
743 * or <tt>threadFactory</tt> are null.
744 */
745 public ThreadPoolExecutor(int corePoolSize,
746 int maximumPoolSize,
747 long keepAliveTime,
748 TimeUnit unit,
749 BlockingQueue<Runnable> workQueue,
750 ThreadFactory threadFactory) {
751
752 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
753 threadFactory, defaultHandler);
754 }
755
756 /**
757 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
758 * parameters.
759 *
760 * @param corePoolSize the number of threads to keep in the
761 * pool, even if they are idle.
762 * @param maximumPoolSize the maximum number of threads to allow in the
763 * pool.
764 * @param keepAliveTime when the number of threads is greater than
765 * the core, this is the maximum time that excess idle threads
766 * will wait for new tasks before terminating.
767 * @param unit the time unit for the keepAliveTime
768 * argument.
769 * @param workQueue the queue to use for holding tasks before they
770 * are executed. This queue will hold only the <tt>Runnable</tt>
771 * tasks submitted by the <tt>execute</tt> method.
772 * @param handler the handler to use when execution is blocked
773 * because the thread bounds and queue capacities are reached.
774 * @throws IllegalArgumentException if corePoolSize, or
775 * keepAliveTime less than zero, or if maximumPoolSize less than or
776 * equal to zero, or if corePoolSize greater than maximumPoolSize.
777 * @throws NullPointerException if <tt>workQueue</tt>
778 * or <tt>handler</tt> are null.
779 */
780 public ThreadPoolExecutor(int corePoolSize,
781 int maximumPoolSize,
782 long keepAliveTime,
783 TimeUnit unit,
784 BlockingQueue<Runnable> workQueue,
785 RejectedExecutionHandler handler) {
786 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
787 Executors.defaultThreadFactory(), handler);
788 }
789
790 /**
791 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
792 * parameters.
793 *
794 * @param corePoolSize the number of threads to keep in the
795 * pool, even if they are idle.
796 * @param maximumPoolSize the maximum number of threads to allow in the
797 * pool.
798 * @param keepAliveTime when the number of threads is greater than
799 * the core, this is the maximum time that excess idle threads
800 * will wait for new tasks before terminating.
801 * @param unit the time unit for the keepAliveTime
802 * argument.
803 * @param workQueue the queue to use for holding tasks before they
804 * are executed. This queue will hold only the <tt>Runnable</tt>
805 * tasks submitted by the <tt>execute</tt> method.
806 * @param threadFactory the factory to use when the executor
807 * creates a new thread.
808 * @param handler the handler to use when execution is blocked
809 * because the thread bounds and queue capacities are reached.
810 * @throws IllegalArgumentException if corePoolSize, or
811 * keepAliveTime less than zero, or if maximumPoolSize less than or
812 * equal to zero, or if corePoolSize greater than maximumPoolSize.
813 * @throws NullPointerException if <tt>workQueue</tt>
814 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
815 */
816 public ThreadPoolExecutor(int corePoolSize,
817 int maximumPoolSize,
818 long keepAliveTime,
819 TimeUnit unit,
820 BlockingQueue<Runnable> workQueue,
821 ThreadFactory threadFactory,
822 RejectedExecutionHandler handler) {
823 if (corePoolSize < 0 ||
824 maximumPoolSize <= 0 ||
825 maximumPoolSize < corePoolSize ||
826 keepAliveTime < 0)
827 throw new IllegalArgumentException();
828 if (workQueue == null || threadFactory == null || handler == null)
829 throw new NullPointerException();
830 this.corePoolSize = corePoolSize;
831 this.maximumPoolSize = maximumPoolSize;
832 this.workQueue = workQueue;
833 this.keepAliveTime = unit.toNanos(keepAliveTime);
834 this.threadFactory = threadFactory;
835 this.handler = handler;
836 }
837
838
839 /**
840 * Executes the given task sometime in the future. The task
841 * may execute in a new thread or in an existing pooled thread.
842 *
843 * If the task cannot be submitted for execution, either because this
844 * executor has been shutdown or because its capacity has been reached,
845 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
846 *
847 * @param command the task to execute
848 * @throws RejectedExecutionException at discretion of
849 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
850 * for execution
851 * @throws NullPointerException if command is null
852 */
853 public void execute(Runnable command) {
854 if (command == null)
855 throw new NullPointerException();
856 for (;;) {
857 if (runState != RUNNING) {
858 reject(command);
859 return;
860 }
861 if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
862 return;
863 if (workQueue.offer(command))
864 return;
865 Runnable r = addIfUnderMaximumPoolSize(command);
866 if (r == command)
867 return;
868 if (r == null) {
869 reject(command);
870 return;
871 }
872 // else retry
873 }
874 }
875
876 public void shutdown() {
877 // Fail if caller doesn't have modifyThread permission
878 SecurityManager security = System.getSecurityManager();
879 if (security != null)
880 java.security.AccessController.checkPermission(shutdownPerm);
881
882 boolean fullyTerminated = false;
883 mainLock.lock();
884 try {
885 if (workers.size() > 0) {
886 // Check if caller can modify worker threads.
887 // This might not be true even if passed above check,
888 // if the securityManager treats some threads specially.
889 if (security != null) {
890 for (Worker w: workers)
891 security.checkAccess(w.thread);
892 }
893
894 int state = runState;
895 if (state == RUNNING) // don't override shutdownNow
896 runState = SHUTDOWN;
897
898 try {
899 for (Worker w: workers)
900 w.interruptIfIdle();
901 } catch(SecurityException se) {
902 // If SecurityManager allows above checks, but then
903 // unexpectedly throws exception when interrupting
904 // threads (which it ought not do), back out as
905 // cleanly as we can. -Some threads may have been
906 // killed but we remain in non-shutdown state.
907 runState = state;
908 throw se;
909 }
910 }
911 else { // If no workers, trigger full termination now
912 fullyTerminated = true;
913 runState = TERMINATED;
914 termination.signalAll();
915 }
916 } finally {
917 mainLock.unlock();
918 }
919 if (fullyTerminated)
920 terminated();
921 }
922
923
924 public List<Runnable> shutdownNow() {
925 // Almost the same code as shutdown()
926 SecurityManager security = System.getSecurityManager();
927 if (security != null)
928 java.security.AccessController.checkPermission(shutdownPerm);
929
930 boolean fullyTerminated = false;
931 mainLock.lock();
932 try {
933 if (workers.size() > 0) {
934 if (security != null) {
935 for (Worker w: workers)
936 security.checkAccess(w.thread);
937 }
938
939 int state = runState;
940 if (state != TERMINATED)
941 runState = STOP;
942 try {
943 for (Worker w : workers)
944 w.interruptNow();
945 } catch(SecurityException se) {
946 runState = state; // back out;
947 throw se;
948 }
949 }
950 else { // If no workers, trigger full termination now
951 fullyTerminated = true;
952 runState = TERMINATED;
953 termination.signalAll();
954 }
955 } finally {
956 mainLock.unlock();
957 }
958 if (fullyTerminated)
959 terminated();
960
961 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
962 }
963
964 public boolean isShutdown() {
965 return runState != RUNNING;
966 }
967
968 /**
969 * Return true if this executor is in the process of terminating
970 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
971 * completely terminated. This method may be useful for
972 * debugging. A return of <tt>true</tt> reported a sufficient
973 * period after shutdown may indicate that submitted tasks have
974 * ignored or suppressed interruption, causing this executor not
975 * to properly terminate.
976 * @return true if terminating but not yet terminated.
977 */
978 public boolean isTerminating() {
979 return runState == STOP;
980 }
981
982 public boolean isTerminated() {
983 return runState == TERMINATED;
984 }
985
986 public boolean awaitTermination(long timeout, TimeUnit unit)
987 throws InterruptedException {
988 mainLock.lock();
989 try {
990 long nanos = unit.toNanos(timeout);
991 for (;;) {
992 if (runState == TERMINATED)
993 return true;
994 if (nanos <= 0)
995 return false;
996 nanos = termination.awaitNanos(nanos);
997 }
998 } finally {
999 mainLock.unlock();
1000 }
1001 }
1002
1003 /**
1004 * Invokes <tt>shutdown</tt> when this executor is no longer
1005 * referenced.
1006 */
1007 protected void finalize() {
1008 shutdown();
1009 }
1010
1011 /**
1012 * Sets the thread factory used to create new threads.
1013 *
1014 * @param threadFactory the new thread factory
1015 * @throws NullPointerException if threadFactory is null
1016 * @see #getThreadFactory
1017 */
1018 public void setThreadFactory(ThreadFactory threadFactory) {
1019 if (threadFactory == null)
1020 throw new NullPointerException();
1021 this.threadFactory = threadFactory;
1022 }
1023
1024 /**
1025 * Returns the thread factory used to create new threads.
1026 *
1027 * @return the current thread factory
1028 * @see #setThreadFactory
1029 */
1030 public ThreadFactory getThreadFactory() {
1031 return threadFactory;
1032 }
1033
1034 /**
1035 * Sets a new handler for unexecutable tasks.
1036 *
1037 * @param handler the new handler
1038 * @throws NullPointerException if handler is null
1039 * @see #getRejectedExecutionHandler
1040 */
1041 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1042 if (handler == null)
1043 throw new NullPointerException();
1044 this.handler = handler;
1045 }
1046
1047 /**
1048 * Returns the current handler for unexecutable tasks.
1049 *
1050 * @return the current handler
1051 * @see #setRejectedExecutionHandler
1052 */
1053 public RejectedExecutionHandler getRejectedExecutionHandler() {
1054 return handler;
1055 }
1056
1057 /**
1058 * Returns the task queue used by this executor. Access to the
1059 * task queue is intended primarily for debugging and monitoring.
1060 * This queue may be in active use. Retrieving the task queue
1061 * does not prevent queued tasks from executing.
1062 *
1063 * @return the task queue
1064 */
1065 public BlockingQueue<Runnable> getQueue() {
1066 return workQueue;
1067 }
1068
1069 /**
1070 * Removes this task from the executor's internal queue if it is
1071 * present, thus causing it not to be run if it has not already
1072 * started.
1073 *
1074 * <p> This method may be useful as one part of a cancellation
1075 * scheme. It may fail to remove tasks that have been converted
1076 * into other forms before being placed on the internal queue. For
1077 * example, a task entered using <tt>submit</tt> might be
1078 * converted into a form that maintains <tt>Future</tt> status.
1079 * However, in such cases, method {@link ThreadPoolExecutor#purge}
1080 * may be used to remove those Futures that have been cancelled.
1081 *
1082 *
1083 * @param task the task to remove
1084 * @return true if the task was removed
1085 */
1086 public boolean remove(Runnable task) {
1087 return getQueue().remove(task);
1088 }
1089
1090
1091 /**
1092 * Tries to remove from the work queue all {@link Future}
1093 * tasks that have been cancelled. This method can be useful as a
1094 * storage reclamation operation, that has no other impact on
1095 * functionality. Cancelled tasks are never executed, but may
1096 * accumulate in work queues until worker threads can actively
1097 * remove them. Invoking this method instead tries to remove them now.
1098 * However, this method may fail to remove tasks in
1099 * the presence of interference by other threads.
1100 */
1101
1102 public void purge() {
1103 // Fail if we encounter interference during traversal
1104 try {
1105 Iterator<Runnable> it = getQueue().iterator();
1106 while (it.hasNext()) {
1107 Runnable r = it.next();
1108 if (r instanceof Future<?>) {
1109 Future<?> c = (Future<?>)r;
1110 if (c.isCancelled())
1111 it.remove();
1112 }
1113 }
1114 }
1115 catch(ConcurrentModificationException ex) {
1116 return;
1117 }
1118 }
1119
1120 /**
1121 * Sets the core number of threads. This overrides any value set
1122 * in the constructor. If the new value is smaller than the
1123 * current value, excess existing threads will be terminated when
1124 * they next become idle. If larger, new threads will, if needed,
1125 * be started to execute any queued tasks.
1126 *
1127 * @param corePoolSize the new core size
1128 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1129 * less than zero
1130 * @see #getCorePoolSize
1131 */
1132 public void setCorePoolSize(int corePoolSize) {
1133 if (corePoolSize < 0)
1134 throw new IllegalArgumentException();
1135 mainLock.lock();
1136 try {
1137 int extra = this.corePoolSize - corePoolSize;
1138 this.corePoolSize = corePoolSize;
1139 if (extra < 0) {
1140 Runnable r;
1141 while (extra++ < 0 && poolSize < corePoolSize &&
1142 (r = workQueue.poll()) != null)
1143 addThread(r).start();
1144 }
1145 else if (extra > 0 && poolSize > corePoolSize) {
1146 Iterator<Worker> it = workers.iterator();
1147 while (it.hasNext() &&
1148 extra-- > 0 &&
1149 poolSize > corePoolSize &&
1150 workQueue.remainingCapacity() == 0)
1151 it.next().interruptIfIdle();
1152 }
1153 } finally {
1154 mainLock.unlock();
1155 }
1156 }
1157
1158 /**
1159 * Returns the core number of threads.
1160 *
1161 * @return the core number of threads
1162 * @see #setCorePoolSize
1163 */
1164 public int getCorePoolSize() {
1165 return corePoolSize;
1166 }
1167
1168 /**
1169 * Start a core thread, causing it to idly wait for work. This
1170 * overrides the default policy of starting core threads only when
1171 * new tasks are executed. This method will return <tt>false</tt>
1172 * if all core threads have already been started.
1173 * @return true if a thread was started
1174 */
1175 public boolean prestartCoreThread() {
1176 return addIfUnderCorePoolSize(null);
1177 }
1178
1179 /**
1180 * Start all core threads, causing them to idly wait for work. This
1181 * overrides the default policy of starting core threads only when
1182 * new tasks are executed.
1183 * @return the number of threads started.
1184 */
1185 public int prestartAllCoreThreads() {
1186 int n = 0;
1187 while (addIfUnderCorePoolSize(null))
1188 ++n;
1189 return n;
1190 }
1191
1192 /**
1193 * Sets the maximum allowed number of threads. This overrides any
1194 * value set in the constructor. If the new value is smaller than
1195 * the current value, excess existing threads will be
1196 * terminated when they next become idle.
1197 *
1198 * @param maximumPoolSize the new maximum
1199 * @throws IllegalArgumentException if maximumPoolSize less than zero or
1200 * the {@link #getCorePoolSize core pool size}
1201 * @see #getMaximumPoolSize
1202 */
1203 public void setMaximumPoolSize(int maximumPoolSize) {
1204 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1205 throw new IllegalArgumentException();
1206 mainLock.lock();
1207 try {
1208 int extra = this.maximumPoolSize - maximumPoolSize;
1209 this.maximumPoolSize = maximumPoolSize;
1210 if (extra > 0 && poolSize > maximumPoolSize) {
1211 Iterator<Worker> it = workers.iterator();
1212 while (it.hasNext() &&
1213 extra > 0 &&
1214 poolSize > maximumPoolSize) {
1215 it.next().interruptIfIdle();
1216 --extra;
1217 }
1218 }
1219 } finally {
1220 mainLock.unlock();
1221 }
1222 }
1223
1224 /**
1225 * Returns the maximum allowed number of threads.
1226 *
1227 * @return the maximum allowed number of threads
1228 * @see #setMaximumPoolSize
1229 */
1230 public int getMaximumPoolSize() {
1231 return maximumPoolSize;
1232 }
1233
1234 /**
1235 * Sets the time limit for which threads may remain idle before
1236 * being terminated. If there are more than the core number of
1237 * threads currently in the pool, after waiting this amount of
1238 * time without processing a task, excess threads will be
1239 * terminated. This overrides any value set in the constructor.
1240 * @param time the time to wait. A time value of zero will cause
1241 * excess threads to terminate immediately after executing tasks.
1242 * @param unit the time unit of the time argument
1243 * @throws IllegalArgumentException if time less than zero
1244 * @see #getKeepAliveTime
1245 */
1246 public void setKeepAliveTime(long time, TimeUnit unit) {
1247 if (time < 0)
1248 throw new IllegalArgumentException();
1249 this.keepAliveTime = unit.toNanos(time);
1250 }
1251
1252 /**
1253 * Returns the thread keep-alive time, which is the amount of time
1254 * which threads in excess of the core pool size may remain
1255 * idle before being terminated.
1256 *
1257 * @param unit the desired time unit of the result
1258 * @return the time limit
1259 * @see #setKeepAliveTime
1260 */
1261 public long getKeepAliveTime(TimeUnit unit) {
1262 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1263 }
1264
1265 /* Statistics */
1266
1267 /**
1268 * Returns the current number of threads in the pool.
1269 *
1270 * @return the number of threads
1271 */
1272 public int getPoolSize() {
1273 return poolSize;
1274 }
1275
1276 /**
1277 * Returns the approximate number of threads that are actively
1278 * executing tasks.
1279 *
1280 * @return the number of threads
1281 */
1282 public int getActiveCount() {
1283 mainLock.lock();
1284 try {
1285 int n = 0;
1286 for (Worker w : workers) {
1287 if (w.isActive())
1288 ++n;
1289 }
1290 return n;
1291 } finally {
1292 mainLock.unlock();
1293 }
1294 }
1295
1296 /**
1297 * Returns the largest number of threads that have ever
1298 * simultaneously been in the pool.
1299 *
1300 * @return the number of threads
1301 */
1302 public int getLargestPoolSize() {
1303 mainLock.lock();
1304 try {
1305 return largestPoolSize;
1306 } finally {
1307 mainLock.unlock();
1308 }
1309 }
1310
1311 /**
1312 * Returns the approximate total number of tasks that have been
1313 * scheduled for execution. Because the states of tasks and
1314 * threads may change dynamically during computation, the returned
1315 * value is only an approximation, but one that does not ever
1316 * decrease across successive calls.
1317 *
1318 * @return the number of tasks
1319 */
1320 public long getTaskCount() {
1321 mainLock.lock();
1322 try {
1323 long n = completedTaskCount;
1324 for (Worker w : workers) {
1325 n += w.completedTasks;
1326 if (w.isActive())
1327 ++n;
1328 }
1329 return n + workQueue.size();
1330 } finally {
1331 mainLock.unlock();
1332 }
1333 }
1334
1335 /**
1336 * Returns the approximate total number of tasks that have
1337 * completed execution. Because the states of tasks and threads
1338 * may change dynamically during computation, the returned value
1339 * is only an approximation, but one that does not ever decrease
1340 * across successive calls.
1341 *
1342 * @return the number of tasks
1343 */
1344 public long getCompletedTaskCount() {
1345 mainLock.lock();
1346 try {
1347 long n = completedTaskCount;
1348 for (Worker w : workers)
1349 n += w.completedTasks;
1350 return n;
1351 } finally {
1352 mainLock.unlock();
1353 }
1354 }
1355
1356 /**
1357 * Method invoked prior to executing the given Runnable in the
1358 * given thread. This method is invoked by thread <tt>t</tt> that
1359 * will execute task <tt>r</tt>, and may be used to re-initialize
1360 * ThreadLocals, or to perform logging. Note: To properly nest
1361 * multiple overridings, subclasses should generally invoke
1362 * <tt>super.beforeExecute</tt> at the end of this method.
1363 *
1364 * @param t the thread that will run task r.
1365 * @param r the task that will be executed.
1366 */
1367 protected void beforeExecute(Thread t, Runnable r) { }
1368
1369 /**
1370 * Method invoked upon completion of execution of the given
1371 * Runnable. This method is invoked by the thread that executed
1372 * the task. If non-null, the Throwable is the uncaught exception
1373 * that caused execution to terminate abruptly. Note: To properly
1374 * nest multiple overridings, subclasses should generally invoke
1375 * <tt>super.afterExecute</tt> at the beginning of this method.
1376 *
1377 * @param r the runnable that has completed.
1378 * @param t the exception that caused termination, or null if
1379 * execution completed normally.
1380 */
1381 protected void afterExecute(Runnable r, Throwable t) { }
1382
1383 /**
1384 * Method invoked when the Executor has terminated. Default
1385 * implementation does nothing. Note: To properly nest multiple
1386 * overridings, subclasses should generally invoke
1387 * <tt>super.terminated</tt> within this method.
1388 */
1389 protected void terminated() { }
1390
1391 /**
1392 * A handler for rejected tasks that runs the rejected task
1393 * directly in the calling thread of the <tt>execute</tt> method,
1394 * unless the executor has been shut down, in which case the task
1395 * is discarded.
1396 */
1397 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1398
1399 /**
1400 * Creates a <tt>CallerRunsPolicy</tt>.
1401 */
1402 public CallerRunsPolicy() { }
1403
1404 /**
1405 * Executes task r in the caller's thread, unless the executor
1406 * has been shut down, in which case the task is discarded.
1407 * @param r the runnable task requested to be executed
1408 * @param e the executor attempting to execute this task
1409 */
1410 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1411 if (!e.isShutdown()) {
1412 r.run();
1413 }
1414 }
1415 }
1416
1417 /**
1418 * A handler for rejected tasks that throws a
1419 * <tt>RejectedExecutionException</tt>.
1420 */
1421 public static class AbortPolicy implements RejectedExecutionHandler {
1422
1423 /**
1424 * Creates an <tt>AbortPolicy</tt>.
1425 */
1426 public AbortPolicy() { }
1427
1428 /**
1429 * Always throws RejectedExecutionException
1430 * @param r the runnable task requested to be executed
1431 * @param e the executor attempting to execute this task
1432 * @throws RejectedExecutionException always.
1433 */
1434 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1435 throw new RejectedExecutionException();
1436 }
1437 }
1438
1439 /**
1440 * A handler for rejected tasks that silently discards the
1441 * rejected task.
1442 */
1443 public static class DiscardPolicy implements RejectedExecutionHandler {
1444
1445 /**
1446 * Creates <tt>DiscardPolicy</tt>.
1447 */
1448 public DiscardPolicy() { }
1449
1450 /**
1451 * Does nothing, which has the effect of discarding task r.
1452 * @param r the runnable task requested to be executed
1453 * @param e the executor attempting to execute this task
1454 */
1455 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1456 }
1457 }
1458
1459 /**
1460 * A handler for rejected tasks that discards the oldest unhandled
1461 * request and then retries <tt>execute</tt>, unless the executor
1462 * is shut down, in which case the task is discarded.
1463 */
1464 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1465 /**
1466 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1467 */
1468 public DiscardOldestPolicy() { }
1469
1470 /**
1471 * Obtains and ignores the next task that the executor
1472 * would otherwise execute, if one is immediately available,
1473 * and then retries execution of task r, unless the executor
1474 * is shut down, in which case task r is instead discarded.
1475 * @param r the runnable task requested to be executed
1476 * @param e the executor attempting to execute this task
1477 */
1478 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1479 if (!e.isShutdown()) {
1480 e.getQueue().poll();
1481 e.execute(r);
1482 }
1483 }
1484 }
1485 }