ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.62
Committed: Fri Dec 31 14:52:36 2004 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.61: +47 -9 lines
Log Message:
Add ThreadPoolExecutor.allowCoreThreadTimeOut

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