ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.106
Committed: Mon Jul 17 12:54:33 2006 UTC (17 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.105: +13 -7 lines
Log Message:
Revert Worker.run loop form; update documentation

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
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</dt>
64 *
65 * <dd> By default, even core threads are initially created and
66 * started only when new tasks arrive, but this can be overridden
67 * dynamically using method {@link
68 * ThreadPoolExecutor#prestartCoreThread} or
69 * {@link ThreadPoolExecutor#prestartAllCoreThreads}.
70 * You probably want to prestart threads if you construct the
71 * pool with a non-empty queue. </dd>
72 *
73 * <dt>Creating new threads</dt>
74 *
75 * <dd>New threads are created using a {@link
76 * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
77 * {@link Executors#defaultThreadFactory} is used, that creates threads to all
78 * be in the same {@link ThreadGroup} and with the same
79 * <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying
80 * a different ThreadFactory, you can alter the thread's name, thread
81 * group, priority, daemon status, etc. If a <tt>ThreadFactory</tt> fails to create
82 * a thread when asked by returning null from <tt>newThread</tt>,
83 * the executor will continue, but might
84 * not be able to execute any tasks. </dd>
85 *
86 * <dt>Keep-alive times</dt>
87 *
88 * <dd>If the pool currently has more than corePoolSize threads,
89 * excess threads will be terminated if they have been idle for more
90 * than the keepAliveTime (see {@link
91 * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
92 * reducing resource consumption when the pool is not being actively
93 * used. If the pool becomes more active later, new threads will be
94 * constructed. This parameter can also be changed dynamically using
95 * method {@link ThreadPoolExecutor#setKeepAliveTime}. Using a value
96 * of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS} effectively
97 * disables idle threads from ever terminating prior to shut down. By
98 * default, the keep-alive policy applies only when there are more
99 * than corePoolSizeThreads. But method {@link
100 * ThreadPoolExecutor#allowCoreThreadTimeOut} can be used to apply
101 * this time-out policy to core threads as well, so long as
102 * the keepAliveTime value is non-zero. </dd>
103 *
104 * <dt>Queuing</dt>
105 *
106 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
107 * submitted tasks. The use of this queue interacts with pool sizing:
108 *
109 * <ul>
110 *
111 * <li> If fewer than corePoolSize threads are running, the Executor
112 * always prefers adding a new thread
113 * rather than queuing.</li>
114 *
115 * <li> If corePoolSize or more threads are running, the Executor
116 * always prefers queuing a request rather than adding a new
117 * thread.</li>
118 *
119 * <li> If a request cannot be queued, a new thread is created unless
120 * this would exceed maximumPoolSize, in which case, the task will be
121 * rejected.</li>
122 *
123 * </ul>
124 *
125 * There are three general strategies for queuing:
126 * <ol>
127 *
128 * <li> <em> Direct handoffs.</em> A good default choice for a work
129 * queue is a {@link SynchronousQueue} that hands off tasks to threads
130 * without otherwise holding them. Here, an attempt to queue a task
131 * will fail if no threads are immediately available to run it, so a
132 * new thread will be constructed. This policy avoids lockups when
133 * handling sets of requests that might have internal dependencies.
134 * Direct handoffs generally require unbounded maximumPoolSizes to
135 * avoid rejection of new submitted tasks. This in turn admits the
136 * possibility of unbounded thread growth when commands continue to
137 * arrive on average faster than they can be processed. </li>
138 *
139 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
140 * example a {@link LinkedBlockingQueue} without a predefined
141 * capacity) will cause new tasks to wait in the queue when all
142 * corePoolSize threads are busy. Thus, no more than corePoolSize
143 * threads will ever be created. (And the value of the maximumPoolSize
144 * therefore doesn't have any effect.) This may be appropriate when
145 * each task is completely independent of others, so tasks cannot
146 * affect each others execution; for example, in a web page server.
147 * While this style of queuing can be useful in smoothing out
148 * transient bursts of requests, it admits the possibility of
149 * unbounded work queue growth when commands continue to arrive on
150 * average faster than they can be processed. </li>
151 *
152 * <li><em>Bounded queues.</em> A bounded queue (for example, an
153 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
154 * used with finite maximumPoolSizes, but can be more difficult to
155 * tune and control. Queue sizes and maximum pool sizes may be traded
156 * off for each other: Using large queues and small pools minimizes
157 * CPU usage, OS resources, and context-switching overhead, but can
158 * lead to artificially low throughput. If tasks frequently block (for
159 * example if they are I/O bound), a system may be able to schedule
160 * time for more threads than you otherwise allow. Use of small queues
161 * generally requires larger pool sizes, which keeps CPUs busier but
162 * may encounter unacceptable scheduling overhead, which also
163 * decreases throughput. </li>
164 *
165 * </ol>
166 *
167 * </dd>
168 *
169 * <dt>Rejected tasks</dt>
170 *
171 * <dd> New tasks submitted in method {@link
172 * ThreadPoolExecutor#execute} will be <em>rejected</em> when the
173 * Executor has been shut down, and also when the Executor uses finite
174 * bounds for both maximum threads and work queue capacity, and is
175 * saturated. In either case, the <tt>execute</tt> method invokes the
176 * {@link RejectedExecutionHandler#rejectedExecution} method of its
177 * {@link RejectedExecutionHandler}. Four predefined handler policies
178 * are provided:
179 *
180 * <ol>
181 *
182 * <li> In the
183 * default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a
184 * runtime {@link RejectedExecutionException} upon rejection. </li>
185 *
186 * <li> In {@link
187 * ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes
188 * <tt>execute</tt> itself runs the task. This provides a simple
189 * feedback control mechanism that will slow down the rate that new
190 * tasks are submitted. </li>
191 *
192 * <li> In {@link ThreadPoolExecutor.DiscardPolicy},
193 * a task that cannot be executed is simply dropped. </li>
194 *
195 * <li>In {@link
196 * ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not
197 * shut down, the task at the head of the work queue is dropped, and
198 * then execution is retried (which can fail again, causing this to be
199 * repeated.) </li>
200 *
201 * </ol>
202 *
203 * It is possible to define and use other kinds of {@link
204 * RejectedExecutionHandler} classes. Doing so requires some care
205 * especially when policies are designed to work only under particular
206 * capacity or queuing policies. </dd>
207 *
208 * <dt>Hook methods</dt>
209 *
210 * <dd>This class provides <tt>protected</tt> overridable {@link
211 * ThreadPoolExecutor#beforeExecute} and {@link
212 * ThreadPoolExecutor#afterExecute} methods that are called before and
213 * after execution of each task. These can be used to manipulate the
214 * execution environment; for example, reinitializing ThreadLocals,
215 * gathering statistics, or adding log entries. Additionally, method
216 * {@link ThreadPoolExecutor#terminated} can be overridden to perform
217 * any special processing that needs to be done once the Executor has
218 * fully terminated.
219 *
220 * <p>If hook or callback methods throw
221 * exceptions, internal worker threads may in turn fail and
222 * abruptly terminate.</dd>
223 *
224 * <dt>Queue maintenance</dt>
225 *
226 * <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to
227 * the work queue for purposes of monitoring and debugging. Use of
228 * this method for any other purpose is strongly discouraged. Two
229 * supplied methods, {@link ThreadPoolExecutor#remove} and {@link
230 * ThreadPoolExecutor#purge} are available to assist in storage
231 * reclamation when large numbers of queued tasks become
232 * cancelled.</dd>
233 *
234 * <dt>Finalization</dt>
235 *
236 * <dd> A pool that is no longer referenced in a program <em>AND</em>
237 * has no remaining threads will be <tt>shutdown</tt>
238 * automatically. If you would like to ensure that unreferenced pools
239 * are reclaimed even if users forget to call {@link
240 * ThreadPoolExecutor#shutdown}, then you must arrange that unused
241 * threads eventually die, by setting appropriate keep-alive times,
242 * using a lower bound of zero core threads and/or setting {@link
243 * ThreadPoolExecutor#allowCoreThreadTimeOut}. </dd> </dl>
244 *
245 * <p> <b>Extension example</b>. Most extensions of this class
246 * override one or more of the protected hook methods. For example,
247 * here is a subclass that adds a simple pause/resume feature:
248 *
249 * <pre>
250 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
251 * private boolean isPaused;
252 * private ReentrantLock pauseLock = new ReentrantLock();
253 * private Condition unpaused = pauseLock.newCondition();
254 *
255 * public PausableThreadPoolExecutor(...) { super(...); }
256 *
257 * protected void beforeExecute(Thread t, Runnable r) {
258 * super.beforeExecute(t, r);
259 * pauseLock.lock();
260 * try {
261 * while (isPaused) unpaused.await();
262 * } catch (InterruptedException ie) {
263 * t.interrupt();
264 * } finally {
265 * pauseLock.unlock();
266 * }
267 * }
268 *
269 * public void pause() {
270 * pauseLock.lock();
271 * try {
272 * isPaused = true;
273 * } finally {
274 * pauseLock.unlock();
275 * }
276 * }
277 *
278 * public void resume() {
279 * pauseLock.lock();
280 * try {
281 * isPaused = false;
282 * unpaused.signalAll();
283 * } finally {
284 * pauseLock.unlock();
285 * }
286 * }
287 * }
288 * </pre>
289 * @since 1.5
290 * @author Doug Lea
291 */
292 public class ThreadPoolExecutor extends AbstractExecutorService {
293
294 /**
295 * Permission for checking shutdown
296 */
297 private static final RuntimePermission shutdownPerm =
298 new RuntimePermission("modifyThread");
299
300 /*
301 * A ThreadPoolExecutor manages a largish set of control fields.
302 * State changes in fields that affect execution control
303 * guarantees only occur within mainLock regions. These include
304 * fields runState, poolSize, corePoolSize, and maximumPoolSize
305 * However, these fields are also declared volatile, so can be
306 * read outside of locked regions. (Also, the workers Set is
307 * accessed only under lock).
308 *
309 * The other fields representing user control parameters do not
310 * affect execution invariants, so are declared volatile and
311 * allowed to change (via user methods) asynchronously with
312 * execution. These fields: allowCoreThreadTimeOut, keepAliveTime,
313 * the rejected execution handler, and threadFactory, are not
314 * updated within locks.
315 *
316 * The extensive use of volatiles here enables the most
317 * performance-critical actions, such as enqueuing and dequeuing
318 * tasks in the workQueue, to normally proceed without holding the
319 * mainLock when they see that the state allows actions, although,
320 * as described below, sometimes at the expense of re-checks
321 * following these actions.
322 */
323
324 /**
325 * runState provides the main lifecyle control, taking on values:
326 *
327 * RUNNING: Accept new tasks and process queued tasks
328 * SHUTDOWN: Don't accept new tasks, but process queued tasks
329 * STOP: Don't accept new tasks, don't process queued tasks,
330 * and interrupt in-progress tasks
331 * TERMINATED: Same as STOP, plus all threads have terminated
332 *
333 * The numerical order among these values matters, to allow
334 * ordered comparisons. The runState monotonically increases over
335 * time, but need not hit each state. The transitions are:
336 *
337 * RUNNING -> SHUTDOWN
338 * On invocation of shutdown(), perhaps implicitly in finalize()
339 * (RUNNING or SHUTDOWN) -> STOP
340 * On invocation of shutdownNow()
341 * SHUTDOWN -> TERMINATED
342 * When both queue and pool are empty
343 * STOP -> TERMINATED
344 * When pool is empty
345 */
346 volatile int runState;
347 static final int RUNNING = 0;
348 static final int SHUTDOWN = 1;
349 static final int STOP = 2;
350 static final int TERMINATED = 3;
351
352 /**
353 * The queue used for holding tasks and handing off to worker
354 * threads. Note that when using this queue, we do not require
355 * that workQueue.poll() returning null necessarily means that
356 * workQueue.isEmpty(), so must sometimes check both. This
357 * accommodates special-purpose queues such as DelayQueues for
358 * which poll() is allowed to return null even if it may later
359 * return non-null when delays expire.
360 */
361 private final BlockingQueue<Runnable> workQueue;
362
363 /**
364 * Lock held on updates to poolSize, corePoolSize,
365 * maximumPoolSize, runState, and workers set.
366 */
367 private final ReentrantLock mainLock = new ReentrantLock();
368
369 /**
370 * Wait condition to support awaitTermination
371 */
372 private final Condition termination = mainLock.newCondition();
373
374 /**
375 * Set containing all worker threads in pool. Accessed only when
376 * holding mainLock.
377 */
378 private final HashSet<Worker> workers = new HashSet<Worker>();
379
380 /**
381 * Timeout in nanoseconds for idle threads waiting for work.
382 * Threads use this timeout when there are more than corePoolSize
383 * present or if allowCoreThreadTimeOut. Otherwise they wait
384 * forever for new work.
385 */
386 private volatile long keepAliveTime;
387
388 /**
389 * If false (default), core threads stay alive even when idle.
390 * If true, core threads use keepAliveTime to time out waiting
391 * for work.
392 */
393 private volatile boolean allowCoreThreadTimeOut;
394
395 /**
396 * Core pool size, updated only while holding mainLock, but
397 * volatile to allow concurrent readability even during updates.
398 */
399 private volatile int corePoolSize;
400
401 /**
402 * Maximum pool size, updated only while holding mainLock but
403 * volatile to allow concurrent readability even during updates.
404 */
405 private volatile int maximumPoolSize;
406
407 /**
408 * Current pool size, updated only while holding mainLock but
409 * volatile to allow concurrent readability even during updates.
410 */
411 private volatile int poolSize;
412
413 /**
414 * Handler called when saturated or shutdown in execute.
415 */
416 private volatile RejectedExecutionHandler handler;
417
418 /**
419 * Factory for new threads. All threads are created using this
420 * factory (via method addThread). All callers must be prepared
421 * for addThread to fail by returning null, which may reflect a
422 * system or user's policy limiting the number of threads. Even
423 * though it is not treated as an error, failure to create threads
424 * may result in new tasks being rejected or existing ones
425 * remaining stuck in the queue. On the other hand, no special
426 * precautions exist to handle OutOfMemoryErrors that might be
427 * thrown while trying to create threads, since there is generally
428 * no recourse from within this class.
429 */
430 private volatile ThreadFactory threadFactory;
431
432 /**
433 * Tracks largest attained pool size.
434 */
435 private int largestPoolSize;
436
437 /**
438 * Counter for completed tasks. Updated only on termination of
439 * worker threads.
440 */
441 private long completedTaskCount;
442
443 /**
444 * The default rejected execution handler
445 */
446 private static final RejectedExecutionHandler defaultHandler =
447 new AbortPolicy();
448
449 // Constructors
450
451 /**
452 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
453 * parameters and default thread factory and rejected execution handler.
454 * It may be more convenient to use one of the {@link Executors} factory
455 * methods instead of this general purpose constructor.
456 *
457 * @param corePoolSize the number of threads to keep in the
458 * pool, even if they are idle.
459 * @param maximumPoolSize the maximum number of threads to allow in the
460 * pool.
461 * @param keepAliveTime when the number of threads is greater than
462 * the core, this is the maximum time that excess idle threads
463 * will wait for new tasks before terminating.
464 * @param unit the time unit for the keepAliveTime
465 * argument.
466 * @param workQueue the queue to use for holding tasks before they
467 * are executed. This queue will hold only the <tt>Runnable</tt>
468 * tasks submitted by the <tt>execute</tt> method.
469 * @throws IllegalArgumentException if corePoolSize or
470 * keepAliveTime less than zero, or if maximumPoolSize less than or
471 * equal to zero, or if corePoolSize greater than maximumPoolSize.
472 * @throws NullPointerException if <tt>workQueue</tt> is null
473 */
474 public ThreadPoolExecutor(int corePoolSize,
475 int maximumPoolSize,
476 long keepAliveTime,
477 TimeUnit unit,
478 BlockingQueue<Runnable> workQueue) {
479 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
480 Executors.defaultThreadFactory(), defaultHandler);
481 }
482
483 /**
484 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
485 * parameters and default rejected execution handler.
486 *
487 * @param corePoolSize the number of threads to keep in the
488 * pool, even if they are idle.
489 * @param maximumPoolSize the maximum number of threads to allow in the
490 * pool.
491 * @param keepAliveTime when the number of threads is greater than
492 * the core, this is the maximum time that excess idle threads
493 * will wait for new tasks before terminating.
494 * @param unit the time unit for the keepAliveTime
495 * argument.
496 * @param workQueue the queue to use for holding tasks before they
497 * are executed. This queue will hold only the <tt>Runnable</tt>
498 * tasks submitted by the <tt>execute</tt> method.
499 * @param threadFactory the factory to use when the executor
500 * creates a new thread.
501 * @throws IllegalArgumentException if corePoolSize or
502 * keepAliveTime less than zero, or if maximumPoolSize less than or
503 * equal to zero, or if corePoolSize greater than maximumPoolSize.
504 * @throws NullPointerException if <tt>workQueue</tt>
505 * or <tt>threadFactory</tt> are null.
506 */
507 public ThreadPoolExecutor(int corePoolSize,
508 int maximumPoolSize,
509 long keepAliveTime,
510 TimeUnit unit,
511 BlockingQueue<Runnable> workQueue,
512 ThreadFactory threadFactory) {
513 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
514 threadFactory, defaultHandler);
515 }
516
517 /**
518 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
519 * parameters and default thread factory.
520 *
521 * @param corePoolSize the number of threads to keep in the
522 * pool, even if they are idle.
523 * @param maximumPoolSize the maximum number of threads to allow in the
524 * pool.
525 * @param keepAliveTime when the number of threads is greater than
526 * the core, this is the maximum time that excess idle threads
527 * will wait for new tasks before terminating.
528 * @param unit the time unit for the keepAliveTime
529 * argument.
530 * @param workQueue the queue to use for holding tasks before they
531 * are executed. This queue will hold only the <tt>Runnable</tt>
532 * tasks submitted by the <tt>execute</tt> method.
533 * @param handler the handler to use when execution is blocked
534 * because the thread bounds and queue capacities are reached.
535 * @throws IllegalArgumentException if corePoolSize or
536 * keepAliveTime less than zero, or if maximumPoolSize less than or
537 * equal to zero, or if corePoolSize greater than maximumPoolSize.
538 * @throws NullPointerException if <tt>workQueue</tt>
539 * or <tt>handler</tt> are null.
540 */
541 public ThreadPoolExecutor(int corePoolSize,
542 int maximumPoolSize,
543 long keepAliveTime,
544 TimeUnit unit,
545 BlockingQueue<Runnable> workQueue,
546 RejectedExecutionHandler handler) {
547 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
548 Executors.defaultThreadFactory(), handler);
549 }
550
551 /**
552 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
553 * parameters.
554 *
555 * @param corePoolSize the number of threads to keep in the
556 * pool, even if they are idle.
557 * @param maximumPoolSize the maximum number of threads to allow in the
558 * pool.
559 * @param keepAliveTime when the number of threads is greater than
560 * the core, this is the maximum time that excess idle threads
561 * will wait for new tasks before terminating.
562 * @param unit the time unit for the keepAliveTime
563 * argument.
564 * @param workQueue the queue to use for holding tasks before they
565 * are executed. This queue will hold only the <tt>Runnable</tt>
566 * tasks submitted by the <tt>execute</tt> method.
567 * @param threadFactory the factory to use when the executor
568 * creates a new thread.
569 * @param handler the handler to use when execution is blocked
570 * because the thread bounds and queue capacities are reached.
571 * @throws IllegalArgumentException if corePoolSize or
572 * keepAliveTime less than zero, or if maximumPoolSize less than or
573 * equal to zero, or if corePoolSize greater than maximumPoolSize.
574 * @throws NullPointerException if <tt>workQueue</tt>
575 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
576 */
577 public ThreadPoolExecutor(int corePoolSize,
578 int maximumPoolSize,
579 long keepAliveTime,
580 TimeUnit unit,
581 BlockingQueue<Runnable> workQueue,
582 ThreadFactory threadFactory,
583 RejectedExecutionHandler handler) {
584 if (corePoolSize < 0 ||
585 maximumPoolSize <= 0 ||
586 maximumPoolSize < corePoolSize ||
587 keepAliveTime < 0)
588 throw new IllegalArgumentException();
589 if (workQueue == null || threadFactory == null || handler == null)
590 throw new NullPointerException();
591 this.corePoolSize = corePoolSize;
592 this.maximumPoolSize = maximumPoolSize;
593 this.workQueue = workQueue;
594 this.keepAliveTime = unit.toNanos(keepAliveTime);
595 this.threadFactory = threadFactory;
596 this.handler = handler;
597 }
598
599 /*
600 * Support for execute().
601 *
602 * Method execute() and its helper methods handle the various
603 * cases encountered when new tasks are submitted. The main
604 * execute() method proceeds in 3 steps:
605 *
606 * 1. If it appears that fewer than corePoolSize threads are
607 * running, try to start a new thread with the given command as
608 * its first task. The check here errs on the side of caution.
609 * The call to addIfUnderCorePoolSize rechecks runState and pool
610 * size under lock (they change only under lock) so prevents false
611 * alarms that would add threads when it shouldn't, but may also
612 * fail to add them when they should. This is compensated within
613 * the following steps.
614 *
615 * 2. If a task can be successfully queued, then we are done, but
616 * still need to compensate for missing the fact that we should
617 * have added a thread (because existing ones died) or that
618 * shutdown occurred since entry into this method. So we recheck
619 * state and if necessary (in ensureQueuedTaskHandled) roll back
620 * the enqueuing if shut down, or start a new thread if there are
621 * none.
622 *
623 * 3. If we cannot queue task, then we try to add a new
624 * thread. There's no guesswork here (addIfUnderMaximumPoolSize)
625 * since it is performed under lock. If it fails, we know we are
626 * shut down or saturated.
627 *
628 * The reason for taking this overall approach is to normally
629 * avoid holding mainLock during this method, which would be a
630 * serious scalability bottleneck. After warmup, almost all calls
631 * take step 2 in a way that entails no locking.
632 */
633
634 /**
635 * Executes the given task sometime in the future. The task
636 * may execute in a new thread or in an existing pooled thread.
637 *
638 * If the task cannot be submitted for execution, either because this
639 * executor has been shutdown or because its capacity has been reached,
640 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
641 *
642 * @param command the task to execute
643 * @throws RejectedExecutionException at discretion of
644 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
645 * for execution
646 * @throws NullPointerException if command is null
647 */
648 public void execute(Runnable command) {
649 if (command == null)
650 throw new NullPointerException();
651 if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
652 if (runState == RUNNING && workQueue.offer(command)) {
653 if (runState != RUNNING || poolSize == 0)
654 ensureQueuedTaskHandled(command);
655 }
656 else if (!addIfUnderMaximumPoolSize(command))
657 reject(command); // is shutdown or saturated
658 }
659 }
660
661 /**
662 * Creates and returns a new thread running firstTask as its first
663 * task. Call only while holding mainLock.
664 *
665 * @param firstTask the task the new thread should run first (or
666 * null if none)
667 * @return the new thread, or null if threadFactory fails to create thread
668 */
669 private Thread addThread(Runnable firstTask) {
670 Worker w = new Worker(firstTask);
671 Thread t = threadFactory.newThread(w);
672 if (t != null) {
673 w.thread = t;
674 workers.add(w);
675 int nt = ++poolSize;
676 if (nt > largestPoolSize)
677 largestPoolSize = nt;
678 }
679 return t;
680 }
681
682 /**
683 * Creates and starts a new thread running firstTask as its first
684 * task, only if fewer than corePoolSize threads are running
685 * and the pool is not shut down.
686 * @param firstTask the task the new thread should run first (or
687 * null if none)
688 * @return true if successful
689 */
690 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
691 Thread t = null;
692 final ReentrantLock mainLock = this.mainLock;
693 mainLock.lock();
694 try {
695 if (poolSize < corePoolSize && runState == RUNNING)
696 t = addThread(firstTask);
697 } finally {
698 mainLock.unlock();
699 }
700 if (t == null)
701 return false;
702 t.start();
703 return true;
704 }
705
706 /**
707 * Creates and starts a new thread running firstTask as its first
708 * task, only if fewer than maximumPoolSize threads are running
709 * and pool is not shut down.
710 * @param firstTask the task the new thread should run first (or
711 * null if none)
712 * @return true if successful
713 */
714 private boolean addIfUnderMaximumPoolSize(Runnable firstTask) {
715 Thread t = null;
716 final ReentrantLock mainLock = this.mainLock;
717 mainLock.lock();
718 try {
719 if (poolSize < maximumPoolSize && runState == RUNNING)
720 t = addThread(firstTask);
721 } finally {
722 mainLock.unlock();
723 }
724 if (t == null)
725 return false;
726 t.start();
727 return true;
728 }
729
730 /**
731 * Rechecks state after queuing a task. Called from execute when
732 * pool state has been observed to change after queuing a task. If
733 * the task was queued concurrently with a call to shutdownNow,
734 * and is still present in the queue, this task must be removed
735 * and rejected to preserve shutdownNow guarantees. Otherwise,
736 * this method ensures (unless addThread fails) that there is at
737 * least one live thread to handle this task.
738 * @param command the task
739 */
740 private void ensureQueuedTaskHandled(Runnable command) {
741 final ReentrantLock mainLock = this.mainLock;
742 mainLock.lock();
743 boolean reject = false;
744 Thread t = null;
745 try {
746 int state = runState;
747 if (state != RUNNING && workQueue.remove(command))
748 reject = true;
749 else if (state < STOP &&
750 poolSize < Math.max(corePoolSize, 1) &&
751 !workQueue.isEmpty())
752 t = addThread(null);
753 } finally {
754 mainLock.unlock();
755 }
756 if (reject)
757 reject(command);
758 else if (t != null)
759 t.start();
760 }
761
762 /**
763 * Invokes the rejected execution handler for the given command.
764 */
765 void reject(Runnable command) {
766 handler.rejectedExecution(command, this);
767 }
768
769
770 /**
771 * Worker threads.
772 *
773 * Worker threads can start out life either with an initial first
774 * task, or without one. Normally, they are started with a first
775 * task. This enables execute(), etc to bypass queuing when there
776 * are fewer than corePoolSize threads (in which case we always
777 * start one), or when the queue is full.(in which case we must
778 * bypass queue.) Initially idle threads are created either by
779 * users (prestartCoreThread and setCorePoolSize) or when methods
780 * ensureQueuedTaskHandled and tryTerminate notice that the queue
781 * is not empty but there are no active threads to handle them.
782 *
783 * After completing a task, workers try to get another one,
784 * via method getTask. If they cannot (i.e., getTask returns
785 * null), they exit, calling workerDone to update pool state.
786 *
787 * When starting to run a task, unless the pool is stopped, each
788 * worker thread ensures that it is not interrupted, and uses
789 * runLock to prevent the pool from interrupting it in the midst
790 * of execution. This shields user tasks from any interrupts that
791 * may otherwise be needed during shutdown (see method
792 * interruptIdleWorkers), unless the pool is stopping (via
793 * shutdownNow) in which case interrupts are let through to affect
794 * both tasks and workers. However, this shielding does not
795 * necessarily protect the workers from lagging interrupts from
796 * other user threads directed towards tasks that have already
797 * been completed. Thus, a worker thread may be interrupted
798 * needlessly (for example in getTask), in which case it rechecks
799 * pool state to see if it should exit.
800 */
801 private final class Worker implements Runnable {
802 /**
803 * The runLock is acquired and released surrounding each task
804 * execution. It mainly protects against interrupts that are
805 * intended to cancel the worker thread from instead
806 * interrupting the task being run.
807 */
808 private final ReentrantLock runLock = new ReentrantLock();
809
810 /**
811 * Initial task to run before entering run loop. Possibly null.
812 */
813 private Runnable firstTask;
814
815 /**
816 * Per thread completed task counter; accumulated
817 * into completedTaskCount upon termination.
818 */
819 volatile long completedTasks;
820
821 /**
822 * Thread this worker is running in. Acts as a final field,
823 * but cannot be set until thread is created.
824 */
825 Thread thread;
826
827 Worker(Runnable firstTask) {
828 this.firstTask = firstTask;
829 }
830
831 boolean isActive() {
832 return runLock.isLocked();
833 }
834
835 /**
836 * Interrupts thread if not running a task.
837 */
838 void interruptIfIdle() {
839 final ReentrantLock runLock = this.runLock;
840 if (runLock.tryLock()) {
841 try {
842 thread.interrupt();
843 } finally {
844 runLock.unlock();
845 }
846 }
847 }
848
849 /**
850 * Interrupts thread even if running a task.
851 */
852 void interruptNow() {
853 thread.interrupt();
854 }
855
856 /**
857 * Main run loop
858 */
859 public void run() {
860 /*
861 * Basically, we repeatedly get tasks from queue and
862 * execute them, while coping with a number of issues:
863 *
864 * 1. We may start out with a firstTask, in which case we
865 * don't need to get the first one.
866 *
867 * 2. getTask will return null upon interruption (normally
868 * due to shutdown or lack of work) which will break loop
869 * and cause this thread to die. This is the "normal"
870 * non-abrupt exit (tracked by completedAbruptly). All
871 * other cases exit with completedAbruptly true, which is
872 * relayed to workerDone as an indicator that this thread
873 * should be replaced.
874 *
875 * 3. Before running any task, we set runLock (mainly) in
876 * order to avoid interrupts. We then ensure that unless
877 * pool is stopping, this thread does not have its
878 * interrupt set. This requires a double-check of state in
879 * case the interrupt was cleared concurrently with a
880 * shutdownNow -- if so, the interrupt is re-enabled.
881 * This lock is held across all three of beforeExecute,
882 * task.run, and afterExecute, which also shields
883 * extension code from stray interrupts.
884 *
885 * 4. Each task run is preceded by a call to beforeExecute,
886 * which might throw an exception, in which case, to be
887 * conservative, we cause thread to die (breaking loop and
888 * falling into workerDone), without processing the task.
889 *
890 * 5. Assuming beforeExecute completes normally, we run
891 * the task, gathering any of its thrown exceptions to
892 * send to afterExecute. We separately handle
893 * RuntimeException, Error (both of which the specs
894 * guarantee that we trap) and arbitrary Throwables.
895 * Because we cannot rethrow Throwables within
896 * Runnable.run, we wrap them within Errors on the way out
897 * (to the thread's UncaughtExceptionHandler). Any thrown
898 * exception also conservatively causes thread to die.
899 *
900 * 6. After run completes, we call afterExecute, which
901 * may also throw an exception, which will also cause
902 * thread to die. According to JLS Sec 14.20, this exception
903 * is the one that will be in effect even if task.run throws.
904 *
905 * The net effect of the exception mechanics is that
906 * afterExecute and the thread's UncaughtExceptionHandler
907 * have as accurate information as we can provide about
908 * any problems encountered by user code.
909 */
910
911 final ReentrantLock runLock = this.runLock;
912 boolean completedAbruptly = true;
913 Runnable task = firstTask;
914 firstTask = null;
915 try {
916 while (task != null || (task = getTask()) != null) {
917 runLock.lock();
918 try {
919 /*
920 * Ensure that unless pool is stopping, this thread
921 * does not have its interrupt set. This requires a
922 * double-check of state in case the interrupt was
923 * cleared concurrently with a shutdownNow -- if so,
924 * the interrupt is re-enabled.
925 */
926 if (runState < STOP &&
927 Thread.interrupted() &&
928 runState >= STOP)
929 thread.interrupt();
930
931 beforeExecute(thread, task);
932
933 Throwable thrown = null;
934 try {
935 task.run();
936 } catch (RuntimeException x) {
937 thrown = x; throw x;
938 } catch (Error x) {
939 thrown = x; throw x;
940 } catch (Throwable x) {
941 thrown = x; throw new Error(x);
942 } finally {
943 afterExecute(task, thrown);
944 }
945 } finally {
946 task = null;
947 ++completedTasks;
948 runLock.unlock();
949 }
950 }
951 completedAbruptly = false;
952 } finally {
953 workerDone(this, completedAbruptly);
954 }
955 }
956 }
957
958 /* Utilities for worker thread control */
959
960 /**
961 * Gets the next task for a worker thread to run. The general
962 * approach is similar to execute() in that worker threads trying
963 * to get a task to run do so on the basis of prevailing state
964 * accessed outside of locks. This may cause them to choose the
965 * "wrong" action, such as trying to exit because no tasks
966 * appear to be available, or entering a take when the pool is in
967 * the process of being shut down. These potential problems are
968 * countered by (1) rechecking pool state (in workerCanExit)
969 * before giving up, and (2) interrupting other workers upon
970 * shutdown, so they can recheck state. All other user-based state
971 * changes (to allowCoreThreadTimeOut etc) are OK even when
972 * performed asynchronously wrt getTask.
973 *
974 * @return the task
975 */
976 Runnable getTask() {
977 for (;;) {
978 try {
979 int state = runState;
980 if (state > SHUTDOWN)
981 return null;
982 Runnable r;
983 if (state == SHUTDOWN) // Help drain queue
984 r = workQueue.poll();
985 else if (poolSize > corePoolSize || allowCoreThreadTimeOut)
986 r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
987 else
988 r = workQueue.take();
989 if (r != null)
990 return r;
991 if (workerCanExit()) {
992 if (runState >= SHUTDOWN) // Wake up others
993 interruptIdleWorkers();
994 return null;
995 }
996 // Else retry
997 } catch (InterruptedException ie) {
998 // On interruption, re-check runState
999 }
1000 }
1001 }
1002
1003 /**
1004 * Check whether a worker thread that fails to get a task can
1005 * exit. We allow a worker thread to die if the pool is stopping,
1006 * or the queue is empty, or there is at least one thread to
1007 * handle possibly non-empty queue, even if core timeouts are
1008 * allowed.
1009 */
1010 private boolean workerCanExit() {
1011 final ReentrantLock mainLock = this.mainLock;
1012 mainLock.lock();
1013 boolean canExit;
1014 try {
1015 canExit = runState >= STOP ||
1016 workQueue.isEmpty() ||
1017 (allowCoreThreadTimeOut &&
1018 poolSize > Math.max(1, corePoolSize));
1019 } finally {
1020 mainLock.unlock();
1021 }
1022 return canExit;
1023 }
1024
1025 /**
1026 * Wakes up all threads that might be waiting for tasks so they
1027 * can check for termination. Note: this method is also called by
1028 * ScheduledThreadPoolExecutor.
1029 */
1030 void interruptIdleWorkers() {
1031 final ReentrantLock mainLock = this.mainLock;
1032 mainLock.lock();
1033 try {
1034 for (Worker w : workers)
1035 w.interruptIfIdle();
1036 } finally {
1037 mainLock.unlock();
1038 }
1039 }
1040
1041 /**
1042 * Removes an exiting worker thread from worker set, and
1043 * gathers its statistics. Additionally, this may:
1044 * 1. Cause termination if this is the last exiting thread
1045 * during shutdown, or
1046 * 2. If not shutting down, generate a replacement if this
1047 * thread completed abruptly (due to an exception in one of
1048 * its tasks) or there are any queued tasks.
1049 * @param w the worker
1050 * @param completedAbruptly whether w died due to a task throwing
1051 */
1052 void workerDone(Worker w, boolean completedAbruptly) {
1053 Thread replacement = null;
1054 final ReentrantLock mainLock = this.mainLock;
1055 mainLock.lock();
1056 try {
1057 completedTaskCount += w.completedTasks;
1058 workers.remove(w);
1059 int n = --poolSize;
1060 if (runState < STOP &&
1061 (completedAbruptly || !workQueue.isEmpty()))
1062 replacement = addThread(null);
1063 else if (n == 0)
1064 tryTerminate();
1065 } finally {
1066 mainLock.unlock();
1067 }
1068 if (replacement != null)
1069 replacement.start();
1070 }
1071
1072 /* Termination support. */
1073
1074 /**
1075 * Transitions to TERMINATED state if either (SHUTDOWN and pool
1076 * and queue empty) or (STOP and pool empty). Call only while
1077 * holding mainLock.
1078 *
1079 * This method is called from the three places in which
1080 * termination can occur: in workerDone on exit of the last thread
1081 * after pool has been shut down, or directly within calls to
1082 * shutdown or shutdownNow, if there are no live threads.
1083 */
1084 private void tryTerminate() {
1085 if (poolSize == 0) {
1086 int state = runState;
1087 if (state == STOP || (state == SHUTDOWN && workQueue.isEmpty())) {
1088 runState = TERMINATED;
1089 termination.signalAll();
1090 terminated();
1091 }
1092 }
1093 }
1094
1095 /**
1096 * Initiates an orderly shutdown in which previously submitted
1097 * tasks are executed, but no new tasks will be
1098 * accepted. Invocation has no additional effect if already shut
1099 * down.
1100 * @throws SecurityException if a security manager exists and
1101 * shutting down this ExecutorService may manipulate threads that
1102 * the caller is not permitted to modify because it does not hold
1103 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1104 * or the security manager's <tt>checkAccess</tt> method denies access.
1105 */
1106 public void shutdown() {
1107 /*
1108 * Conceptually, shutdown is just a matter of changing the
1109 * runState to SHUTDOWN, and then interrupting any worker
1110 * threads that might be blocked in getTask() to wake them up
1111 * so they can exit. Then, if there happen not to be any
1112 * threads or tasks, we can directly terminate pool via
1113 * tryTerminate. Else, the last worker to leave the building
1114 * turns off the lights (in workerDone).
1115 *
1116 * But this is made more delicate because we must cooperate
1117 * with the security manager (if present), which may implement
1118 * policies that make more sense for operations on Threads
1119 * than they do for ThreadPools. This requires 3 steps:
1120 *
1121 * 1. Making sure caller has permission to shut down threads
1122 * in general (see shutdownPerm).
1123 *
1124 * 2. If (1) passes, making sure the caller is allowed to
1125 * modify each of our threads. This might not be true even if
1126 * first check passed, if the SecurityManager treats some
1127 * threads specially. If this check passes, then we can try
1128 * to set runState.
1129 *
1130 * 3. If both (1) and (2) pass, dealing with inconsistent
1131 * security managers that allow checkAccess but then throw a
1132 * SecurityException when interrupt() is invoked. In this
1133 * third case, because we have already set runState, we can
1134 * only try to back out from the shutdown as cleanly as
1135 * possible. Some workers may have been killed but we remain
1136 * in non-shutdown state.
1137 */
1138
1139 SecurityManager security = System.getSecurityManager();
1140 if (security != null)
1141 security.checkPermission(shutdownPerm);
1142
1143 final ReentrantLock mainLock = this.mainLock;
1144 mainLock.lock();
1145 try {
1146 if (security != null) { // Check if caller can modify our threads
1147 for (Worker w : workers)
1148 security.checkAccess(w.thread);
1149 }
1150
1151 int state = runState;
1152 if (state < SHUTDOWN)
1153 runState = SHUTDOWN;
1154
1155 try {
1156 for (Worker w : workers)
1157 w.interruptIfIdle();
1158 } catch (SecurityException se) { // Back out
1159 runState = state;
1160 throw se;
1161 }
1162
1163 tryTerminate(); // Terminate now if pool and queue empty
1164 } finally {
1165 mainLock.unlock();
1166 }
1167 }
1168
1169 /**
1170 * Attempts to stop all actively executing tasks, halts the
1171 * processing of waiting tasks, and returns a list of the tasks
1172 * that were awaiting execution. These tasks are drained (removed)
1173 * from the task queue upon return from this method.
1174 *
1175 * <p>There are no guarantees beyond best-effort attempts to stop
1176 * processing actively executing tasks. This implementation
1177 * cancels tasks via {@link Thread#interrupt}, so any task that
1178 * fails to respond to interrupts may never terminate.
1179 *
1180 * @return list of tasks that never commenced execution
1181 * @throws SecurityException if a security manager exists and
1182 * shutting down this ExecutorService may manipulate threads that
1183 * the caller is not permitted to modify because it does not hold
1184 * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1185 * or the security manager's <tt>checkAccess</tt> method denies access.
1186 */
1187 public List<Runnable> shutdownNow() {
1188 /*
1189 * shutdownNow differs from shutdown only in that
1190 * 1. runState is set to STOP,
1191 * 2. all worker threads are interrupted, not just the idle ones, and
1192 * 3. the queue is drained and returned.
1193 */
1194 SecurityManager security = System.getSecurityManager();
1195 if (security != null)
1196 security.checkPermission(shutdownPerm);
1197
1198 final ReentrantLock mainLock = this.mainLock;
1199 mainLock.lock();
1200 try {
1201 if (security != null) { // Check if caller can modify our threads
1202 for (Worker w : workers)
1203 security.checkAccess(w.thread);
1204 }
1205
1206 int state = runState;
1207 if (state < STOP)
1208 runState = STOP;
1209
1210 try {
1211 for (Worker w : workers)
1212 w.interruptNow();
1213 } catch (SecurityException se) { // Back out
1214 runState = state;
1215 throw se;
1216 }
1217
1218 List<Runnable> tasks = drainQueue();
1219 tryTerminate(); // Terminate now if pool and queue empty
1220 return tasks;
1221 } finally {
1222 mainLock.unlock();
1223 }
1224 }
1225
1226 /**
1227 * Drains the task queue into a new list. Used by shutdownNow.
1228 * Call only while holding main lock.
1229 */
1230 private List<Runnable> drainQueue() {
1231 List<Runnable> taskList = new ArrayList<Runnable>();
1232 workQueue.drainTo(taskList);
1233 /*
1234 * If the queue is a DelayQueue or any other kind of queue
1235 * for which poll or drainTo may fail to remove some elements,
1236 * we need to manually traverse and remove remaining tasks.
1237 * To guarantee atomicity wrt other threads using this queue,
1238 * we need to create a new iterator for each element removed.
1239 */
1240 while (!workQueue.isEmpty()) {
1241 Iterator<Runnable> it = workQueue.iterator();
1242 try {
1243 if (it.hasNext()) {
1244 Runnable r = it.next();
1245 if (workQueue.remove(r))
1246 taskList.add(r);
1247 }
1248 } catch (ConcurrentModificationException ignore) {
1249 }
1250 }
1251 return taskList;
1252 }
1253
1254 public boolean isShutdown() {
1255 return runState != RUNNING;
1256 }
1257
1258 /**
1259 * Returns true if this executor is in the process of terminating
1260 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1261 * completely terminated. This method may be useful for
1262 * debugging. A return of <tt>true</tt> reported a sufficient
1263 * period after shutdown may indicate that submitted tasks have
1264 * ignored or suppressed interruption, causing this executor not
1265 * to properly terminate.
1266 * @return true if terminating but not yet terminated
1267 */
1268 public boolean isTerminating() {
1269 int state = runState;
1270 return state == SHUTDOWN || state == STOP;
1271 }
1272
1273 public boolean isTerminated() {
1274 return runState == TERMINATED;
1275 }
1276
1277 public boolean awaitTermination(long timeout, TimeUnit unit)
1278 throws InterruptedException {
1279 long nanos = unit.toNanos(timeout);
1280 final ReentrantLock mainLock = this.mainLock;
1281 mainLock.lock();
1282 try {
1283 for (;;) {
1284 if (runState == TERMINATED)
1285 return true;
1286 if (nanos <= 0)
1287 return false;
1288 nanos = termination.awaitNanos(nanos);
1289 }
1290 } finally {
1291 mainLock.unlock();
1292 }
1293 }
1294
1295 /**
1296 * Invokes <tt>shutdown</tt> when this executor is no longer
1297 * referenced.
1298 */
1299 protected void finalize() {
1300 shutdown();
1301 }
1302
1303 /* Getting and setting tunable parameters */
1304
1305 /**
1306 * Sets the thread factory used to create new threads.
1307 *
1308 * @param threadFactory the new thread factory
1309 * @throws NullPointerException if threadFactory is null
1310 * @see #getThreadFactory
1311 */
1312 public void setThreadFactory(ThreadFactory threadFactory) {
1313 if (threadFactory == null)
1314 throw new NullPointerException();
1315 this.threadFactory = threadFactory;
1316 }
1317
1318 /**
1319 * Returns the thread factory used to create new threads.
1320 *
1321 * @return the current thread factory
1322 * @see #setThreadFactory
1323 */
1324 public ThreadFactory getThreadFactory() {
1325 return threadFactory;
1326 }
1327
1328 /**
1329 * Sets a new handler for unexecutable tasks.
1330 *
1331 * @param handler the new handler
1332 * @throws NullPointerException if handler is null
1333 * @see #getRejectedExecutionHandler
1334 */
1335 public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1336 if (handler == null)
1337 throw new NullPointerException();
1338 this.handler = handler;
1339 }
1340
1341 /**
1342 * Returns the current handler for unexecutable tasks.
1343 *
1344 * @return the current handler
1345 * @see #setRejectedExecutionHandler
1346 */
1347 public RejectedExecutionHandler getRejectedExecutionHandler() {
1348 return handler;
1349 }
1350
1351 /**
1352 * Sets the core number of threads. This overrides any value set
1353 * in the constructor. If the new value is smaller than the
1354 * current value, excess existing threads will be terminated when
1355 * they next become idle. If larger, new threads will, if needed,
1356 * be started to execute any queued tasks.
1357 *
1358 * @param corePoolSize the new core size
1359 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1360 * less than zero
1361 * @see #getCorePoolSize
1362 */
1363 public void setCorePoolSize(int corePoolSize) {
1364 if (corePoolSize < 0)
1365 throw new IllegalArgumentException();
1366 final ReentrantLock mainLock = this.mainLock;
1367 mainLock.lock();
1368 try {
1369 int extra = this.corePoolSize - corePoolSize;
1370 this.corePoolSize = corePoolSize;
1371 if (extra < 0) {
1372 int n = workQueue.size(); // don't add more threads than tasks
1373 while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize) {
1374 Thread t = addThread(null);
1375 if (t != null)
1376 t.start();
1377 else
1378 break;
1379 }
1380 }
1381 else if (extra > 0 && poolSize > corePoolSize) {
1382 try {
1383 Iterator<Worker> it = workers.iterator();
1384 while (it.hasNext() &&
1385 extra-- > 0 &&
1386 poolSize > corePoolSize &&
1387 workQueue.remainingCapacity() == 0)
1388 it.next().interruptIfIdle();
1389 } catch (SecurityException ignore) {
1390 // Not an error; it is OK if the threads stay live
1391 }
1392 }
1393 } finally {
1394 mainLock.unlock();
1395 }
1396 }
1397
1398 /**
1399 * Returns the core number of threads.
1400 *
1401 * @return the core number of threads
1402 * @see #setCorePoolSize
1403 */
1404 public int getCorePoolSize() {
1405 return corePoolSize;
1406 }
1407
1408 /**
1409 * Starts a core thread, causing it to idly wait for work. This
1410 * overrides the default policy of starting core threads only when
1411 * new tasks are executed. This method will return <tt>false</tt>
1412 * if all core threads have already been started.
1413 * @return true if a thread was started
1414 */
1415 public boolean prestartCoreThread() {
1416 return addIfUnderCorePoolSize(null);
1417 }
1418
1419 /**
1420 * Starts all core threads, causing them to idly wait for work. This
1421 * overrides the default policy of starting core threads only when
1422 * new tasks are executed.
1423 * @return the number of threads started
1424 */
1425 public int prestartAllCoreThreads() {
1426 int n = 0;
1427 while (addIfUnderCorePoolSize(null))
1428 ++n;
1429 return n;
1430 }
1431
1432 /**
1433 * Returns true if this pool allows core threads to time out and
1434 * terminate if no tasks arrive within the keepAlive time, being
1435 * replaced if needed when new tasks arrive. When true, the same
1436 * keep-alive policy applying to non-core threads applies also to
1437 * core threads. When false (the default), core threads are never
1438 * terminated due to lack of incoming tasks.
1439 * @return <tt>true</tt> if core threads are allowed to time out,
1440 * else <tt>false</tt>
1441 *
1442 * @since 1.6
1443 */
1444 public boolean allowsCoreThreadTimeOut() {
1445 return allowCoreThreadTimeOut;
1446 }
1447
1448 /**
1449 * Sets the policy governing whether core threads may time out and
1450 * terminate if no tasks arrive within the keep-alive time, being
1451 * replaced if needed when new tasks arrive. When false, core
1452 * threads are never terminated due to lack of incoming
1453 * tasks. When true, the same keep-alive policy applying to
1454 * non-core threads applies also to core threads. To avoid
1455 * continual thread replacement, the keep-alive time must be
1456 * greater than zero when setting <tt>true</tt>. This method
1457 * should in general be called before the pool is actively used.
1458 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1459 * @throws IllegalArgumentException if value is <tt>true</tt>
1460 * and the current keep-alive time is not greater than zero.
1461 *
1462 * @since 1.6
1463 */
1464 public void allowCoreThreadTimeOut(boolean value) {
1465 if (value && keepAliveTime <= 0)
1466 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1467
1468 allowCoreThreadTimeOut = value;
1469 }
1470
1471 /**
1472 * Sets the maximum allowed number of threads. This overrides any
1473 * value set in the constructor. If the new value is smaller than
1474 * the current value, excess existing threads will be
1475 * terminated when they next become idle.
1476 *
1477 * @param maximumPoolSize the new maximum
1478 * @throws IllegalArgumentException if the new maximum is
1479 * less than or equal to zero, or
1480 * less than the {@linkplain #getCorePoolSize core pool size}
1481 * @see #getMaximumPoolSize
1482 */
1483 public void setMaximumPoolSize(int maximumPoolSize) {
1484 if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1485 throw new IllegalArgumentException();
1486 final ReentrantLock mainLock = this.mainLock;
1487 mainLock.lock();
1488 try {
1489 int extra = this.maximumPoolSize - maximumPoolSize;
1490 this.maximumPoolSize = maximumPoolSize;
1491 if (extra > 0 && poolSize > maximumPoolSize) {
1492 try {
1493 Iterator<Worker> it = workers.iterator();
1494 while (it.hasNext() &&
1495 extra > 0 &&
1496 poolSize > maximumPoolSize) {
1497 it.next().interruptIfIdle();
1498 --extra;
1499 }
1500 } catch (SecurityException ignore) {
1501 // Not an error; it is OK if the threads stay live
1502 }
1503 }
1504 } finally {
1505 mainLock.unlock();
1506 }
1507 }
1508
1509 /**
1510 * Returns the maximum allowed number of threads.
1511 *
1512 * @return the maximum allowed number of threads
1513 * @see #setMaximumPoolSize
1514 */
1515 public int getMaximumPoolSize() {
1516 return maximumPoolSize;
1517 }
1518
1519 /**
1520 * Sets the time limit for which threads may remain idle before
1521 * being terminated. If there are more than the core number of
1522 * threads currently in the pool, after waiting this amount of
1523 * time without processing a task, excess threads will be
1524 * terminated. This overrides any value set in the constructor.
1525 * @param time the time to wait. A time value of zero will cause
1526 * excess threads to terminate immediately after executing tasks.
1527 * @param unit the time unit of the time argument
1528 * @throws IllegalArgumentException if time less than zero or
1529 * if time is zero and allowsCoreThreadTimeOut
1530 * @see #getKeepAliveTime
1531 */
1532 public void setKeepAliveTime(long time, TimeUnit unit) {
1533 if (time < 0)
1534 throw new IllegalArgumentException();
1535 if (time == 0 && allowsCoreThreadTimeOut())
1536 throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1537 this.keepAliveTime = unit.toNanos(time);
1538 }
1539
1540 /**
1541 * Returns the thread keep-alive time, which is the amount of time
1542 * that threads in excess of the core pool size may remain
1543 * idle before being terminated.
1544 *
1545 * @param unit the desired time unit of the result
1546 * @return the time limit
1547 * @see #setKeepAliveTime
1548 */
1549 public long getKeepAliveTime(TimeUnit unit) {
1550 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1551 }
1552
1553 /* User-level queue utilities */
1554
1555 /**
1556 * Returns the task queue used by this executor. Access to the
1557 * task queue is intended primarily for debugging and monitoring.
1558 * This queue may be in active use. Retrieving the task queue
1559 * does not prevent queued tasks from executing.
1560 *
1561 * @return the task queue
1562 */
1563 public BlockingQueue<Runnable> getQueue() {
1564 return workQueue;
1565 }
1566
1567 /**
1568 * Removes this task from the executor's internal queue if it is
1569 * present, thus causing it not to be run if it has not already
1570 * started.
1571 *
1572 * <p> This method may be useful as one part of a cancellation
1573 * scheme. It may fail to remove tasks that have been converted
1574 * into other forms before being placed on the internal queue. For
1575 * example, a task entered using <tt>submit</tt> might be
1576 * converted into a form that maintains <tt>Future</tt> status.
1577 * However, in such cases, method {@link ThreadPoolExecutor#purge}
1578 * may be used to remove those Futures that have been cancelled.
1579 *
1580 * @param task the task to remove
1581 * @return true if the task was removed
1582 */
1583 public boolean remove(Runnable task) {
1584 return getQueue().remove(task);
1585 }
1586
1587 /**
1588 * Tries to remove from the work queue all {@link Future}
1589 * tasks that have been cancelled. This method can be useful as a
1590 * storage reclamation operation, that has no other impact on
1591 * functionality. Cancelled tasks are never executed, but may
1592 * accumulate in work queues until worker threads can actively
1593 * remove them. Invoking this method instead tries to remove them now.
1594 * However, this method may fail to remove tasks in
1595 * the presence of interference by other threads.
1596 */
1597 public void purge() {
1598 // Fail if we encounter interference during traversal
1599 try {
1600 Iterator<Runnable> it = getQueue().iterator();
1601 while (it.hasNext()) {
1602 Runnable r = it.next();
1603 if (r instanceof Future<?>) {
1604 Future<?> c = (Future<?>)r;
1605 if (c.isCancelled())
1606 it.remove();
1607 }
1608 }
1609 }
1610 catch (ConcurrentModificationException ex) {
1611 return;
1612 }
1613 }
1614
1615 /* Statistics */
1616
1617 /**
1618 * Returns the current number of threads in the pool.
1619 *
1620 * @return the number of threads
1621 */
1622 public int getPoolSize() {
1623 return poolSize;
1624 }
1625
1626 /**
1627 * Returns the approximate number of threads that are actively
1628 * executing tasks.
1629 *
1630 * @return the number of threads
1631 */
1632 public int getActiveCount() {
1633 final ReentrantLock mainLock = this.mainLock;
1634 mainLock.lock();
1635 try {
1636 int n = 0;
1637 for (Worker w : workers) {
1638 if (w.isActive())
1639 ++n;
1640 }
1641 return n;
1642 } finally {
1643 mainLock.unlock();
1644 }
1645 }
1646
1647 /**
1648 * Returns the largest number of threads that have ever
1649 * simultaneously been in the pool.
1650 *
1651 * @return the number of threads
1652 */
1653 public int getLargestPoolSize() {
1654 final ReentrantLock mainLock = this.mainLock;
1655 mainLock.lock();
1656 try {
1657 return largestPoolSize;
1658 } finally {
1659 mainLock.unlock();
1660 }
1661 }
1662
1663 /**
1664 * Returns the approximate total number of tasks that have ever been
1665 * scheduled for execution. Because the states of tasks and
1666 * threads may change dynamically during computation, the returned
1667 * value is only an approximation.
1668 *
1669 * @return the number of tasks
1670 */
1671 public long getTaskCount() {
1672 final ReentrantLock mainLock = this.mainLock;
1673 mainLock.lock();
1674 try {
1675 long n = completedTaskCount;
1676 for (Worker w : workers) {
1677 n += w.completedTasks;
1678 if (w.isActive())
1679 ++n;
1680 }
1681 return n + workQueue.size();
1682 } finally {
1683 mainLock.unlock();
1684 }
1685 }
1686
1687 /**
1688 * Returns the approximate total number of tasks that have
1689 * completed execution. Because the states of tasks and threads
1690 * may change dynamically during computation, the returned value
1691 * is only an approximation, but one that does not ever decrease
1692 * across successive calls.
1693 *
1694 * @return the number of tasks
1695 */
1696 public long getCompletedTaskCount() {
1697 final ReentrantLock mainLock = this.mainLock;
1698 mainLock.lock();
1699 try {
1700 long n = completedTaskCount;
1701 for (Worker w : workers)
1702 n += w.completedTasks;
1703 return n;
1704 } finally {
1705 mainLock.unlock();
1706 }
1707 }
1708
1709 /* Extension hooks */
1710
1711 /**
1712 * Method invoked prior to executing the given Runnable in the
1713 * given thread. This method is invoked by thread <tt>t</tt> that
1714 * will execute task <tt>r</tt>, and may be used to re-initialize
1715 * ThreadLocals, or to perform logging.
1716 *
1717 * <p>This implementation does nothing, but may be customized in
1718 * subclasses. Note: To properly nest multiple overridings, subclasses
1719 * should generally invoke <tt>super.beforeExecute</tt> at the end of
1720 * this method.
1721 *
1722 * @param t the thread that will run task r.
1723 * @param r the task that will be executed.
1724 */
1725 protected void beforeExecute(Thread t, Runnable r) { }
1726
1727 /**
1728 * Method invoked upon completion of execution of the given Runnable.
1729 * This method is invoked by the thread that executed the task. If
1730 * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1731 * or <tt>Error</tt> that caused execution to terminate abruptly.
1732 *
1733 * <p><b>Note:</b> When actions are enclosed in tasks (such as
1734 * {@link FutureTask}) either explicitly or via methods such as
1735 * <tt>submit</tt>, these task objects catch and maintain
1736 * computational exceptions, and so they do not cause abrupt
1737 * termination, and the internal exceptions are <em>not</em>
1738 * passed to this method.
1739 *
1740 * <p>This implementation does nothing, but may be customized in
1741 * subclasses. Note: To properly nest multiple overridings, subclasses
1742 * should generally invoke <tt>super.afterExecute</tt> at the
1743 * beginning of this method.
1744 *
1745 * @param r the runnable that has completed.
1746 * @param t the exception that caused termination, or null if
1747 * execution completed normally.
1748 */
1749 protected void afterExecute(Runnable r, Throwable t) { }
1750
1751 /**
1752 * Method invoked when the Executor has terminated. Default
1753 * implementation does nothing. Note: To properly nest multiple
1754 * overridings, subclasses should generally invoke
1755 * <tt>super.terminated</tt> within this method.
1756 */
1757 protected void terminated() { }
1758
1759 /* Predefined RejectedExecutionHandlers */
1760
1761 /**
1762 * A handler for rejected tasks that runs the rejected task
1763 * directly in the calling thread of the <tt>execute</tt> method,
1764 * unless the executor has been shut down, in which case the task
1765 * is discarded.
1766 */
1767 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1768 /**
1769 * Creates a <tt>CallerRunsPolicy</tt>.
1770 */
1771 public CallerRunsPolicy() { }
1772
1773 /**
1774 * Executes task r in the caller's thread, unless the executor
1775 * has been shut down, in which case the task is discarded.
1776 * @param r the runnable task requested to be executed
1777 * @param e the executor attempting to execute this task
1778 */
1779 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1780 if (!e.isShutdown()) {
1781 r.run();
1782 }
1783 }
1784 }
1785
1786 /**
1787 * A handler for rejected tasks that throws a
1788 * <tt>RejectedExecutionException</tt>.
1789 */
1790 public static class AbortPolicy implements RejectedExecutionHandler {
1791 /**
1792 * Creates an <tt>AbortPolicy</tt>.
1793 */
1794 public AbortPolicy() { }
1795
1796 /**
1797 * Always throws RejectedExecutionException.
1798 * @param r the runnable task requested to be executed
1799 * @param e the executor attempting to execute this task
1800 * @throws RejectedExecutionException always.
1801 */
1802 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1803 throw new RejectedExecutionException();
1804 }
1805 }
1806
1807 /**
1808 * A handler for rejected tasks that silently discards the
1809 * rejected task.
1810 */
1811 public static class DiscardPolicy implements RejectedExecutionHandler {
1812 /**
1813 * Creates a <tt>DiscardPolicy</tt>.
1814 */
1815 public DiscardPolicy() { }
1816
1817 /**
1818 * Does nothing, which has the effect of discarding task r.
1819 * @param r the runnable task requested to be executed
1820 * @param e the executor attempting to execute this task
1821 */
1822 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1823 }
1824 }
1825
1826 /**
1827 * A handler for rejected tasks that discards the oldest unhandled
1828 * request and then retries <tt>execute</tt>, unless the executor
1829 * is shut down, in which case the task is discarded.
1830 */
1831 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1832 /**
1833 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1834 */
1835 public DiscardOldestPolicy() { }
1836
1837 /**
1838 * Obtains and ignores the next task that the executor
1839 * would otherwise execute, if one is immediately available,
1840 * and then retries execution of task r, unless the executor
1841 * is shut down, in which case task r is instead discarded.
1842 * @param r the runnable task requested to be executed
1843 * @param e the executor attempting to execute this task
1844 */
1845 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1846 if (!e.isShutdown()) {
1847 e.getQueue().poll();
1848 e.execute(r);
1849 }
1850 }
1851 }
1852 }