ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.32
Committed: Sat Oct 11 15:37:31 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.31: +1 -1 lines
Log Message:
Redeclare some Conditions as ReentrantLock.ConditionObjects

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