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