ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.116
Committed: Tue Jan 30 03:43:07 2007 UTC (17 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.115: +189 -180 lines
Log Message:
TPE/STPE review rework

File Contents

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