ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.180
Committed: Tue Sep 12 21:38:35 2017 UTC (6 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.179: +12 -8 lines
Log Message:
rename CAPACITY to COUNT_MASK; clarify effective pool size limits

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