ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.168
Committed: Sun Feb 19 00:31:33 2017 UTC (7 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.167: +9 -18 lines
Log Message:
remove no-longer-useful style spec for javadoc <dd> tags

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