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