ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.171
Committed: Wed Mar 22 20:22:57 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.170: +1 -2 lines
Log Message:
whitespace

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