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