ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.53
Committed: Wed Jan 21 15:20:35 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.52: +31 -4 lines
Log Message:
doc improvements; consistent conventions for nested classes

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