ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.184
Committed: Wed Jan 17 00:32:55 2018 UTC (6 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.183: +5 -39 lines
Log Message:
Remove finalize

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