ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.197
Committed: Wed Dec 9 22:05:21 2020 UTC (3 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.196: +5 -3 lines
Log Message:
DiscardOldestPolicy code snippet: fix compile error pointed out by prappo

File Contents

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