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/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
import java.util.concurrent.locks.*; |
9 |
import java.util.*; |
10 |
|
11 |
/** |
12 |
* An {@link ExecutorService} that executes each submitted task using |
13 |
* one of possibly several pooled threads, normally configured |
14 |
* using {@link Executors} factory methods. |
15 |
* |
16 |
* <p>Thread pools address two different problems: they usually |
17 |
* provide improved performance when executing large numbers of |
18 |
* asynchronous tasks, due to reduced per-task invocation overhead, |
19 |
* and they provide a means of bounding and managing the resources, |
20 |
* including threads, consumed when executing a collection of tasks. |
21 |
* Each <tt>ThreadPoolExecutor</tt> also maintains some basic |
22 |
* statistics, such as the number of completed tasks. |
23 |
* |
24 |
* <p>To be useful across a wide range of contexts, this class |
25 |
* provides many adjustable parameters and extensibility |
26 |
* hooks. However, programmers are urged to use the more convenient |
27 |
* {@link Executors} factory methods {@link |
28 |
* Executors#newCachedThreadPool} (unbounded thread pool, with |
29 |
* automatic thread reclamation), {@link Executors#newFixedThreadPool} |
30 |
* (fixed size thread pool) and {@link |
31 |
* Executors#newSingleThreadExecutor} (single background thread), that |
32 |
* preconfigure settings for the most common usage |
33 |
* scenarios. Otherwise, use the following guide when manually |
34 |
* configuring and tuning this class: |
35 |
* |
36 |
* <dl> |
37 |
* |
38 |
* <dt>Core and maximum pool sizes</dt> |
39 |
* |
40 |
* <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the |
41 |
* pool size |
42 |
* (see {@link ThreadPoolExecutor#getPoolSize}) |
43 |
* according to the bounds set by corePoolSize |
44 |
* (see {@link ThreadPoolExecutor#getCorePoolSize}) |
45 |
* and |
46 |
* maximumPoolSize |
47 |
* (see {@link ThreadPoolExecutor#getMaximumPoolSize}). |
48 |
* When a new task is submitted in method {@link |
49 |
* ThreadPoolExecutor#execute}, and fewer than corePoolSize threads |
50 |
* are running, a new thread is created to handle the request, even if |
51 |
* other worker threads are idle. If there are more than |
52 |
* corePoolSize but less than maximumPoolSize threads running, a new |
53 |
* thread will be created only if the queue is full. By setting |
54 |
* corePoolSize and maximumPoolSize the same, you create a fixed-size |
55 |
* thread pool. By setting maximumPoolSize to an essentially unbounded |
56 |
* value such as <tt>Integer.MAX_VALUE</tt>, you allow the pool to |
57 |
* accommodate an arbitrary number of concurrent tasks. Most typically, |
58 |
* core and maximum pool sizes are set only upon construction, but they |
59 |
* may also be changed dynamically using {@link |
60 |
* ThreadPoolExecutor#setCorePoolSize} and {@link |
61 |
* ThreadPoolExecutor#setMaximumPoolSize}. <dd> |
62 |
* |
63 |
* <dt> On-demand construction |
64 |
* |
65 |
* <dd> By default, even core threads are initially created and |
66 |
* started only when new tasks arrive, but this can be overridden |
67 |
* dynamically using method {@link |
68 |
* ThreadPoolExecutor#prestartCoreThread} or |
69 |
* {@link ThreadPoolExecutor#prestartAllCoreThreads}. |
70 |
* You probably want to prestart threads if you construct the |
71 |
* pool with a non-empty queue. </dd> |
72 |
* |
73 |
* <dt>Creating new threads</dt> |
74 |
* |
75 |
* <dd>New threads are created using a {@link |
76 |
* java.util.concurrent.ThreadFactory}. If not otherwise specified, a |
77 |
* {@link Executors#defaultThreadFactory} is used, that creates threads to all |
78 |
* be in the same {@link ThreadGroup} and with the same |
79 |
* <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying |
80 |
* a different ThreadFactory, you can alter the thread's name, thread |
81 |
* group, priority, daemon status, etc. If a <tt>ThreadFactory</tt> fails to create |
82 |
* a thread when asked by returning null from <tt>newThread</tt>, |
83 |
* the executor will continue, but might |
84 |
* not be able to execute any tasks. </dd> |
85 |
* |
86 |
* <dt>Keep-alive times</dt> |
87 |
* |
88 |
* <dd>If the pool currently has more than corePoolSize threads, |
89 |
* excess threads will be terminated if they have been idle for more |
90 |
* than the keepAliveTime (see {@link |
91 |
* ThreadPoolExecutor#getKeepAliveTime}). This provides a means of |
92 |
* reducing resource consumption when the pool is not being actively |
93 |
* used. If the pool becomes more active later, new threads will be |
94 |
* constructed. This parameter can also be changed dynamically using |
95 |
* method {@link ThreadPoolExecutor#setKeepAliveTime}. Using a value |
96 |
* of <tt>Long.MAX_VALUE</tt> {@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 |
* than corePoolSizeThreads. But method {@link |
100 |
* ThreadPoolExecutor#allowCoreThreadTimeOut} can be used to apply |
101 |
* this time-out policy to core threads as well, so long as |
102 |
* the 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 |
172 |
* ThreadPoolExecutor#execute} will be <em>rejected</em> when the |
173 |
* Executor has been shut down, and also when the Executor uses finite |
174 |
* bounds for both maximum threads and work queue capacity, and is |
175 |
* saturated. In either case, the <tt>execute</tt> method invokes the |
176 |
* {@link RejectedExecutionHandler#rejectedExecution} method of its |
177 |
* {@link RejectedExecutionHandler}. Four predefined handler policies |
178 |
* are provided: |
179 |
* |
180 |
* <ol> |
181 |
* |
182 |
* <li> In the |
183 |
* default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a |
184 |
* runtime {@link RejectedExecutionException} upon rejection. </li> |
185 |
* |
186 |
* <li> In {@link |
187 |
* ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes |
188 |
* <tt>execute</tt> itself runs the task. This provides a simple |
189 |
* feedback control mechanism that will slow down the rate that new |
190 |
* tasks are submitted. </li> |
191 |
* |
192 |
* <li> In {@link ThreadPoolExecutor.DiscardPolicy}, |
193 |
* a task that cannot be executed is simply dropped. </li> |
194 |
* |
195 |
* <li>In {@link |
196 |
* ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not |
197 |
* shut down, the task at the head of the work queue is dropped, and |
198 |
* then execution is retried (which can fail again, causing this to be |
199 |
* repeated.) </li> |
200 |
* |
201 |
* </ol> |
202 |
* |
203 |
* It is possible to define and use other kinds of {@link |
204 |
* RejectedExecutionHandler} classes. Doing so requires some care |
205 |
* especially when policies are designed to work only under particular |
206 |
* capacity or queuing policies. </dd> |
207 |
* |
208 |
* <dt>Hook methods</dt> |
209 |
* |
210 |
* <dd>This class provides <tt>protected</tt> overridable {@link |
211 |
* ThreadPoolExecutor#beforeExecute} and {@link |
212 |
* ThreadPoolExecutor#afterExecute} methods that are called before and |
213 |
* after execution of each task. These can be used to manipulate the |
214 |
* execution environment; for example, reinitializing ThreadLocals, |
215 |
* gathering statistics, or adding log entries. Additionally, method |
216 |
* {@link ThreadPoolExecutor#terminated} can be overridden to perform |
217 |
* any special processing that needs to be done once the Executor has |
218 |
* fully terminated. |
219 |
* |
220 |
* <p>If hook or callback methods throw |
221 |
* exceptions, internal worker threads may in turn fail and |
222 |
* abruptly terminate.</dd> |
223 |
* |
224 |
* <dt>Queue maintenance</dt> |
225 |
* |
226 |
* <dd> Method {@link ThreadPoolExecutor#getQueue} allows access to |
227 |
* the work queue for purposes of monitoring and debugging. Use of |
228 |
* this method for any other purpose is strongly discouraged. Two |
229 |
* supplied methods, {@link ThreadPoolExecutor#remove} and {@link |
230 |
* ThreadPoolExecutor#purge} are available to assist in storage |
231 |
* reclamation when large numbers of queued tasks become |
232 |
* cancelled.</dd> </dl> |
233 |
* |
234 |
* <p> <b>Extension example</b>. Most extensions of this class |
235 |
* override one or more of the protected hook methods. For example, |
236 |
* here is a subclass that adds a simple pause/resume feature: |
237 |
* |
238 |
* <pre> |
239 |
* class PausableThreadPoolExecutor extends ThreadPoolExecutor { |
240 |
* private boolean isPaused; |
241 |
* private ReentrantLock pauseLock = new ReentrantLock(); |
242 |
* private Condition unpaused = pauseLock.newCondition(); |
243 |
* |
244 |
* public PausableThreadPoolExecutor(...) { super(...); } |
245 |
* |
246 |
* protected void beforeExecute(Thread t, Runnable r) { |
247 |
* super.beforeExecute(t, r); |
248 |
* pauseLock.lock(); |
249 |
* try { |
250 |
* while (isPaused) unpaused.await(); |
251 |
* } catch (InterruptedException ie) { |
252 |
* t.interrupt(); |
253 |
* } finally { |
254 |
* pauseLock.unlock(); |
255 |
* } |
256 |
* } |
257 |
* |
258 |
* public void pause() { |
259 |
* pauseLock.lock(); |
260 |
* try { |
261 |
* isPaused = true; |
262 |
* } finally { |
263 |
* pauseLock.unlock(); |
264 |
* } |
265 |
* } |
266 |
* |
267 |
* public void resume() { |
268 |
* pauseLock.lock(); |
269 |
* try { |
270 |
* isPaused = false; |
271 |
* unpaused.signalAll(); |
272 |
* } finally { |
273 |
* pauseLock.unlock(); |
274 |
* } |
275 |
* } |
276 |
* } |
277 |
* </pre> |
278 |
* @since 1.5 |
279 |
* @author Doug Lea |
280 |
*/ |
281 |
public class ThreadPoolExecutor extends AbstractExecutorService { |
282 |
/** |
283 |
* Only used to force toArray() to produce a Runnable[]. |
284 |
*/ |
285 |
private static final Runnable[] EMPTY_RUNNABLE_ARRAY = new Runnable[0]; |
286 |
|
287 |
/** |
288 |
* Permission for checking shutdown |
289 |
*/ |
290 |
private static final RuntimePermission shutdownPerm = |
291 |
new RuntimePermission("modifyThread"); |
292 |
|
293 |
/** |
294 |
* Queue used for holding tasks and handing off to worker threads. |
295 |
*/ |
296 |
private final BlockingQueue<Runnable> workQueue; |
297 |
|
298 |
/** |
299 |
* Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and |
300 |
* workers set. |
301 |
*/ |
302 |
private final ReentrantLock mainLock = new ReentrantLock(); |
303 |
|
304 |
/** |
305 |
* Wait condition to support awaitTermination |
306 |
*/ |
307 |
private final Condition termination = mainLock.newCondition(); |
308 |
|
309 |
/** |
310 |
* Set containing all worker threads in pool. |
311 |
*/ |
312 |
private final HashSet<Worker> workers = new HashSet<Worker>(); |
313 |
|
314 |
/** |
315 |
* Timeout in nanoseconds for idle threads waiting for work. |
316 |
* Threads use this timeout only when there are more than |
317 |
* corePoolSize present. Otherwise they wait forever for new work. |
318 |
*/ |
319 |
private volatile long keepAliveTime; |
320 |
|
321 |
/** |
322 |
* If false (default) core threads stay alive even when idle. |
323 |
* If true, core threads use keepAliveTime to time out waiting for work. |
324 |
*/ |
325 |
private boolean allowCoreThreadTimeOut; |
326 |
|
327 |
/** |
328 |
* Core pool size, updated only while holding mainLock, |
329 |
* but volatile to allow concurrent readability even |
330 |
* during updates. |
331 |
*/ |
332 |
private volatile int corePoolSize; |
333 |
|
334 |
/** |
335 |
* Maximum pool size, updated only while holding mainLock |
336 |
* but volatile to allow concurrent readability even |
337 |
* during updates. |
338 |
*/ |
339 |
private volatile int maximumPoolSize; |
340 |
|
341 |
/** |
342 |
* Current pool size, updated only while holding mainLock |
343 |
* but volatile to allow concurrent readability even |
344 |
* during updates. |
345 |
*/ |
346 |
private volatile int poolSize; |
347 |
|
348 |
/** |
349 |
* Lifecycle state |
350 |
*/ |
351 |
volatile int runState; |
352 |
|
353 |
// Special values for runState |
354 |
/** Normal, not-shutdown mode */ |
355 |
static final int RUNNING = 0; |
356 |
/** Controlled shutdown mode */ |
357 |
static final int SHUTDOWN = 1; |
358 |
/** Immediate shutdown mode */ |
359 |
static final int STOP = 2; |
360 |
/** Final state */ |
361 |
static final int TERMINATED = 3; |
362 |
|
363 |
/** |
364 |
* Handler called when saturated or shutdown in execute. |
365 |
*/ |
366 |
private volatile RejectedExecutionHandler handler; |
367 |
|
368 |
/** |
369 |
* Factory for new threads. |
370 |
*/ |
371 |
private volatile ThreadFactory threadFactory; |
372 |
|
373 |
/** |
374 |
* Tracks largest attained pool size. |
375 |
*/ |
376 |
private int largestPoolSize; |
377 |
|
378 |
/** |
379 |
* Counter for completed tasks. Updated only on termination of |
380 |
* worker threads. |
381 |
*/ |
382 |
private long completedTaskCount; |
383 |
|
384 |
/** |
385 |
* The default rejected execution handler |
386 |
*/ |
387 |
private static final RejectedExecutionHandler defaultHandler = |
388 |
new AbortPolicy(); |
389 |
|
390 |
/** |
391 |
* Invokes the rejected execution handler for the given command. |
392 |
*/ |
393 |
void reject(Runnable command) { |
394 |
handler.rejectedExecution(command, this); |
395 |
} |
396 |
|
397 |
/** |
398 |
* Creates and returns a new thread running firstTask as its first |
399 |
* task. Call only while holding mainLock. |
400 |
* @param firstTask the task the new thread should run first (or |
401 |
* null if none) |
402 |
* @return the new thread, or null if threadFactory fails to create thread |
403 |
*/ |
404 |
private Thread addThread(Runnable firstTask) { |
405 |
Worker w = new Worker(firstTask); |
406 |
Thread t = threadFactory.newThread(w); |
407 |
if (t != null) { |
408 |
w.thread = t; |
409 |
workers.add(w); |
410 |
int nt = ++poolSize; |
411 |
if (nt > largestPoolSize) |
412 |
largestPoolSize = nt; |
413 |
} |
414 |
return t; |
415 |
} |
416 |
|
417 |
/** |
418 |
* Creates and starts a new thread running firstTask as its first |
419 |
* task, only if fewer than corePoolSize threads are running. |
420 |
* @param firstTask the task the new thread should run first (or |
421 |
* null if none) |
422 |
* @return true if successful. |
423 |
*/ |
424 |
private boolean addIfUnderCorePoolSize(Runnable firstTask) { |
425 |
Thread t = null; |
426 |
final ReentrantLock mainLock = this.mainLock; |
427 |
mainLock.lock(); |
428 |
try { |
429 |
if (poolSize < corePoolSize) |
430 |
t = addThread(firstTask); |
431 |
} finally { |
432 |
mainLock.unlock(); |
433 |
} |
434 |
if (t == null) |
435 |
return false; |
436 |
t.start(); |
437 |
return true; |
438 |
} |
439 |
|
440 |
/** |
441 |
* Creates and starts a new thread only if fewer than maximumPoolSize |
442 |
* threads are running. The new thread runs as its first task the |
443 |
* next task in queue, or if there is none, the given task. |
444 |
* @param firstTask the task the new thread should run first (or |
445 |
* null if none) |
446 |
* @return null on failure, else the first task to be run by new thread. |
447 |
*/ |
448 |
private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) { |
449 |
Thread t = null; |
450 |
Runnable next = null; |
451 |
final ReentrantLock mainLock = this.mainLock; |
452 |
mainLock.lock(); |
453 |
try { |
454 |
if (poolSize < maximumPoolSize) { |
455 |
next = workQueue.poll(); |
456 |
if (next == null) |
457 |
next = firstTask; |
458 |
t = addThread(next); |
459 |
} |
460 |
} finally { |
461 |
mainLock.unlock(); |
462 |
} |
463 |
if (t == null) |
464 |
return null; |
465 |
t.start(); |
466 |
return next; |
467 |
} |
468 |
|
469 |
|
470 |
/** |
471 |
* Gets the next task for a worker thread to run. |
472 |
* @return the task |
473 |
*/ |
474 |
Runnable getTask() { |
475 |
for (;;) { |
476 |
try { |
477 |
switch(runState) { |
478 |
case RUNNING: { |
479 |
// untimed wait if core and not allowing core timeout |
480 |
if (poolSize <= corePoolSize && !allowCoreThreadTimeOut) |
481 |
return workQueue.take(); |
482 |
|
483 |
long timeout = keepAliveTime; |
484 |
if (timeout <= 0) // die immediately for 0 timeout |
485 |
return null; |
486 |
Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS); |
487 |
if (r != null) |
488 |
return r; |
489 |
if (poolSize > corePoolSize || allowCoreThreadTimeOut) |
490 |
return null; // timed out |
491 |
// Else, after timeout, the pool shrank. Retry |
492 |
break; |
493 |
} |
494 |
|
495 |
case SHUTDOWN: { |
496 |
// Help drain queue |
497 |
Runnable r = workQueue.poll(); |
498 |
if (r != null) |
499 |
return r; |
500 |
|
501 |
// Check if can terminate |
502 |
if (workQueue.isEmpty()) { |
503 |
interruptIdleWorkers(); |
504 |
return null; |
505 |
} |
506 |
|
507 |
// Else there could still be delayed tasks in queue. |
508 |
return workQueue.take(); |
509 |
} |
510 |
|
511 |
case STOP: |
512 |
return null; |
513 |
default: |
514 |
assert false; |
515 |
} |
516 |
} catch (InterruptedException ie) { |
517 |
// On interruption, re-check runstate |
518 |
} |
519 |
} |
520 |
} |
521 |
|
522 |
/** |
523 |
* Wakes up all threads that might be waiting for tasks. |
524 |
*/ |
525 |
void interruptIdleWorkers() { |
526 |
final ReentrantLock mainLock = this.mainLock; |
527 |
mainLock.lock(); |
528 |
try { |
529 |
for (Worker w : workers) |
530 |
w.interruptIfIdle(); |
531 |
} finally { |
532 |
mainLock.unlock(); |
533 |
} |
534 |
} |
535 |
|
536 |
/** |
537 |
* Performs bookkeeping for a terminated worker thread. |
538 |
* @param w the worker |
539 |
*/ |
540 |
void workerDone(Worker w) { |
541 |
final ReentrantLock mainLock = this.mainLock; |
542 |
mainLock.lock(); |
543 |
try { |
544 |
completedTaskCount += w.completedTasks; |
545 |
workers.remove(w); |
546 |
if (--poolSize > 0) |
547 |
return; |
548 |
|
549 |
// Else, this is the last thread. Deal with potential shutdown. |
550 |
|
551 |
int state = runState; |
552 |
assert state != TERMINATED; |
553 |
|
554 |
if (state != STOP) { |
555 |
// If there are queued tasks but no threads, create |
556 |
// replacement thread. We must create it initially |
557 |
// idle to avoid orphaned tasks in case addThread |
558 |
// fails. This also handles case of delayed tasks |
559 |
// that will sometime later become runnable. |
560 |
if (!workQueue.isEmpty()) { |
561 |
Thread t = addThread(null); |
562 |
if (t != null) |
563 |
t.start(); |
564 |
return; |
565 |
} |
566 |
|
567 |
// Otherwise, we can exit without replacement |
568 |
if (state == RUNNING) |
569 |
return; |
570 |
} |
571 |
|
572 |
// Either state is STOP, or state is SHUTDOWN and there is |
573 |
// no work to do. So we can terminate. |
574 |
termination.signalAll(); |
575 |
runState = TERMINATED; |
576 |
// fall through to call terminate() outside of lock. |
577 |
} finally { |
578 |
mainLock.unlock(); |
579 |
} |
580 |
|
581 |
assert runState == TERMINATED; |
582 |
terminated(); |
583 |
} |
584 |
|
585 |
/** |
586 |
* Worker threads |
587 |
*/ |
588 |
private class Worker implements Runnable { |
589 |
|
590 |
/** |
591 |
* The runLock is acquired and released surrounding each task |
592 |
* execution. It mainly protects against interrupts that are |
593 |
* intended to cancel the worker thread from instead |
594 |
* interrupting the task being run. |
595 |
*/ |
596 |
private final ReentrantLock runLock = new ReentrantLock(); |
597 |
|
598 |
/** |
599 |
* Initial task to run before entering run loop |
600 |
*/ |
601 |
private Runnable firstTask; |
602 |
|
603 |
/** |
604 |
* Per thread completed task counter; accumulated |
605 |
* into completedTaskCount upon termination. |
606 |
*/ |
607 |
volatile long completedTasks; |
608 |
|
609 |
/** |
610 |
* Thread this worker is running in. Acts as a final field, |
611 |
* but cannot be set until thread is created. |
612 |
*/ |
613 |
Thread thread; |
614 |
|
615 |
Worker(Runnable firstTask) { |
616 |
this.firstTask = firstTask; |
617 |
} |
618 |
|
619 |
boolean isActive() { |
620 |
return runLock.isLocked(); |
621 |
} |
622 |
|
623 |
/** |
624 |
* Interrupt thread if not running a task |
625 |
*/ |
626 |
void interruptIfIdle() { |
627 |
final ReentrantLock runLock = this.runLock; |
628 |
if (runLock.tryLock()) { |
629 |
try { |
630 |
thread.interrupt(); |
631 |
} finally { |
632 |
runLock.unlock(); |
633 |
} |
634 |
} |
635 |
} |
636 |
|
637 |
/** |
638 |
* Interrupt thread even if running a task. |
639 |
*/ |
640 |
void interruptNow() { |
641 |
thread.interrupt(); |
642 |
} |
643 |
|
644 |
/** |
645 |
* Run a single task between before/after methods. |
646 |
*/ |
647 |
private void runTask(Runnable task) { |
648 |
final ReentrantLock runLock = this.runLock; |
649 |
runLock.lock(); |
650 |
try { |
651 |
Thread.interrupted(); // clear interrupt status on entry |
652 |
// Abort now if immediate cancel. Otherwise, we have |
653 |
// committed to run this task. |
654 |
if (runState == STOP) |
655 |
return; |
656 |
|
657 |
boolean ran = false; |
658 |
beforeExecute(thread, task); |
659 |
try { |
660 |
task.run(); |
661 |
ran = true; |
662 |
afterExecute(task, null); |
663 |
++completedTasks; |
664 |
} catch (RuntimeException ex) { |
665 |
if (!ran) |
666 |
afterExecute(task, ex); |
667 |
// Else the exception occurred within |
668 |
// afterExecute itself in which case we don't |
669 |
// want to call it again. |
670 |
throw ex; |
671 |
} |
672 |
} finally { |
673 |
runLock.unlock(); |
674 |
} |
675 |
} |
676 |
|
677 |
/** |
678 |
* Main run loop |
679 |
*/ |
680 |
public void run() { |
681 |
try { |
682 |
Runnable task = firstTask; |
683 |
firstTask = null; |
684 |
while (task != null || (task = getTask()) != null) { |
685 |
runTask(task); |
686 |
task = null; // unnecessary but can help GC |
687 |
} |
688 |
} finally { |
689 |
workerDone(this); |
690 |
} |
691 |
} |
692 |
} |
693 |
|
694 |
// Public methods |
695 |
|
696 |
/** |
697 |
* Creates a new <tt>ThreadPoolExecutor</tt> with the given initial |
698 |
* parameters and default thread factory and rejected execution handler. |
699 |
* It may be more convenient to use one of the {@link Executors} factory |
700 |
* methods instead of this general purpose constructor. |
701 |
* |
702 |
* @param corePoolSize the number of threads to keep in the |
703 |
* pool, even if they are idle. |
704 |
* @param maximumPoolSize the maximum number of threads to allow in the |
705 |
* pool. |
706 |
* @param keepAliveTime when the number of threads is greater than |
707 |
* the core, this is the maximum time that excess idle threads |
708 |
* will wait for new tasks before terminating. |
709 |
* @param unit the time unit for the keepAliveTime |
710 |
* argument. |
711 |
* @param workQueue the queue to use for holding tasks before they |
712 |
* are executed. This queue will hold only the <tt>Runnable</tt> |
713 |
* tasks submitted by the <tt>execute</tt> method. |
714 |
* @throws IllegalArgumentException if corePoolSize, or |
715 |
* keepAliveTime less than zero, or if maximumPoolSize less than or |
716 |
* equal to zero, or if corePoolSize greater than maximumPoolSize. |
717 |
* @throws NullPointerException if <tt>workQueue</tt> is null |
718 |
*/ |
719 |
public ThreadPoolExecutor(int corePoolSize, |
720 |
int maximumPoolSize, |
721 |
long keepAliveTime, |
722 |
TimeUnit unit, |
723 |
BlockingQueue<Runnable> workQueue) { |
724 |
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, |
725 |
Executors.defaultThreadFactory(), defaultHandler); |
726 |
} |
727 |
|
728 |
/** |
729 |
* Creates a new <tt>ThreadPoolExecutor</tt> with the given initial |
730 |
* parameters and default rejected execution handler. |
731 |
* |
732 |
* @param corePoolSize the number of threads to keep in the |
733 |
* pool, even if they are idle. |
734 |
* @param maximumPoolSize the maximum number of threads to allow in the |
735 |
* pool. |
736 |
* @param keepAliveTime when the number of threads is greater than |
737 |
* the core, this is the maximum time that excess idle threads |
738 |
* will wait for new tasks before terminating. |
739 |
* @param unit the time unit for the keepAliveTime |
740 |
* argument. |
741 |
* @param workQueue the queue to use for holding tasks before they |
742 |
* are executed. This queue will hold only the <tt>Runnable</tt> |
743 |
* tasks submitted by the <tt>execute</tt> method. |
744 |
* @param threadFactory the factory to use when the executor |
745 |
* creates a new thread. |
746 |
* @throws IllegalArgumentException if corePoolSize, or |
747 |
* keepAliveTime less than zero, or if maximumPoolSize less than or |
748 |
* equal to zero, or if corePoolSize greater than maximumPoolSize. |
749 |
* @throws NullPointerException if <tt>workQueue</tt> |
750 |
* or <tt>threadFactory</tt> are null. |
751 |
*/ |
752 |
public ThreadPoolExecutor(int corePoolSize, |
753 |
int maximumPoolSize, |
754 |
long keepAliveTime, |
755 |
TimeUnit unit, |
756 |
BlockingQueue<Runnable> workQueue, |
757 |
ThreadFactory threadFactory) { |
758 |
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, |
759 |
threadFactory, defaultHandler); |
760 |
} |
761 |
|
762 |
/** |
763 |
* Creates a new <tt>ThreadPoolExecutor</tt> with the given initial |
764 |
* parameters and default thread factory. |
765 |
* |
766 |
* @param corePoolSize the number of threads to keep in the |
767 |
* pool, even if they are idle. |
768 |
* @param maximumPoolSize the maximum number of threads to allow in the |
769 |
* pool. |
770 |
* @param keepAliveTime when the number of threads is greater than |
771 |
* the core, this is the maximum time that excess idle threads |
772 |
* will wait for new tasks before terminating. |
773 |
* @param unit the time unit for the keepAliveTime |
774 |
* argument. |
775 |
* @param workQueue the queue to use for holding tasks before they |
776 |
* are executed. This queue will hold only the <tt>Runnable</tt> |
777 |
* tasks submitted by the <tt>execute</tt> method. |
778 |
* @param handler the handler to use when execution is blocked |
779 |
* because the thread bounds and queue capacities are reached. |
780 |
* @throws IllegalArgumentException if corePoolSize, or |
781 |
* keepAliveTime less than zero, or if maximumPoolSize less than or |
782 |
* equal to zero, or if corePoolSize greater than maximumPoolSize. |
783 |
* @throws NullPointerException if <tt>workQueue</tt> |
784 |
* or <tt>handler</tt> are null. |
785 |
*/ |
786 |
public ThreadPoolExecutor(int corePoolSize, |
787 |
int maximumPoolSize, |
788 |
long keepAliveTime, |
789 |
TimeUnit unit, |
790 |
BlockingQueue<Runnable> workQueue, |
791 |
RejectedExecutionHandler handler) { |
792 |
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, |
793 |
Executors.defaultThreadFactory(), handler); |
794 |
} |
795 |
|
796 |
/** |
797 |
* Creates a new <tt>ThreadPoolExecutor</tt> with the given initial |
798 |
* parameters. |
799 |
* |
800 |
* @param corePoolSize the number of threads to keep in the |
801 |
* pool, even if they are idle. |
802 |
* @param maximumPoolSize the maximum number of threads to allow in the |
803 |
* pool. |
804 |
* @param keepAliveTime when the number of threads is greater than |
805 |
* the core, this is the maximum time that excess idle threads |
806 |
* will wait for new tasks before terminating. |
807 |
* @param unit the time unit for the keepAliveTime |
808 |
* argument. |
809 |
* @param workQueue the queue to use for holding tasks before they |
810 |
* are executed. This queue will hold only the <tt>Runnable</tt> |
811 |
* tasks submitted by the <tt>execute</tt> method. |
812 |
* @param threadFactory the factory to use when the executor |
813 |
* creates a new thread. |
814 |
* @param handler the handler to use when execution is blocked |
815 |
* because the thread bounds and queue capacities are reached. |
816 |
* @throws IllegalArgumentException if corePoolSize, or |
817 |
* keepAliveTime less than zero, or if maximumPoolSize less than or |
818 |
* equal to zero, or if corePoolSize greater than maximumPoolSize. |
819 |
* @throws NullPointerException if <tt>workQueue</tt> |
820 |
* or <tt>threadFactory</tt> or <tt>handler</tt> are null. |
821 |
*/ |
822 |
public ThreadPoolExecutor(int corePoolSize, |
823 |
int maximumPoolSize, |
824 |
long keepAliveTime, |
825 |
TimeUnit unit, |
826 |
BlockingQueue<Runnable> workQueue, |
827 |
ThreadFactory threadFactory, |
828 |
RejectedExecutionHandler handler) { |
829 |
if (corePoolSize < 0 || |
830 |
maximumPoolSize <= 0 || |
831 |
maximumPoolSize < corePoolSize || |
832 |
keepAliveTime < 0) |
833 |
throw new IllegalArgumentException(); |
834 |
if (workQueue == null || threadFactory == null || handler == null) |
835 |
throw new NullPointerException(); |
836 |
this.corePoolSize = corePoolSize; |
837 |
this.maximumPoolSize = maximumPoolSize; |
838 |
this.workQueue = workQueue; |
839 |
this.keepAliveTime = unit.toNanos(keepAliveTime); |
840 |
this.threadFactory = threadFactory; |
841 |
this.handler = handler; |
842 |
} |
843 |
|
844 |
|
845 |
/** |
846 |
* Executes the given task sometime in the future. The task |
847 |
* may execute in a new thread or in an existing pooled thread. |
848 |
* |
849 |
* If the task cannot be submitted for execution, either because this |
850 |
* executor has been shutdown or because its capacity has been reached, |
851 |
* the task is handled by the current <tt>RejectedExecutionHandler</tt>. |
852 |
* |
853 |
* @param command the task to execute |
854 |
* @throws RejectedExecutionException at discretion of |
855 |
* <tt>RejectedExecutionHandler</tt>, if task cannot be accepted |
856 |
* for execution |
857 |
* @throws NullPointerException if command is null |
858 |
*/ |
859 |
public void execute(Runnable command) { |
860 |
if (command == null) |
861 |
throw new NullPointerException(); |
862 |
for (;;) { |
863 |
if (runState != RUNNING) { |
864 |
reject(command); |
865 |
return; |
866 |
} |
867 |
if (poolSize < corePoolSize && addIfUnderCorePoolSize(command)) |
868 |
return; |
869 |
if (workQueue.offer(command)) |
870 |
return; |
871 |
Runnable r = addIfUnderMaximumPoolSize(command); |
872 |
if (r == command) |
873 |
return; |
874 |
if (r == null) { |
875 |
reject(command); |
876 |
return; |
877 |
} |
878 |
// else retry |
879 |
} |
880 |
} |
881 |
|
882 |
/** |
883 |
* Initiates an orderly shutdown in which previously submitted |
884 |
* tasks are executed, but no new tasks will be |
885 |
* accepted. Invocation has no additional effect if already shut |
886 |
* down. |
887 |
* @throws SecurityException if a security manager exists and |
888 |
* shutting down this ExecutorService may manipulate threads that |
889 |
* the caller is not permitted to modify because it does not hold |
890 |
* {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>, |
891 |
* or the security manager's <tt>checkAccess</tt> method denies access. |
892 |
*/ |
893 |
public void shutdown() { |
894 |
// Fail if caller doesn't have modifyThread permission. We |
895 |
// explicitly check permissions directly because we can't trust |
896 |
// implementations of SecurityManager to correctly override |
897 |
// the "check access" methods such that our documented |
898 |
// security policy is implemented. |
899 |
SecurityManager security = System.getSecurityManager(); |
900 |
if (security != null) |
901 |
java.security.AccessController.checkPermission(shutdownPerm); |
902 |
|
903 |
boolean fullyTerminated = false; |
904 |
final ReentrantLock mainLock = this.mainLock; |
905 |
mainLock.lock(); |
906 |
try { |
907 |
if (workers.size() > 0) { |
908 |
// Check if caller can modify worker threads. This |
909 |
// might not be true even if passed above check, if |
910 |
// the SecurityManager treats some threads specially. |
911 |
if (security != null) { |
912 |
for (Worker w: workers) |
913 |
security.checkAccess(w.thread); |
914 |
} |
915 |
|
916 |
int state = runState; |
917 |
if (state == RUNNING) // don't override shutdownNow |
918 |
runState = SHUTDOWN; |
919 |
|
920 |
try { |
921 |
for (Worker w: workers) |
922 |
w.interruptIfIdle(); |
923 |
} catch (SecurityException se) { |
924 |
// If SecurityManager allows above checks, but |
925 |
// then unexpectedly throws exception when |
926 |
// interrupting threads (which it ought not do), |
927 |
// back out as cleanly as we can. Some threads may |
928 |
// have been killed but we remain in non-shutdown |
929 |
// state. |
930 |
runState = state; |
931 |
throw se; |
932 |
} |
933 |
} |
934 |
else { // If no workers, trigger full termination now |
935 |
fullyTerminated = true; |
936 |
runState = TERMINATED; |
937 |
termination.signalAll(); |
938 |
} |
939 |
} finally { |
940 |
mainLock.unlock(); |
941 |
} |
942 |
if (fullyTerminated) |
943 |
terminated(); |
944 |
} |
945 |
|
946 |
|
947 |
/** |
948 |
* Attempts to stop all actively executing tasks, halts the |
949 |
* processing of waiting tasks, and returns a list of the tasks that were |
950 |
* awaiting execution. |
951 |
* |
952 |
* <p>This implementation cancels tasks via {@link |
953 |
* Thread#interrupt}, so if any tasks mask or fail to respond to |
954 |
* interrupts, they may never terminate. |
955 |
* |
956 |
* @return list of tasks that never commenced execution |
957 |
* @throws SecurityException if a security manager exists and |
958 |
* shutting down this ExecutorService may manipulate threads that |
959 |
* the caller is not permitted to modify because it does not hold |
960 |
* {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>, |
961 |
* or the security manager's <tt>checkAccess</tt> method denies access. |
962 |
*/ |
963 |
public List<Runnable> shutdownNow() { |
964 |
// Almost the same code as shutdown() |
965 |
SecurityManager security = System.getSecurityManager(); |
966 |
if (security != null) |
967 |
java.security.AccessController.checkPermission(shutdownPerm); |
968 |
|
969 |
boolean fullyTerminated = false; |
970 |
final ReentrantLock mainLock = this.mainLock; |
971 |
mainLock.lock(); |
972 |
try { |
973 |
if (workers.size() > 0) { |
974 |
if (security != null) { |
975 |
for (Worker w: workers) |
976 |
security.checkAccess(w.thread); |
977 |
} |
978 |
|
979 |
int state = runState; |
980 |
if (state != TERMINATED) |
981 |
runState = STOP; |
982 |
try { |
983 |
for (Worker w : workers) |
984 |
w.interruptNow(); |
985 |
} catch (SecurityException se) { |
986 |
runState = state; // back out; |
987 |
throw se; |
988 |
} |
989 |
} |
990 |
else { // If no workers, trigger full termination now |
991 |
fullyTerminated = true; |
992 |
runState = TERMINATED; |
993 |
termination.signalAll(); |
994 |
} |
995 |
} finally { |
996 |
mainLock.unlock(); |
997 |
} |
998 |
if (fullyTerminated) |
999 |
terminated(); |
1000 |
return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY)); |
1001 |
} |
1002 |
|
1003 |
public boolean isShutdown() { |
1004 |
return runState != RUNNING; |
1005 |
} |
1006 |
|
1007 |
/** |
1008 |
* Returns true if this executor is in the process of terminating |
1009 |
* after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not |
1010 |
* completely terminated. This method may be useful for |
1011 |
* debugging. A return of <tt>true</tt> reported a sufficient |
1012 |
* period after shutdown may indicate that submitted tasks have |
1013 |
* ignored or suppressed interruption, causing this executor not |
1014 |
* to properly terminate. |
1015 |
* @return true if terminating but not yet terminated. |
1016 |
*/ |
1017 |
public boolean isTerminating() { |
1018 |
return runState == STOP; |
1019 |
} |
1020 |
|
1021 |
public boolean isTerminated() { |
1022 |
return runState == TERMINATED; |
1023 |
} |
1024 |
|
1025 |
public boolean awaitTermination(long timeout, TimeUnit unit) |
1026 |
throws InterruptedException { |
1027 |
long nanos = unit.toNanos(timeout); |
1028 |
final ReentrantLock mainLock = this.mainLock; |
1029 |
mainLock.lock(); |
1030 |
try { |
1031 |
for (;;) { |
1032 |
if (runState == TERMINATED) |
1033 |
return true; |
1034 |
if (nanos <= 0) |
1035 |
return false; |
1036 |
nanos = termination.awaitNanos(nanos); |
1037 |
} |
1038 |
} finally { |
1039 |
mainLock.unlock(); |
1040 |
} |
1041 |
} |
1042 |
|
1043 |
/** |
1044 |
* Invokes <tt>shutdown</tt> when this executor is no longer |
1045 |
* referenced. |
1046 |
*/ |
1047 |
protected void finalize() { |
1048 |
shutdown(); |
1049 |
} |
1050 |
|
1051 |
/** |
1052 |
* Sets the thread factory used to create new threads. |
1053 |
* |
1054 |
* @param threadFactory the new thread factory |
1055 |
* @throws NullPointerException if threadFactory is null |
1056 |
* @see #getThreadFactory |
1057 |
*/ |
1058 |
public void setThreadFactory(ThreadFactory threadFactory) { |
1059 |
if (threadFactory == null) |
1060 |
throw new NullPointerException(); |
1061 |
this.threadFactory = threadFactory; |
1062 |
} |
1063 |
|
1064 |
/** |
1065 |
* Returns the thread factory used to create new threads. |
1066 |
* |
1067 |
* @return the current thread factory |
1068 |
* @see #setThreadFactory |
1069 |
*/ |
1070 |
public ThreadFactory getThreadFactory() { |
1071 |
return threadFactory; |
1072 |
} |
1073 |
|
1074 |
/** |
1075 |
* Sets a new handler for unexecutable tasks. |
1076 |
* |
1077 |
* @param handler the new handler |
1078 |
* @throws NullPointerException if handler is null |
1079 |
* @see #getRejectedExecutionHandler |
1080 |
*/ |
1081 |
public void setRejectedExecutionHandler(RejectedExecutionHandler handler) { |
1082 |
if (handler == null) |
1083 |
throw new NullPointerException(); |
1084 |
this.handler = handler; |
1085 |
} |
1086 |
|
1087 |
/** |
1088 |
* Returns the current handler for unexecutable tasks. |
1089 |
* |
1090 |
* @return the current handler |
1091 |
* @see #setRejectedExecutionHandler |
1092 |
*/ |
1093 |
public RejectedExecutionHandler getRejectedExecutionHandler() { |
1094 |
return handler; |
1095 |
} |
1096 |
|
1097 |
/** |
1098 |
* Returns the task queue used by this executor. Access to the |
1099 |
* task queue is intended primarily for debugging and monitoring. |
1100 |
* This queue may be in active use. Retrieving the task queue |
1101 |
* does not prevent queued tasks from executing. |
1102 |
* |
1103 |
* @return the task queue |
1104 |
*/ |
1105 |
public BlockingQueue<Runnable> getQueue() { |
1106 |
return workQueue; |
1107 |
} |
1108 |
|
1109 |
/** |
1110 |
* Removes this task from the executor's internal queue if it is |
1111 |
* present, thus causing it not to be run if it has not already |
1112 |
* started. |
1113 |
* |
1114 |
* <p> This method may be useful as one part of a cancellation |
1115 |
* scheme. It may fail to remove tasks that have been converted |
1116 |
* into other forms before being placed on the internal queue. For |
1117 |
* example, a task entered using <tt>submit</tt> might be |
1118 |
* converted into a form that maintains <tt>Future</tt> status. |
1119 |
* However, in such cases, method {@link ThreadPoolExecutor#purge} |
1120 |
* may be used to remove those Futures that have been cancelled. |
1121 |
* |
1122 |
* |
1123 |
* @param task the task to remove |
1124 |
* @return true if the task was removed |
1125 |
*/ |
1126 |
public boolean remove(Runnable task) { |
1127 |
return getQueue().remove(task); |
1128 |
} |
1129 |
|
1130 |
|
1131 |
/** |
1132 |
* Tries to remove from the work queue all {@link Future} |
1133 |
* tasks that have been cancelled. This method can be useful as a |
1134 |
* storage reclamation operation, that has no other impact on |
1135 |
* functionality. Cancelled tasks are never executed, but may |
1136 |
* accumulate in work queues until worker threads can actively |
1137 |
* remove them. Invoking this method instead tries to remove them now. |
1138 |
* However, this method may fail to remove tasks in |
1139 |
* the presence of interference by other threads. |
1140 |
*/ |
1141 |
public void purge() { |
1142 |
// Fail if we encounter interference during traversal |
1143 |
try { |
1144 |
Iterator<Runnable> it = getQueue().iterator(); |
1145 |
while (it.hasNext()) { |
1146 |
Runnable r = it.next(); |
1147 |
if (r instanceof Future<?>) { |
1148 |
Future<?> c = (Future<?>)r; |
1149 |
if (c.isCancelled()) |
1150 |
it.remove(); |
1151 |
} |
1152 |
} |
1153 |
} |
1154 |
catch (ConcurrentModificationException ex) { |
1155 |
return; |
1156 |
} |
1157 |
} |
1158 |
|
1159 |
/** |
1160 |
* Sets the core number of threads. This overrides any value set |
1161 |
* in the constructor. If the new value is smaller than the |
1162 |
* current value, excess existing threads will be terminated when |
1163 |
* they next become idle. If larger, new threads will, if needed, |
1164 |
* be started to execute any queued tasks. |
1165 |
* |
1166 |
* @param corePoolSize the new core size |
1167 |
* @throws IllegalArgumentException if <tt>corePoolSize</tt> |
1168 |
* less than zero |
1169 |
* @see #getCorePoolSize |
1170 |
*/ |
1171 |
public void setCorePoolSize(int corePoolSize) { |
1172 |
if (corePoolSize < 0) |
1173 |
throw new IllegalArgumentException(); |
1174 |
final ReentrantLock mainLock = this.mainLock; |
1175 |
mainLock.lock(); |
1176 |
try { |
1177 |
int extra = this.corePoolSize - corePoolSize; |
1178 |
this.corePoolSize = corePoolSize; |
1179 |
if (extra < 0) { |
1180 |
int n = workQueue.size(); |
1181 |
// We have to create initially-idle threads here |
1182 |
// because we otherwise have no recourse about |
1183 |
// what to do with a dequeued task if addThread fails. |
1184 |
while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize ) { |
1185 |
Thread t = addThread(null); |
1186 |
if (t != null) |
1187 |
t.start(); |
1188 |
else |
1189 |
break; |
1190 |
} |
1191 |
} |
1192 |
else if (extra > 0 && poolSize > corePoolSize) { |
1193 |
Iterator<Worker> it = workers.iterator(); |
1194 |
while (it.hasNext() && |
1195 |
extra-- > 0 && |
1196 |
poolSize > corePoolSize && |
1197 |
workQueue.remainingCapacity() == 0) |
1198 |
it.next().interruptIfIdle(); |
1199 |
} |
1200 |
} finally { |
1201 |
mainLock.unlock(); |
1202 |
} |
1203 |
} |
1204 |
|
1205 |
/** |
1206 |
* Returns the core number of threads. |
1207 |
* |
1208 |
* @return the core number of threads |
1209 |
* @see #setCorePoolSize |
1210 |
*/ |
1211 |
public int getCorePoolSize() { |
1212 |
return corePoolSize; |
1213 |
} |
1214 |
|
1215 |
/** |
1216 |
* Starts a core thread, causing it to idly wait for work. This |
1217 |
* overrides the default policy of starting core threads only when |
1218 |
* new tasks are executed. This method will return <tt>false</tt> |
1219 |
* if all core threads have already been started. |
1220 |
* @return true if a thread was started |
1221 |
*/ |
1222 |
public boolean prestartCoreThread() { |
1223 |
return addIfUnderCorePoolSize(null); |
1224 |
} |
1225 |
|
1226 |
/** |
1227 |
* Starts all core threads, causing them to idly wait for work. This |
1228 |
* overrides the default policy of starting core threads only when |
1229 |
* new tasks are executed. |
1230 |
* @return the number of threads started. |
1231 |
*/ |
1232 |
public int prestartAllCoreThreads() { |
1233 |
int n = 0; |
1234 |
while (addIfUnderCorePoolSize(null)) |
1235 |
++n; |
1236 |
return n; |
1237 |
} |
1238 |
|
1239 |
/** |
1240 |
* Returns true if this pool allows core threads to time out and |
1241 |
* terminate if no tasks arrive within the keepAlive time, being |
1242 |
* replaced if needed when new tasks arrive. When true, the same |
1243 |
* keep-alive policy applying to non-core threads applies also to |
1244 |
* core threads. When false (the default), core threads are never |
1245 |
* terminated due to lack of incoming tasks. |
1246 |
* @return <tt>true</tt> if core threads are allowed to time out, |
1247 |
* else <tt>false</tt> |
1248 |
*/ |
1249 |
public boolean allowsCoreThreadTimeOut() { |
1250 |
return allowCoreThreadTimeOut; |
1251 |
} |
1252 |
|
1253 |
/** |
1254 |
* Sets the policy governing whether core threads may time out and |
1255 |
* terminate if no tasks arrive within the keep-alive time, being |
1256 |
* replaced if needed when new tasks arrive. When false, core |
1257 |
* threads are never terminated due to lack of incoming |
1258 |
* tasks. When true, the same keep-alive policy applying to |
1259 |
* non-core threads applies also to core threads. To avoid |
1260 |
* continual thread replacement, the keep-alive time must be |
1261 |
* greater than zero when setting <tt>true</tt>. This method |
1262 |
* should in general be called before the pool is actively used. |
1263 |
* @param value <tt>true</tt> if should time out, else <tt>false</tt> |
1264 |
* @throws IllegalArgumentException if value is <tt>true</tt> |
1265 |
* and the current keep-alive time is not greater than zero. |
1266 |
*/ |
1267 |
public void allowCoreThreadTimeOut(boolean value) { |
1268 |
if (value && keepAliveTime <= 0) |
1269 |
throw new IllegalArgumentException("Core threads must have nonzero keep alive times"); |
1270 |
|
1271 |
allowCoreThreadTimeOut = value; |
1272 |
} |
1273 |
|
1274 |
/** |
1275 |
* Sets the maximum allowed number of threads. This overrides any |
1276 |
* value set in the constructor. If the new value is smaller than |
1277 |
* the current value, excess existing threads will be |
1278 |
* terminated when they next become idle. |
1279 |
* |
1280 |
* @param maximumPoolSize the new maximum |
1281 |
* @throws IllegalArgumentException if maximumPoolSize less than zero or |
1282 |
* the {@link #getCorePoolSize core pool size} |
1283 |
* @see #getMaximumPoolSize |
1284 |
*/ |
1285 |
public void setMaximumPoolSize(int maximumPoolSize) { |
1286 |
if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize) |
1287 |
throw new IllegalArgumentException(); |
1288 |
final ReentrantLock mainLock = this.mainLock; |
1289 |
mainLock.lock(); |
1290 |
try { |
1291 |
int extra = this.maximumPoolSize - maximumPoolSize; |
1292 |
this.maximumPoolSize = maximumPoolSize; |
1293 |
if (extra > 0 && poolSize > maximumPoolSize) { |
1294 |
Iterator<Worker> it = workers.iterator(); |
1295 |
while (it.hasNext() && |
1296 |
extra > 0 && |
1297 |
poolSize > maximumPoolSize) { |
1298 |
it.next().interruptIfIdle(); |
1299 |
--extra; |
1300 |
} |
1301 |
} |
1302 |
} finally { |
1303 |
mainLock.unlock(); |
1304 |
} |
1305 |
} |
1306 |
|
1307 |
/** |
1308 |
* Returns the maximum allowed number of threads. |
1309 |
* |
1310 |
* @return the maximum allowed number of threads |
1311 |
* @see #setMaximumPoolSize |
1312 |
*/ |
1313 |
public int getMaximumPoolSize() { |
1314 |
return maximumPoolSize; |
1315 |
} |
1316 |
|
1317 |
/** |
1318 |
* Sets the time limit for which threads may remain idle before |
1319 |
* being terminated. If there are more than the core number of |
1320 |
* threads currently in the pool, after waiting this amount of |
1321 |
* time without processing a task, excess threads will be |
1322 |
* terminated. This overrides any value set in the constructor. |
1323 |
* @param time the time to wait. A time value of zero will cause |
1324 |
* excess threads to terminate immediately after executing tasks. |
1325 |
* @param unit the time unit of the time argument |
1326 |
* @throws IllegalArgumentException if time less than zero or |
1327 |
* if time is zero and allowsCoreThreadTimeOut |
1328 |
* @see #getKeepAliveTime |
1329 |
*/ |
1330 |
public void setKeepAliveTime(long time, TimeUnit unit) { |
1331 |
if (time < 0) |
1332 |
throw new IllegalArgumentException(); |
1333 |
if (time == 0 && allowsCoreThreadTimeOut()) |
1334 |
throw new IllegalArgumentException("Core threads must have nonzero keep alive times"); |
1335 |
this.keepAliveTime = unit.toNanos(time); |
1336 |
} |
1337 |
|
1338 |
/** |
1339 |
* Returns the thread keep-alive time, which is the amount of time |
1340 |
* which threads in excess of the core pool size may remain |
1341 |
* idle before being terminated. |
1342 |
* |
1343 |
* @param unit the desired time unit of the result |
1344 |
* @return the time limit |
1345 |
* @see #setKeepAliveTime |
1346 |
*/ |
1347 |
public long getKeepAliveTime(TimeUnit unit) { |
1348 |
return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS); |
1349 |
} |
1350 |
|
1351 |
/* Statistics */ |
1352 |
|
1353 |
/** |
1354 |
* Returns the current number of threads in the pool. |
1355 |
* |
1356 |
* @return the number of threads |
1357 |
*/ |
1358 |
public int getPoolSize() { |
1359 |
return poolSize; |
1360 |
} |
1361 |
|
1362 |
/** |
1363 |
* Returns the approximate number of threads that are actively |
1364 |
* executing tasks. |
1365 |
* |
1366 |
* @return the number of threads |
1367 |
*/ |
1368 |
public int getActiveCount() { |
1369 |
final ReentrantLock mainLock = this.mainLock; |
1370 |
mainLock.lock(); |
1371 |
try { |
1372 |
int n = 0; |
1373 |
for (Worker w : workers) { |
1374 |
if (w.isActive()) |
1375 |
++n; |
1376 |
} |
1377 |
return n; |
1378 |
} finally { |
1379 |
mainLock.unlock(); |
1380 |
} |
1381 |
} |
1382 |
|
1383 |
/** |
1384 |
* Returns the largest number of threads that have ever |
1385 |
* simultaneously been in the pool. |
1386 |
* |
1387 |
* @return the number of threads |
1388 |
*/ |
1389 |
public int getLargestPoolSize() { |
1390 |
final ReentrantLock mainLock = this.mainLock; |
1391 |
mainLock.lock(); |
1392 |
try { |
1393 |
return largestPoolSize; |
1394 |
} finally { |
1395 |
mainLock.unlock(); |
1396 |
} |
1397 |
} |
1398 |
|
1399 |
/** |
1400 |
* Returns the approximate total number of tasks that have been |
1401 |
* scheduled for execution. Because the states of tasks and |
1402 |
* threads may change dynamically during computation, the returned |
1403 |
* value is only an approximation, but one that does not ever |
1404 |
* decrease across successive calls. |
1405 |
* |
1406 |
* @return the number of tasks |
1407 |
*/ |
1408 |
public long getTaskCount() { |
1409 |
final ReentrantLock mainLock = this.mainLock; |
1410 |
mainLock.lock(); |
1411 |
try { |
1412 |
long n = completedTaskCount; |
1413 |
for (Worker w : workers) { |
1414 |
n += w.completedTasks; |
1415 |
if (w.isActive()) |
1416 |
++n; |
1417 |
} |
1418 |
return n + workQueue.size(); |
1419 |
} finally { |
1420 |
mainLock.unlock(); |
1421 |
} |
1422 |
} |
1423 |
|
1424 |
/** |
1425 |
* Returns the approximate total number of tasks that have |
1426 |
* completed execution. Because the states of tasks and threads |
1427 |
* may change dynamically during computation, the returned value |
1428 |
* is only an approximation, but one that does not ever decrease |
1429 |
* across successive calls. |
1430 |
* |
1431 |
* @return the number of tasks |
1432 |
*/ |
1433 |
public long getCompletedTaskCount() { |
1434 |
final ReentrantLock mainLock = this.mainLock; |
1435 |
mainLock.lock(); |
1436 |
try { |
1437 |
long n = completedTaskCount; |
1438 |
for (Worker w : workers) |
1439 |
n += w.completedTasks; |
1440 |
return n; |
1441 |
} finally { |
1442 |
mainLock.unlock(); |
1443 |
} |
1444 |
} |
1445 |
|
1446 |
/** |
1447 |
* Method invoked prior to executing the given Runnable in the |
1448 |
* given thread. This method is invoked by thread <tt>t</tt> that |
1449 |
* will execute task <tt>r</tt>, and may be used to re-initialize |
1450 |
* ThreadLocals, or to perform logging. This implementation does |
1451 |
* nothing, but may be customized in subclasses. Note: To properly |
1452 |
* nest multiple overridings, subclasses should generally invoke |
1453 |
* <tt>super.beforeExecute</tt> at the end of this method. |
1454 |
* |
1455 |
* @param t the thread that will run task r. |
1456 |
* @param r the task that will be executed. |
1457 |
*/ |
1458 |
protected void beforeExecute(Thread t, Runnable r) { } |
1459 |
|
1460 |
/** |
1461 |
* Method invoked upon completion of execution of the given Runnable. |
1462 |
* This method is invoked by the thread that executed the task. If |
1463 |
* non-null, the Throwable is the uncaught <tt>RuntimeException</tt> |
1464 |
* or <tt>Error</tt> that caused execution to terminate abruptly. |
1465 |
* |
1466 |
* <p><b>Note:</b> When actions are enclosed in tasks (such as |
1467 |
* {@link FutureTask}) either explicitly or via methods such as |
1468 |
* <tt>submit</tt>, these task objects catch and maintain |
1469 |
* computational exceptions, and so they do not cause abrupt |
1470 |
* termination, and the internal exceptions are <em>not</em> |
1471 |
* passed to this method. |
1472 |
* |
1473 |
* <p>This implementation does nothing, but may be customized in |
1474 |
* subclasses. Note: To properly nest multiple overridings, subclasses |
1475 |
* should generally invoke <tt>super.afterExecute</tt> at the |
1476 |
* beginning of this method. |
1477 |
* |
1478 |
* @param r the runnable that has completed. |
1479 |
* @param t the exception that caused termination, or null if |
1480 |
* execution completed normally. |
1481 |
*/ |
1482 |
protected void afterExecute(Runnable r, Throwable t) { } |
1483 |
|
1484 |
/** |
1485 |
* Method invoked when the Executor has terminated. Default |
1486 |
* implementation does nothing. Note: To properly nest multiple |
1487 |
* overridings, subclasses should generally invoke |
1488 |
* <tt>super.terminated</tt> within this method. |
1489 |
*/ |
1490 |
protected void terminated() { } |
1491 |
|
1492 |
/** |
1493 |
* A handler for rejected tasks that runs the rejected task |
1494 |
* directly in the calling thread of the <tt>execute</tt> method, |
1495 |
* unless the executor has been shut down, in which case the task |
1496 |
* is discarded. |
1497 |
*/ |
1498 |
public static class CallerRunsPolicy implements RejectedExecutionHandler { |
1499 |
/** |
1500 |
* Creates a <tt>CallerRunsPolicy</tt>. |
1501 |
*/ |
1502 |
public CallerRunsPolicy() { } |
1503 |
|
1504 |
/** |
1505 |
* Executes task r in the caller's thread, unless the executor |
1506 |
* has been shut down, in which case the task is discarded. |
1507 |
* @param r the runnable task requested to be executed |
1508 |
* @param e the executor attempting to execute this task |
1509 |
*/ |
1510 |
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { |
1511 |
if (!e.isShutdown()) { |
1512 |
r.run(); |
1513 |
} |
1514 |
} |
1515 |
} |
1516 |
|
1517 |
/** |
1518 |
* A handler for rejected tasks that throws a |
1519 |
* <tt>RejectedExecutionException</tt>. |
1520 |
*/ |
1521 |
public static class AbortPolicy implements RejectedExecutionHandler { |
1522 |
/** |
1523 |
* Creates an <tt>AbortPolicy</tt>. |
1524 |
*/ |
1525 |
public AbortPolicy() { } |
1526 |
|
1527 |
/** |
1528 |
* Always throws RejectedExecutionException. |
1529 |
* @param r the runnable task requested to be executed |
1530 |
* @param e the executor attempting to execute this task |
1531 |
* @throws RejectedExecutionException always. |
1532 |
*/ |
1533 |
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { |
1534 |
throw new RejectedExecutionException(); |
1535 |
} |
1536 |
} |
1537 |
|
1538 |
/** |
1539 |
* A handler for rejected tasks that silently discards the |
1540 |
* rejected task. |
1541 |
*/ |
1542 |
public static class DiscardPolicy implements RejectedExecutionHandler { |
1543 |
/** |
1544 |
* Creates a <tt>DiscardPolicy</tt>. |
1545 |
*/ |
1546 |
public DiscardPolicy() { } |
1547 |
|
1548 |
/** |
1549 |
* Does nothing, which has the effect of discarding task r. |
1550 |
* @param r the runnable task requested to be executed |
1551 |
* @param e the executor attempting to execute this task |
1552 |
*/ |
1553 |
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { |
1554 |
} |
1555 |
} |
1556 |
|
1557 |
/** |
1558 |
* A handler for rejected tasks that discards the oldest unhandled |
1559 |
* request and then retries <tt>execute</tt>, unless the executor |
1560 |
* is shut down, in which case the task is discarded. |
1561 |
*/ |
1562 |
public static class DiscardOldestPolicy implements RejectedExecutionHandler { |
1563 |
/** |
1564 |
* Creates a <tt>DiscardOldestPolicy</tt> for the given executor. |
1565 |
*/ |
1566 |
public DiscardOldestPolicy() { } |
1567 |
|
1568 |
/** |
1569 |
* Obtains and ignores the next task that the executor |
1570 |
* would otherwise execute, if one is immediately available, |
1571 |
* and then retries execution of task r, unless the executor |
1572 |
* is shut down, in which case task r is instead discarded. |
1573 |
* @param r the runnable task requested to be executed |
1574 |
* @param e the executor attempting to execute this task |
1575 |
*/ |
1576 |
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { |
1577 |
if (!e.isShutdown()) { |
1578 |
e.getQueue().poll(); |
1579 |
e.execute(r); |
1580 |
} |
1581 |
} |
1582 |
} |
1583 |
} |