ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.189
Committed: Fri Feb 9 00:03:28 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.188: +3 -8 lines
Log Message:
finalize finalize() javadoc agreed on in JDK-8195862

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