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