ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.61
Committed: Fri Dec 31 12:59:20 2004 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.60: +3 -1 lines
Log Message:
Reduce need for replacing interrupted worker threads

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.47 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.9 import java.util.concurrent.locks.*;
9 dl 1.2 import java.util.*;
10 tim 1.1
11     /**
12 dl 1.17 * An {@link ExecutorService} that executes each submitted task using
13 dl 1.28 * one of possibly several pooled threads, normally configured
14     * using {@link Executors} factory methods.
15 tim 1.1 *
16 dl 1.17 * <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 dl 1.20 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
22 dl 1.22 * statistics, such as the number of completed tasks.
23 dl 1.17 *
24 tim 1.1 * <p>To be useful across a wide range of contexts, this class
25 dl 1.24 * provides many adjustable parameters and extensibility
26     * hooks. However, programmers are urged to use the more convenient
27 dl 1.20 * {@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 dl 1.22 * preconfigure settings for the most common usage
33     * scenarios. Otherwise, use the following guide when manually
34 dl 1.24 * configuring and tuning this class:
35 dl 1.17 *
36 tim 1.1 * <dl>
37 dl 1.2 *
38 dl 1.21 * <dt>Core and maximum pool sizes</dt>
39 dl 1.2 *
40 dl 1.19 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
41 dl 1.21 * 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 dl 1.27 * accommodate an arbitrary number of concurrent tasks. Most typically,
58 dl 1.21 * 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 dl 1.2 *
63 dl 1.21 * <dt> On-demand construction
64 dl 1.2 *
65 dl 1.21 * <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 dl 1.2 *
71 tim 1.1 * <dt>Creating new threads</dt>
72 dl 1.2 *
73 dl 1.33 * <dd>New threads are created using a {@link
74     * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
75 dl 1.34 * {@link Executors#defaultThreadFactory} is used, that creates threads to all
76 dl 1.33 * 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 dl 1.57 * 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 dl 1.56 * not be able to execute any tasks. </dd>
83 dl 1.2 *
84 dl 1.21 * <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 dl 1.48 * <dt>Queuing</dt>
100 dl 1.21 *
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 dl 1.2 *
104 dl 1.21 * <ul>
105     *
106 dl 1.23 * <li> If fewer than corePoolSize threads are running, the Executor
107     * always prefers adding a new thread
108 dl 1.48 * rather than queuing.</li>
109 dl 1.21 *
110 dl 1.23 * <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 dl 1.21 *
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 dl 1.24 * avoid rejection of new submitted tasks. This in turn admits the
131 dl 1.21 * 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 dl 1.22 * 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 dl 1.21 *
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 dl 1.27 * lead to artificially low throughput. If tasks frequently block (for
154 dl 1.21 * 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 dl 1.24 * generally requires larger pool sizes, which keeps CPUs busier but
157     * may encounter unacceptable scheduling overhead, which also
158     * decreases throughput. </li>
159 dl 1.21 *
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 dl 1.22 * 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 dl 1.21 *
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 dl 1.48 * capacity or queuing policies. </dd>
202 dl 1.21 *
203     * <dt>Hook methods</dt>
204     *
205 dl 1.23 * <dd>This class provides <tt>protected</tt> overridable {@link
206 dl 1.21 * ThreadPoolExecutor#beforeExecute} and {@link
207     * ThreadPoolExecutor#afterExecute} methods that are called before and
208 dl 1.19 * after execution of each task. These can be used to manipulate the
209 dl 1.59 * execution environment; for example, reinitializing ThreadLocals,
210 dl 1.21 * 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 dl 1.57 * 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 dl 1.2 *
219 dl 1.21 * <dt>Queue maintenance</dt>
220 dl 1.2 *
221 dl 1.24 * <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 tim 1.1 *
229 dl 1.43 * <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 dl 1.53 * t.interrupt();
248 dl 1.43 * } finally {
249 dl 1.53 * pauseLock.unlock();
250 dl 1.43 * }
251     * }
252     *
253     * public void pause() {
254     * pauseLock.lock();
255     * try {
256     * isPaused = true;
257     * } finally {
258 dl 1.53 * pauseLock.unlock();
259 dl 1.43 * }
260     * }
261     *
262     * public void resume() {
263     * pauseLock.lock();
264     * try {
265     * isPaused = false;
266     * unpaused.signalAll();
267     * } finally {
268 dl 1.53 * pauseLock.unlock();
269 dl 1.43 * }
270     * }
271     * }
272     * </pre>
273 tim 1.1 * @since 1.5
274 dl 1.8 * @author Doug Lea
275 tim 1.1 */
276 tim 1.38 public class ThreadPoolExecutor extends AbstractExecutorService {
277 dl 1.2 /**
278 tim 1.41 * Only used to force toArray() to produce a Runnable[].
279     */
280     private static final Runnable[] EMPTY_RUNNABLE_ARRAY = new Runnable[0];
281    
282     /**
283 dl 1.43 * Permission for checking shutdown
284     */
285     private static final RuntimePermission shutdownPerm =
286     new RuntimePermission("modifyThread");
287    
288     /**
289 dl 1.2 * Queue used for holding tasks and handing off to worker threads.
290 tim 1.10 */
291 dl 1.2 private final BlockingQueue<Runnable> workQueue;
292    
293     /**
294     * Lock held on updates to poolSize, corePoolSize, maximumPoolSize, and
295     * workers set.
296 tim 1.10 */
297 dl 1.2 private final ReentrantLock mainLock = new ReentrantLock();
298    
299     /**
300     * Wait condition to support awaitTermination
301 tim 1.10 */
302 dl 1.46 private final Condition termination = mainLock.newCondition();
303 dl 1.2
304     /**
305     * Set containing all worker threads in pool.
306 tim 1.10 */
307 dl 1.17 private final HashSet<Worker> workers = new HashSet<Worker>();
308 dl 1.2
309     /**
310 dl 1.35 * Timeout in nanoseconds for idle threads waiting for work.
311 dl 1.2 * Threads use this timeout only when there are more than
312     * corePoolSize present. Otherwise they wait forever for new work.
313 tim 1.10 */
314 dl 1.2 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 tim 1.10 */
321 dl 1.2 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 tim 1.10 */
328 dl 1.2 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 tim 1.10 */
335 dl 1.2 private volatile int poolSize;
336    
337     /**
338 dl 1.16 * Lifecycle state
339 tim 1.10 */
340 dl 1.52 volatile int runState;
341 dl 1.2
342 dl 1.16 // Special values for runState
343 dl 1.8 /** Normal, not-shutdown mode */
344 dl 1.52 static final int RUNNING = 0;
345 dl 1.8 /** Controlled shutdown mode */
346 dl 1.52 static final int SHUTDOWN = 1;
347 dl 1.16 /** Immediate shutdown mode */
348 dl 1.52 static final int STOP = 2;
349 dl 1.16 /** Final state */
350 dl 1.52 static final int TERMINATED = 3;
351 dl 1.2
352     /**
353     * Handler called when saturated or shutdown in execute.
354 tim 1.10 */
355 dl 1.33 private volatile RejectedExecutionHandler handler;
356 dl 1.2
357     /**
358     * Factory for new threads.
359 tim 1.10 */
360 dl 1.33 private volatile ThreadFactory threadFactory;
361 dl 1.2
362     /**
363     * Tracks largest attained pool size.
364 tim 1.10 */
365 dl 1.2 private int largestPoolSize;
366    
367     /**
368     * Counter for completed tasks. Updated only on termination of
369     * worker threads.
370 tim 1.10 */
371 dl 1.2 private long completedTaskCount;
372 tim 1.41
373 dl 1.8 /**
374 dl 1.35 * The default rejected execution handler
375 dl 1.8 */
376 tim 1.10 private static final RejectedExecutionHandler defaultHandler =
377 dl 1.2 new AbortPolicy();
378    
379     /**
380 dl 1.17 * Invoke the rejected execution handler for the given command.
381 dl 1.13 */
382     void reject(Runnable command) {
383     handler.rejectedExecution(command, this);
384     }
385    
386 dl 1.33 /**
387 dl 1.2 * Create and return a new thread running firstTask as its first
388     * task. Call only while holding mainLock
389 dl 1.8 * @param firstTask the task the new thread should run first (or
390     * null if none)
391 dl 1.56 * @return the new thread, or null if threadFactory fails to create thread
392 dl 1.2 */
393     private Thread addThread(Runnable firstTask) {
394     Worker w = new Worker(firstTask);
395 dl 1.57 Thread t = threadFactory.newThread(w);
396 dl 1.56 if (t != null) {
397     w.thread = t;
398     workers.add(w);
399     int nt = ++poolSize;
400     if (nt > largestPoolSize)
401     largestPoolSize = nt;
402     }
403 dl 1.2 return t;
404     }
405 dl 1.15
406 dl 1.2 /**
407     * Create and start a new thread running firstTask as its first
408 dl 1.50 * task, only if fewer than corePoolSize threads are running.
409 dl 1.8 * @param firstTask the task the new thread should run first (or
410     * null if none)
411 dl 1.2 * @return true if successful.
412     */
413 dl 1.16 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
414 dl 1.2 Thread t = null;
415 dl 1.45 final ReentrantLock mainLock = this.mainLock;
416 dl 1.2 mainLock.lock();
417     try {
418 tim 1.10 if (poolSize < corePoolSize)
419 dl 1.8 t = addThread(firstTask);
420 tim 1.14 } finally {
421 dl 1.2 mainLock.unlock();
422     }
423     if (t == null)
424     return false;
425     t.start();
426     return true;
427     }
428    
429     /**
430 dl 1.50 * Create and start a new thread only if fewer than maximumPoolSize
431 dl 1.2 * 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 dl 1.8 * @param firstTask the task the new thread should run first (or
434     * null if none)
435 dl 1.2 * @return null on failure, else the first task to be run by new thread.
436     */
437 dl 1.8 private Runnable addIfUnderMaximumPoolSize(Runnable firstTask) {
438 dl 1.2 Thread t = null;
439     Runnable next = null;
440 dl 1.45 final ReentrantLock mainLock = this.mainLock;
441 dl 1.2 mainLock.lock();
442     try {
443     if (poolSize < maximumPoolSize) {
444     next = workQueue.poll();
445     if (next == null)
446 dl 1.8 next = firstTask;
447 dl 1.2 t = addThread(next);
448     }
449 tim 1.14 } finally {
450 dl 1.2 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 dl 1.8 * @return the task
462     * @throws InterruptedException if interrupted while waiting for task
463 dl 1.2 */
464 dl 1.52 Runnable getTask() throws InterruptedException {
465 dl 1.2 for (;;) {
466 dl 1.16 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 dl 1.50 } catch(InterruptedException ignore) {}
500 dl 1.16 break;
501     }
502    
503     case STOP:
504 dl 1.2 return null;
505 dl 1.16 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 dl 1.45 final ReentrantLock mainLock = this.mainLock;
516 dl 1.16 mainLock.lock();
517     try {
518 tim 1.39 for (Worker w : workers)
519     w.interruptIfIdle();
520 dl 1.16 } finally {
521     mainLock.unlock();
522 dl 1.2 }
523     }
524    
525     /**
526     * Perform bookkeeping for a terminated worker thread.
527 tim 1.10 * @param w the worker
528 dl 1.2 */
529 dl 1.52 void workerDone(Worker w) {
530 dl 1.45 final ReentrantLock mainLock = this.mainLock;
531 dl 1.2 mainLock.lock();
532     try {
533     completedTaskCount += w.completedTasks;
534     workers.remove(w);
535 tim 1.10 if (--poolSize > 0)
536 dl 1.2 return;
537    
538 dl 1.16 // Else, this is the last thread. Deal with potential shutdown.
539    
540     int state = runState;
541     assert state != TERMINATED;
542 tim 1.10
543 dl 1.16 if (state != STOP) {
544     // If there are queued tasks but no threads, create
545 dl 1.56 // 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 dl 1.16 if (!workQueue.isEmpty()) {
550 dl 1.56 Thread t = addThread(null);
551     if (t != null)
552     t.start();
553 dl 1.16 return;
554     }
555    
556     // Otherwise, we can exit without replacement
557     if (state == RUNNING)
558     return;
559 dl 1.2 }
560    
561 dl 1.16 // Either state is STOP, or state is SHUTDOWN and there is
562     // no work to do. So we can terminate.
563 dl 1.45 termination.signalAll();
564 dl 1.16 runState = TERMINATED;
565     // fall through to call terminate() outside of lock.
566 tim 1.14 } finally {
567 dl 1.2 mainLock.unlock();
568     }
569    
570 dl 1.16 assert runState == TERMINATED;
571     terminated();
572 dl 1.2 }
573    
574     /**
575 tim 1.10 * Worker threads
576 dl 1.2 */
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 tim 1.10 */
615 dl 1.2 void interruptIfIdle() {
616 dl 1.45 final ReentrantLock runLock = this.runLock;
617 dl 1.2 if (runLock.tryLock()) {
618     try {
619     thread.interrupt();
620 tim 1.14 } finally {
621 dl 1.2 runLock.unlock();
622     }
623     }
624     }
625    
626     /**
627 dl 1.61 * Interrupt thread even if running a task.
628 tim 1.10 */
629 dl 1.2 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 dl 1.45 final ReentrantLock runLock = this.runLock;
638 dl 1.2 runLock.lock();
639     try {
640     // Abort now if immediate cancel. Otherwise, we have
641     // committed to run this task.
642 dl 1.16 if (runState == STOP)
643 dl 1.2 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 dl 1.61 // re-clear to avoid needlessly throwing away thread
652     Thread.interrupted();
653 dl 1.2 afterExecute(task, null);
654     ++completedTasks;
655 tim 1.14 } catch(RuntimeException ex) {
656 dl 1.2 if (!ran)
657     afterExecute(task, ex);
658 dl 1.17 // Else the exception occurred within
659 dl 1.2 // afterExecute itself in which case we don't
660     // want to call it again.
661     throw ex;
662     }
663 tim 1.14 } finally {
664 dl 1.2 runLock.unlock();
665     }
666     }
667    
668     /**
669     * Main run loop
670     */
671     public void run() {
672     try {
673 dl 1.50 Runnable task = firstTask;
674     firstTask = null;
675     while (task != null || (task = getTask()) != null) {
676 dl 1.2 runTask(task);
677     task = null; // unnecessary but can help GC
678     }
679 tim 1.14 } catch(InterruptedException ie) {
680 dl 1.2 // fall through
681 tim 1.14 } finally {
682 dl 1.2 workerDone(this);
683     }
684     }
685     }
686 tim 1.1
687 dl 1.17 // Public methods
688    
689 tim 1.1 /**
690 dl 1.17 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
691 dl 1.34 * initial parameters and default thread factory and handler. It
692     * may be more convenient to use one of the {@link Executors}
693     * factory methods instead of this general purpose constructor.
694 tim 1.1 *
695 dl 1.2 * @param corePoolSize the number of threads to keep in the
696 tim 1.1 * pool, even if they are idle.
697 dl 1.2 * @param maximumPoolSize the maximum number of threads to allow in the
698 tim 1.1 * pool.
699     * @param keepAliveTime when the number of threads is greater than
700 dl 1.2 * the core, this is the maximum time that excess idle threads
701 tim 1.1 * will wait for new tasks before terminating.
702 dl 1.2 * @param unit the time unit for the keepAliveTime
703 tim 1.1 * argument.
704 dl 1.36 * @param workQueue the queue to use for holding tasks before they
705 tim 1.1 * are executed. This queue will hold only the <tt>Runnable</tt>
706     * tasks submitted by the <tt>execute</tt> method.
707 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
708     * keepAliveTime less than zero, or if maximumPoolSize less than or
709     * equal to zero, or if corePoolSize greater than maximumPoolSize.
710 tim 1.1 * @throws NullPointerException if <tt>workQueue</tt> is null
711     */
712 dl 1.2 public ThreadPoolExecutor(int corePoolSize,
713     int maximumPoolSize,
714 tim 1.1 long keepAliveTime,
715 dl 1.2 TimeUnit unit,
716     BlockingQueue<Runnable> workQueue) {
717 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
718 dl 1.34 Executors.defaultThreadFactory(), defaultHandler);
719 dl 1.2 }
720 tim 1.1
721 dl 1.2 /**
722     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
723     * parameters.
724     *
725     * @param corePoolSize the number of threads to keep in the
726     * pool, even if they are idle.
727     * @param maximumPoolSize the maximum number of threads to allow in the
728     * pool.
729     * @param keepAliveTime when the number of threads is greater than
730     * the core, this is the maximum time that excess idle threads
731     * will wait for new tasks before terminating.
732     * @param unit the time unit for the keepAliveTime
733     * argument.
734 dl 1.36 * @param workQueue the queue to use for holding tasks before they
735 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
736     * tasks submitted by the <tt>execute</tt> method.
737     * @param threadFactory the factory to use when the executor
738 tim 1.10 * creates a new thread.
739 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
740     * keepAliveTime less than zero, or if maximumPoolSize less than or
741     * equal to zero, or if corePoolSize greater than maximumPoolSize.
742 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
743 dl 1.2 * or <tt>threadFactory</tt> are null.
744     */
745     public ThreadPoolExecutor(int corePoolSize,
746     int maximumPoolSize,
747     long keepAliveTime,
748     TimeUnit unit,
749     BlockingQueue<Runnable> workQueue,
750     ThreadFactory threadFactory) {
751 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
752 dl 1.2 threadFactory, defaultHandler);
753     }
754 tim 1.1
755 dl 1.2 /**
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 dl 1.36 * @param workQueue the queue to use for holding tasks before they
769 dl 1.2 * 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 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
777 dl 1.2 * 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 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
786 dl 1.34 Executors.defaultThreadFactory(), handler);
787 dl 1.2 }
788 tim 1.1
789 dl 1.2 /**
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 dl 1.36 * @param workQueue the queue to use for holding tasks before they
803 dl 1.2 * 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 tim 1.10 * creates a new thread.
807 dl 1.2 * @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 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
813 dl 1.2 * 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 tim 1.10 if (corePoolSize < 0 ||
823 dl 1.2 maximumPoolSize <= 0 ||
824 tim 1.10 maximumPoolSize < corePoolSize ||
825 dl 1.2 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 tim 1.1 }
836    
837 dl 1.2
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 tim 1.10 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
845 dl 1.2 *
846     * @param command the task to execute
847     * @throws RejectedExecutionException at discretion of
848 dl 1.8 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
849     * for execution
850 dl 1.26 * @throws NullPointerException if command is null
851 dl 1.2 */
852 tim 1.10 public void execute(Runnable command) {
853 dl 1.26 if (command == null)
854     throw new NullPointerException();
855 dl 1.2 for (;;) {
856 dl 1.16 if (runState != RUNNING) {
857 dl 1.13 reject(command);
858 dl 1.2 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 dl 1.13 reject(command);
869 dl 1.2 return;
870     }
871     // else retry
872     }
873 tim 1.1 }
874 dl 1.4
875 dl 1.53 /**
876     * Initiates an orderly shutdown in which previously submitted
877     * tasks are executed, but no new tasks will be
878     * accepted. Invocation has no additional effect if already shut
879     * down.
880     * @throws SecurityException if a security manager exists and
881     * shutting down this ExecutorService may manipulate threads that
882     * the caller is not permitted to modify because it does not hold
883     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
884     * or the security manager's <tt>checkAccess</tt> method denies access.
885     */
886 dl 1.2 public void shutdown() {
887 dl 1.58 // Fail if caller doesn't have modifyThread permission. We
888 dl 1.60 // explicitly check permissions directly because we can't trust
889 dl 1.58 // implementations of SecurityManager to correctly override
890     // the "check access" methods such that our documented
891     // security policy is implemented.
892 dl 1.42 SecurityManager security = System.getSecurityManager();
893     if (security != null)
894 dl 1.43 java.security.AccessController.checkPermission(shutdownPerm);
895 dl 1.42
896 dl 1.25 boolean fullyTerminated = false;
897 dl 1.45 final ReentrantLock mainLock = this.mainLock;
898 dl 1.2 mainLock.lock();
899     try {
900 dl 1.25 if (workers.size() > 0) {
901 dl 1.50 // Check if caller can modify worker threads. This
902     // might not be true even if passed above check, if
903     // the SecurityManager treats some threads specially.
904 dl 1.43 if (security != null) {
905     for (Worker w: workers)
906     security.checkAccess(w.thread);
907     }
908    
909     int state = runState;
910     if (state == RUNNING) // don't override shutdownNow
911 dl 1.25 runState = SHUTDOWN;
912 dl 1.43
913     try {
914     for (Worker w: workers)
915     w.interruptIfIdle();
916     } catch(SecurityException se) {
917 dl 1.50 // If SecurityManager allows above checks, but
918     // then unexpectedly throws exception when
919     // interrupting threads (which it ought not do),
920     // back out as cleanly as we can. Some threads may
921     // have been killed but we remain in non-shutdown
922     // state.
923 dl 1.43 runState = state;
924     throw se;
925     }
926 dl 1.25 }
927     else { // If no workers, trigger full termination now
928     fullyTerminated = true;
929     runState = TERMINATED;
930     termination.signalAll();
931     }
932 tim 1.14 } finally {
933 dl 1.2 mainLock.unlock();
934     }
935 dl 1.25 if (fullyTerminated)
936     terminated();
937 tim 1.1 }
938    
939 dl 1.16
940 dl 1.53 /**
941     * Attempts to stop all actively executing tasks, halts the
942     * processing of waiting tasks, and returns a list of the tasks that were
943     * awaiting execution.
944     *
945     * <p>This implementation cancels tasks via {@link
946     * Thread#interrupt}, so if any tasks mask or fail to respond to
947     * interrupts, they may never terminate.
948     *
949     * @return list of tasks that never commenced execution
950     * @throws SecurityException if a security manager exists and
951     * shutting down this ExecutorService may manipulate threads that
952     * the caller is not permitted to modify because it does not hold
953     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
954     * or the security manager's <tt>checkAccess</tt> method denies access.
955     */
956 tim 1.39 public List<Runnable> shutdownNow() {
957 dl 1.43 // Almost the same code as shutdown()
958 dl 1.42 SecurityManager security = System.getSecurityManager();
959     if (security != null)
960 dl 1.43 java.security.AccessController.checkPermission(shutdownPerm);
961    
962 dl 1.25 boolean fullyTerminated = false;
963 dl 1.45 final ReentrantLock mainLock = this.mainLock;
964 dl 1.2 mainLock.lock();
965     try {
966 dl 1.25 if (workers.size() > 0) {
967 dl 1.43 if (security != null) {
968     for (Worker w: workers)
969     security.checkAccess(w.thread);
970     }
971    
972     int state = runState;
973     if (state != TERMINATED)
974 dl 1.25 runState = STOP;
975 dl 1.43 try {
976     for (Worker w : workers)
977     w.interruptNow();
978     } catch(SecurityException se) {
979     runState = state; // back out;
980     throw se;
981     }
982 dl 1.25 }
983     else { // If no workers, trigger full termination now
984     fullyTerminated = true;
985     runState = TERMINATED;
986     termination.signalAll();
987     }
988 tim 1.14 } finally {
989 dl 1.2 mainLock.unlock();
990     }
991 dl 1.25 if (fullyTerminated)
992     terminated();
993 tim 1.41 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
994 tim 1.1 }
995    
996 dl 1.2 public boolean isShutdown() {
997 dl 1.16 return runState != RUNNING;
998     }
999    
1000     /**
1001 dl 1.55 * Returns true if this executor is in the process of terminating
1002 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1003     * completely terminated. This method may be useful for
1004     * debugging. A return of <tt>true</tt> reported a sufficient
1005     * period after shutdown may indicate that submitted tasks have
1006     * ignored or suppressed interruption, causing this executor not
1007     * to properly terminate.
1008     * @return true if terminating but not yet terminated.
1009     */
1010     public boolean isTerminating() {
1011     return runState == STOP;
1012 tim 1.1 }
1013    
1014 dl 1.2 public boolean isTerminated() {
1015 dl 1.16 return runState == TERMINATED;
1016 dl 1.2 }
1017 tim 1.1
1018 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1019     throws InterruptedException {
1020 dl 1.50 long nanos = unit.toNanos(timeout);
1021 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1022 dl 1.2 mainLock.lock();
1023     try {
1024 dl 1.25 for (;;) {
1025     if (runState == TERMINATED)
1026     return true;
1027     if (nanos <= 0)
1028     return false;
1029     nanos = termination.awaitNanos(nanos);
1030     }
1031 tim 1.14 } finally {
1032 dl 1.2 mainLock.unlock();
1033     }
1034 dl 1.15 }
1035    
1036     /**
1037     * Invokes <tt>shutdown</tt> when this executor is no longer
1038     * referenced.
1039     */
1040     protected void finalize() {
1041     shutdown();
1042 dl 1.2 }
1043 tim 1.10
1044 dl 1.2 /**
1045     * Sets the thread factory used to create new threads.
1046     *
1047     * @param threadFactory the new thread factory
1048 dl 1.30 * @throws NullPointerException if threadFactory is null
1049 tim 1.11 * @see #getThreadFactory
1050 dl 1.2 */
1051     public void setThreadFactory(ThreadFactory threadFactory) {
1052 dl 1.30 if (threadFactory == null)
1053     throw new NullPointerException();
1054 dl 1.2 this.threadFactory = threadFactory;
1055 tim 1.1 }
1056    
1057 dl 1.2 /**
1058     * Returns the thread factory used to create new threads.
1059     *
1060     * @return the current thread factory
1061 tim 1.11 * @see #setThreadFactory
1062 dl 1.2 */
1063     public ThreadFactory getThreadFactory() {
1064     return threadFactory;
1065 tim 1.1 }
1066    
1067 dl 1.2 /**
1068     * Sets a new handler for unexecutable tasks.
1069     *
1070     * @param handler the new handler
1071 dl 1.31 * @throws NullPointerException if handler is null
1072 tim 1.11 * @see #getRejectedExecutionHandler
1073 dl 1.2 */
1074     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1075 dl 1.31 if (handler == null)
1076     throw new NullPointerException();
1077 dl 1.2 this.handler = handler;
1078     }
1079 tim 1.1
1080 dl 1.2 /**
1081     * Returns the current handler for unexecutable tasks.
1082     *
1083     * @return the current handler
1084 tim 1.11 * @see #setRejectedExecutionHandler
1085 dl 1.2 */
1086     public RejectedExecutionHandler getRejectedExecutionHandler() {
1087     return handler;
1088 tim 1.1 }
1089    
1090 dl 1.2 /**
1091 dl 1.17 * Returns the task queue used by this executor. Access to the
1092     * task queue is intended primarily for debugging and monitoring.
1093 dl 1.27 * This queue may be in active use. Retrieving the task queue
1094 dl 1.2 * does not prevent queued tasks from executing.
1095     *
1096     * @return the task queue
1097     */
1098     public BlockingQueue<Runnable> getQueue() {
1099     return workQueue;
1100 tim 1.1 }
1101 dl 1.4
1102     /**
1103 dl 1.44 * Removes this task from the executor's internal queue if it is
1104     * present, thus causing it not to be run if it has not already
1105     * started.
1106     *
1107     * <p> This method may be useful as one part of a cancellation
1108     * scheme. It may fail to remove tasks that have been converted
1109     * into other forms before being placed on the internal queue. For
1110     * example, a task entered using <tt>submit</tt> might be
1111     * converted into a form that maintains <tt>Future</tt> status.
1112     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1113     * may be used to remove those Futures that have been cancelled.
1114     *
1115 tim 1.10 *
1116 dl 1.8 * @param task the task to remove
1117     * @return true if the task was removed
1118 dl 1.4 */
1119 dl 1.5 public boolean remove(Runnable task) {
1120 dl 1.4 return getQueue().remove(task);
1121     }
1122    
1123 dl 1.7
1124     /**
1125 dl 1.37 * Tries to remove from the work queue all {@link Future}
1126 dl 1.16 * tasks that have been cancelled. This method can be useful as a
1127     * storage reclamation operation, that has no other impact on
1128     * functionality. Cancelled tasks are never executed, but may
1129     * accumulate in work queues until worker threads can actively
1130     * remove them. Invoking this method instead tries to remove them now.
1131 dl 1.23 * However, this method may fail to remove tasks in
1132 dl 1.16 * the presence of interference by other threads.
1133 dl 1.7 */
1134     public void purge() {
1135 dl 1.16 // Fail if we encounter interference during traversal
1136     try {
1137     Iterator<Runnable> it = getQueue().iterator();
1138     while (it.hasNext()) {
1139     Runnable r = it.next();
1140 dl 1.37 if (r instanceof Future<?>) {
1141     Future<?> c = (Future<?>)r;
1142 dl 1.16 if (c.isCancelled())
1143     it.remove();
1144     }
1145 dl 1.7 }
1146     }
1147 dl 1.16 catch(ConcurrentModificationException ex) {
1148     return;
1149     }
1150 dl 1.7 }
1151 tim 1.1
1152     /**
1153 dl 1.2 * Sets the core number of threads. This overrides any value set
1154     * in the constructor. If the new value is smaller than the
1155     * current value, excess existing threads will be terminated when
1156 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1157     * be started to execute any queued tasks.
1158 tim 1.1 *
1159 dl 1.2 * @param corePoolSize the new core size
1160 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1161 dl 1.8 * less than zero
1162 tim 1.11 * @see #getCorePoolSize
1163 tim 1.1 */
1164 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1165     if (corePoolSize < 0)
1166     throw new IllegalArgumentException();
1167 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1168 dl 1.2 mainLock.lock();
1169     try {
1170     int extra = this.corePoolSize - corePoolSize;
1171     this.corePoolSize = corePoolSize;
1172 tim 1.38 if (extra < 0) {
1173 dl 1.56 int n = workQueue.size();
1174     // We have to create initially-idle threads here
1175     // because we otherwise have no recourse about
1176     // what to do with a dequeued task if addThread fails.
1177     while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize ) {
1178     Thread t = addThread(null);
1179     if (t != null)
1180     t.start();
1181     else
1182     break;
1183     }
1184 tim 1.38 }
1185     else if (extra > 0 && poolSize > corePoolSize) {
1186 dl 1.2 Iterator<Worker> it = workers.iterator();
1187 tim 1.10 while (it.hasNext() &&
1188 dl 1.34 extra-- > 0 &&
1189 dl 1.2 poolSize > corePoolSize &&
1190 dl 1.34 workQueue.remainingCapacity() == 0)
1191 dl 1.2 it.next().interruptIfIdle();
1192     }
1193 tim 1.14 } finally {
1194 dl 1.2 mainLock.unlock();
1195     }
1196     }
1197 tim 1.1
1198     /**
1199 dl 1.2 * Returns the core number of threads.
1200 tim 1.1 *
1201 dl 1.2 * @return the core number of threads
1202 tim 1.11 * @see #setCorePoolSize
1203 tim 1.1 */
1204 tim 1.10 public int getCorePoolSize() {
1205 dl 1.2 return corePoolSize;
1206 dl 1.16 }
1207    
1208     /**
1209 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1210 dl 1.16 * overrides the default policy of starting core threads only when
1211     * new tasks are executed. This method will return <tt>false</tt>
1212     * if all core threads have already been started.
1213     * @return true if a thread was started
1214     */
1215     public boolean prestartCoreThread() {
1216     return addIfUnderCorePoolSize(null);
1217     }
1218    
1219     /**
1220 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1221 dl 1.16 * overrides the default policy of starting core threads only when
1222     * new tasks are executed.
1223     * @return the number of threads started.
1224     */
1225     public int prestartAllCoreThreads() {
1226     int n = 0;
1227     while (addIfUnderCorePoolSize(null))
1228     ++n;
1229     return n;
1230 dl 1.2 }
1231 tim 1.1
1232     /**
1233     * Sets the maximum allowed number of threads. This overrides any
1234 dl 1.2 * value set in the constructor. If the new value is smaller than
1235     * the current value, excess existing threads will be
1236     * terminated when they next become idle.
1237 tim 1.1 *
1238 dl 1.2 * @param maximumPoolSize the new maximum
1239     * @throws IllegalArgumentException if maximumPoolSize less than zero or
1240     * the {@link #getCorePoolSize core pool size}
1241 tim 1.11 * @see #getMaximumPoolSize
1242 dl 1.2 */
1243     public void setMaximumPoolSize(int maximumPoolSize) {
1244     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1245     throw new IllegalArgumentException();
1246 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1247 dl 1.2 mainLock.lock();
1248     try {
1249     int extra = this.maximumPoolSize - maximumPoolSize;
1250     this.maximumPoolSize = maximumPoolSize;
1251     if (extra > 0 && poolSize > maximumPoolSize) {
1252     Iterator<Worker> it = workers.iterator();
1253 tim 1.10 while (it.hasNext() &&
1254     extra > 0 &&
1255 dl 1.2 poolSize > maximumPoolSize) {
1256     it.next().interruptIfIdle();
1257     --extra;
1258     }
1259     }
1260 tim 1.14 } finally {
1261 dl 1.2 mainLock.unlock();
1262     }
1263     }
1264 tim 1.1
1265     /**
1266     * Returns the maximum allowed number of threads.
1267     *
1268 dl 1.2 * @return the maximum allowed number of threads
1269 tim 1.11 * @see #setMaximumPoolSize
1270 tim 1.1 */
1271 tim 1.10 public int getMaximumPoolSize() {
1272 dl 1.2 return maximumPoolSize;
1273     }
1274 tim 1.1
1275     /**
1276     * Sets the time limit for which threads may remain idle before
1277 dl 1.2 * being terminated. If there are more than the core number of
1278 tim 1.1 * threads currently in the pool, after waiting this amount of
1279     * time without processing a task, excess threads will be
1280     * terminated. This overrides any value set in the constructor.
1281     * @param time the time to wait. A time value of zero will cause
1282     * excess threads to terminate immediately after executing tasks.
1283 dl 1.2 * @param unit the time unit of the time argument
1284 dl 1.17 * @throws IllegalArgumentException if time less than zero
1285 tim 1.11 * @see #getKeepAliveTime
1286 tim 1.1 */
1287 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1288     if (time < 0)
1289     throw new IllegalArgumentException();
1290     this.keepAliveTime = unit.toNanos(time);
1291     }
1292 tim 1.1
1293     /**
1294     * Returns the thread keep-alive time, which is the amount of time
1295 dl 1.2 * which threads in excess of the core pool size may remain
1296 tim 1.10 * idle before being terminated.
1297 tim 1.1 *
1298 dl 1.2 * @param unit the desired time unit of the result
1299 tim 1.1 * @return the time limit
1300 tim 1.11 * @see #setKeepAliveTime
1301 tim 1.1 */
1302 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1303 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1304     }
1305 tim 1.1
1306     /* Statistics */
1307    
1308     /**
1309     * Returns the current number of threads in the pool.
1310     *
1311     * @return the number of threads
1312     */
1313 tim 1.10 public int getPoolSize() {
1314 dl 1.2 return poolSize;
1315     }
1316 tim 1.1
1317     /**
1318 dl 1.2 * Returns the approximate number of threads that are actively
1319 tim 1.1 * executing tasks.
1320     *
1321     * @return the number of threads
1322     */
1323 tim 1.10 public int getActiveCount() {
1324 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1325 dl 1.2 mainLock.lock();
1326     try {
1327     int n = 0;
1328 tim 1.39 for (Worker w : workers) {
1329     if (w.isActive())
1330 dl 1.2 ++n;
1331     }
1332     return n;
1333 tim 1.14 } finally {
1334 dl 1.2 mainLock.unlock();
1335     }
1336     }
1337 tim 1.1
1338     /**
1339 dl 1.2 * Returns the largest number of threads that have ever
1340     * simultaneously been in the pool.
1341 tim 1.1 *
1342     * @return the number of threads
1343     */
1344 tim 1.10 public int getLargestPoolSize() {
1345 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1346 dl 1.2 mainLock.lock();
1347     try {
1348     return largestPoolSize;
1349 tim 1.14 } finally {
1350 dl 1.2 mainLock.unlock();
1351     }
1352     }
1353 tim 1.1
1354     /**
1355 dl 1.2 * Returns the approximate total number of tasks that have been
1356     * scheduled for execution. Because the states of tasks and
1357     * threads may change dynamically during computation, the returned
1358 dl 1.17 * value is only an approximation, but one that does not ever
1359     * decrease across successive calls.
1360 tim 1.1 *
1361     * @return the number of tasks
1362     */
1363 tim 1.10 public long getTaskCount() {
1364 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1365 dl 1.2 mainLock.lock();
1366     try {
1367     long n = completedTaskCount;
1368 tim 1.39 for (Worker w : workers) {
1369 dl 1.2 n += w.completedTasks;
1370     if (w.isActive())
1371     ++n;
1372     }
1373     return n + workQueue.size();
1374 tim 1.14 } finally {
1375 dl 1.2 mainLock.unlock();
1376     }
1377     }
1378 tim 1.1
1379     /**
1380 dl 1.2 * Returns the approximate total number of tasks that have
1381     * completed execution. Because the states of tasks and threads
1382     * may change dynamically during computation, the returned value
1383 dl 1.17 * is only an approximation, but one that does not ever decrease
1384     * across successive calls.
1385 tim 1.1 *
1386     * @return the number of tasks
1387     */
1388 tim 1.10 public long getCompletedTaskCount() {
1389 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1390 dl 1.2 mainLock.lock();
1391     try {
1392     long n = completedTaskCount;
1393 tim 1.39 for (Worker w : workers)
1394     n += w.completedTasks;
1395 dl 1.2 return n;
1396 tim 1.14 } finally {
1397 dl 1.2 mainLock.unlock();
1398     }
1399     }
1400 tim 1.1
1401     /**
1402 dl 1.17 * Method invoked prior to executing the given Runnable in the
1403 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1404     * will execute task <tt>r</tt>, and may be used to re-initialize
1405 dl 1.17 * ThreadLocals, or to perform logging. Note: To properly nest
1406     * multiple overridings, subclasses should generally invoke
1407 dl 1.5 * <tt>super.beforeExecute</tt> at the end of this method.
1408 tim 1.1 *
1409 dl 1.2 * @param t the thread that will run task r.
1410     * @param r the task that will be executed.
1411 tim 1.1 */
1412 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1413 tim 1.1
1414     /**
1415 dl 1.2 * Method invoked upon completion of execution of the given
1416 dl 1.43 * Runnable. This method is invoked by the thread that executed
1417     * the task. If non-null, the Throwable is the uncaught exception
1418 dl 1.5 * that caused execution to terminate abruptly. Note: To properly
1419     * nest multiple overridings, subclasses should generally invoke
1420     * <tt>super.afterExecute</tt> at the beginning of this method.
1421 tim 1.1 *
1422 dl 1.2 * @param r the runnable that has completed.
1423 dl 1.24 * @param t the exception that caused termination, or null if
1424 dl 1.2 * execution completed normally.
1425 tim 1.1 */
1426 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1427 tim 1.1
1428 dl 1.2 /**
1429     * Method invoked when the Executor has terminated. Default
1430 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1431     * overridings, subclasses should generally invoke
1432     * <tt>super.terminated</tt> within this method.
1433 dl 1.2 */
1434     protected void terminated() { }
1435 tim 1.1
1436     /**
1437 dl 1.21 * A handler for rejected tasks that runs the rejected task
1438     * directly in the calling thread of the <tt>execute</tt> method,
1439     * unless the executor has been shut down, in which case the task
1440     * is discarded.
1441 tim 1.1 */
1442 dl 1.2 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1443 tim 1.1 /**
1444 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1445 tim 1.1 */
1446     public CallerRunsPolicy() { }
1447    
1448 dl 1.24 /**
1449     * Executes task r in the caller's thread, unless the executor
1450     * has been shut down, in which case the task is discarded.
1451     * @param r the runnable task requested to be executed
1452     * @param e the executor attempting to execute this task
1453     */
1454 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1455     if (!e.isShutdown()) {
1456 tim 1.1 r.run();
1457     }
1458     }
1459     }
1460    
1461     /**
1462 dl 1.21 * A handler for rejected tasks that throws a
1463 dl 1.8 * <tt>RejectedExecutionException</tt>.
1464 tim 1.1 */
1465 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1466 tim 1.1 /**
1467 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1468 tim 1.1 */
1469     public AbortPolicy() { }
1470    
1471 dl 1.24 /**
1472 dl 1.54 * Always throws RejectedExecutionException.
1473 dl 1.24 * @param r the runnable task requested to be executed
1474     * @param e the executor attempting to execute this task
1475     * @throws RejectedExecutionException always.
1476     */
1477 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1478     throw new RejectedExecutionException();
1479 tim 1.1 }
1480     }
1481    
1482     /**
1483 dl 1.21 * A handler for rejected tasks that silently discards the
1484     * rejected task.
1485 tim 1.1 */
1486 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1487 tim 1.1 /**
1488 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1489 tim 1.1 */
1490     public DiscardPolicy() { }
1491    
1492 dl 1.24 /**
1493     * Does nothing, which has the effect of discarding task r.
1494     * @param r the runnable task requested to be executed
1495     * @param e the executor attempting to execute this task
1496     */
1497 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1498 tim 1.1 }
1499     }
1500    
1501     /**
1502 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1503     * request and then retries <tt>execute</tt>, unless the executor
1504     * is shut down, in which case the task is discarded.
1505 tim 1.1 */
1506 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1507 tim 1.1 /**
1508 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1509 tim 1.1 */
1510     public DiscardOldestPolicy() { }
1511    
1512 dl 1.24 /**
1513     * Obtains and ignores the next task that the executor
1514     * would otherwise execute, if one is immediately available,
1515     * and then retries execution of task r, unless the executor
1516     * is shut down, in which case task r is instead discarded.
1517     * @param r the runnable task requested to be executed
1518     * @param e the executor attempting to execute this task
1519     */
1520 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1521     if (!e.isShutdown()) {
1522     e.getQueue().poll();
1523     e.execute(r);
1524 tim 1.1 }
1525     }
1526     }
1527     }