ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.163
Committed: Mon Sep 14 20:06:57 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.162: +18 -9 lines
Log Message:
Workaround JDK-8072052:<dd> part of <dl> list in javadoc should not be in monospace font

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