ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.63
Committed: Tue Jan 4 00:07:26 2005 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.62: +39 -44 lines
Log Message:
Reduce need for replacing interrupted worker threads

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.47 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.9 import java.util.concurrent.locks.*;
9 dl 1.2 import java.util.*;
10 tim 1.1
11     /**
12 dl 1.17 * An {@link ExecutorService} that executes each submitted task using
13 dl 1.28 * one of possibly several pooled threads, normally configured
14     * using {@link Executors} factory methods.
15 tim 1.1 *
16 dl 1.17 * <p>Thread pools address two different problems: they usually
17     * provide improved performance when executing large numbers of
18     * asynchronous tasks, due to reduced per-task invocation overhead,
19     * and they provide a means of bounding and managing the resources,
20     * including threads, consumed when executing a collection of tasks.
21 dl 1.20 * Each <tt>ThreadPoolExecutor</tt> also maintains some basic
22 dl 1.22 * statistics, such as the number of completed tasks.
23 dl 1.17 *
24 tim 1.1 * <p>To be useful across a wide range of contexts, this class
25 dl 1.24 * provides many adjustable parameters and extensibility
26     * hooks. However, programmers are urged to use the more convenient
27 dl 1.20 * {@link Executors} factory methods {@link
28     * Executors#newCachedThreadPool} (unbounded thread pool, with
29     * automatic thread reclamation), {@link Executors#newFixedThreadPool}
30     * (fixed size thread pool) and {@link
31     * Executors#newSingleThreadExecutor} (single background thread), that
32 dl 1.22 * preconfigure settings for the most common usage
33     * scenarios. Otherwise, use the following guide when manually
34 dl 1.24 * configuring and tuning this class:
35 dl 1.17 *
36 tim 1.1 * <dl>
37 dl 1.2 *
38 dl 1.21 * <dt>Core and maximum pool sizes</dt>
39 dl 1.2 *
40 dl 1.19 * <dd>A <tt>ThreadPoolExecutor</tt> will automatically adjust the
41 dl 1.21 * pool size
42     * (see {@link ThreadPoolExecutor#getPoolSize})
43     * according to the bounds set by corePoolSize
44     * (see {@link ThreadPoolExecutor#getCorePoolSize})
45     * and
46     * maximumPoolSize
47     * (see {@link ThreadPoolExecutor#getMaximumPoolSize}).
48     * When a new task is submitted in method {@link
49     * ThreadPoolExecutor#execute}, and fewer than corePoolSize threads
50     * are running, a new thread is created to handle the request, even if
51     * other worker threads are idle. If there are more than
52     * corePoolSize but less than maximumPoolSize threads running, a new
53     * thread will be created only if the queue is full. By setting
54     * corePoolSize and maximumPoolSize the same, you create a fixed-size
55     * thread pool. By setting maximumPoolSize to an essentially unbounded
56     * value such as <tt>Integer.MAX_VALUE</tt>, you allow the pool to
57 dl 1.27 * accommodate an arbitrary number of concurrent tasks. Most typically,
58 dl 1.21 * core and maximum pool sizes are set only upon construction, but they
59     * may also be changed dynamically using {@link
60     * ThreadPoolExecutor#setCorePoolSize} and {@link
61     * ThreadPoolExecutor#setMaximumPoolSize}. <dd>
62 dl 1.2 *
63 dl 1.21 * <dt> On-demand construction
64 dl 1.2 *
65 dl 1.21 * <dd> By default, even core threads are initially created and
66     * started only when needed by new tasks, but this can be overridden
67     * dynamically using method {@link
68     * ThreadPoolExecutor#prestartCoreThread} or
69     * {@link ThreadPoolExecutor#prestartAllCoreThreads}. </dd>
70 dl 1.2 *
71 tim 1.1 * <dt>Creating new threads</dt>
72 dl 1.2 *
73 dl 1.33 * <dd>New threads are created using a {@link
74     * java.util.concurrent.ThreadFactory}. If not otherwise specified, a
75 dl 1.34 * {@link Executors#defaultThreadFactory} is used, that creates threads to all
76 dl 1.33 * be in the same {@link ThreadGroup} and with the same
77     * <tt>NORM_PRIORITY</tt> priority and non-daemon status. By supplying
78     * a different ThreadFactory, you can alter the thread's name, thread
79 dl 1.57 * group, priority, daemon status, etc. If a <tt>ThreadFactory</tt> fails to create
80     * a thread when asked by returning null from <tt>newThread</tt>,
81     * the executor will continue, but might
82 dl 1.56 * not be able to execute any tasks. </dd>
83 dl 1.2 *
84 dl 1.21 * <dt>Keep-alive times</dt>
85     *
86     * <dd>If the pool currently has more than corePoolSize threads,
87     * excess threads will be terminated if they have been idle for more
88     * than the keepAliveTime (see {@link
89     * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
90     * reducing resource consumption when the pool is not being actively
91     * used. If the pool becomes more active later, new threads will be
92 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 dl 1.2 */
471 dl 1.63 Runnable getTask() {
472 dl 1.2 for (;;) {
473 dl 1.63 try {
474     switch(runState) {
475     case RUNNING: {
476     // untimed wait if core and not allowing core timeout
477     if (poolSize <= corePoolSize && !allowCoreThreadTimeOut)
478     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     if (poolSize > corePoolSize || allowCoreThreadTimeOut)
487     return null; // timed out
488     // Else, after timeout, the pool shrank. 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     // Else there could still be delayed tasks in queue.
505 dl 1.16 return workQueue.take();
506 dl 1.63 }
507 dl 1.16
508 dl 1.63 case STOP:
509 dl 1.16 return null;
510 dl 1.63 default:
511     assert false;
512 dl 1.16 }
513 dl 1.63 } catch(InterruptedException ie) {
514     // On interruption, re-check runstate
515 dl 1.16 }
516     }
517     }
518    
519     /**
520     * Wake up all threads that might be waiting for tasks.
521     */
522     void interruptIdleWorkers() {
523 dl 1.45 final ReentrantLock mainLock = this.mainLock;
524 dl 1.16 mainLock.lock();
525     try {
526 tim 1.39 for (Worker w : workers)
527     w.interruptIfIdle();
528 dl 1.16 } finally {
529     mainLock.unlock();
530 dl 1.2 }
531     }
532    
533     /**
534     * Perform bookkeeping for a terminated worker thread.
535 tim 1.10 * @param w the worker
536 dl 1.2 */
537 dl 1.52 void workerDone(Worker w) {
538 dl 1.45 final ReentrantLock mainLock = this.mainLock;
539 dl 1.2 mainLock.lock();
540     try {
541     completedTaskCount += w.completedTasks;
542     workers.remove(w);
543 tim 1.10 if (--poolSize > 0)
544 dl 1.2 return;
545    
546 dl 1.16 // Else, this is the last thread. Deal with potential shutdown.
547    
548     int state = runState;
549     assert state != TERMINATED;
550 tim 1.10
551 dl 1.16 if (state != STOP) {
552     // If there are queued tasks but no threads, create
553 dl 1.56 // replacement thread. We must create it initially
554     // idle to avoid orphaned tasks in case addThread
555     // fails. This also handles case of delayed tasks
556     // that will sometime later become runnable.
557 dl 1.16 if (!workQueue.isEmpty()) {
558 dl 1.56 Thread t = addThread(null);
559     if (t != null)
560     t.start();
561 dl 1.16 return;
562     }
563    
564     // Otherwise, we can exit without replacement
565     if (state == RUNNING)
566     return;
567 dl 1.2 }
568    
569 dl 1.16 // Either state is STOP, or state is SHUTDOWN and there is
570     // no work to do. So we can terminate.
571 dl 1.45 termination.signalAll();
572 dl 1.16 runState = TERMINATED;
573     // fall through to call terminate() outside of lock.
574 tim 1.14 } finally {
575 dl 1.2 mainLock.unlock();
576     }
577    
578 dl 1.16 assert runState == TERMINATED;
579     terminated();
580 dl 1.2 }
581    
582     /**
583 tim 1.10 * Worker threads
584 dl 1.2 */
585     private class Worker implements Runnable {
586    
587     /**
588     * The runLock is acquired and released surrounding each task
589     * execution. It mainly protects against interrupts that are
590     * intended to cancel the worker thread from instead
591     * interrupting the task being run.
592     */
593     private final ReentrantLock runLock = new ReentrantLock();
594    
595     /**
596     * Initial task to run before entering run loop
597     */
598     private Runnable firstTask;
599    
600     /**
601     * Per thread completed task counter; accumulated
602     * into completedTaskCount upon termination.
603     */
604     volatile long completedTasks;
605    
606     /**
607     * Thread this worker is running in. Acts as a final field,
608     * but cannot be set until thread is created.
609     */
610     Thread thread;
611    
612     Worker(Runnable firstTask) {
613     this.firstTask = firstTask;
614     }
615    
616     boolean isActive() {
617     return runLock.isLocked();
618     }
619    
620     /**
621     * Interrupt thread if not running a task
622 tim 1.10 */
623 dl 1.2 void interruptIfIdle() {
624 dl 1.45 final ReentrantLock runLock = this.runLock;
625 dl 1.2 if (runLock.tryLock()) {
626     try {
627     thread.interrupt();
628 tim 1.14 } finally {
629 dl 1.2 runLock.unlock();
630     }
631     }
632     }
633    
634     /**
635 dl 1.61 * Interrupt thread even if running a task.
636 tim 1.10 */
637 dl 1.2 void interruptNow() {
638     thread.interrupt();
639     }
640    
641     /**
642     * Run a single task between before/after methods.
643     */
644     private void runTask(Runnable task) {
645 dl 1.45 final ReentrantLock runLock = this.runLock;
646 dl 1.2 runLock.lock();
647     try {
648     // Abort now if immediate cancel. Otherwise, we have
649     // committed to run this task.
650 dl 1.16 if (runState == STOP)
651 dl 1.2 return;
652    
653     Thread.interrupted(); // clear interrupt status on entry
654     boolean ran = false;
655     beforeExecute(thread, task);
656     try {
657     task.run();
658     ran = true;
659     afterExecute(task, null);
660     ++completedTasks;
661 tim 1.14 } catch(RuntimeException ex) {
662 dl 1.2 if (!ran)
663     afterExecute(task, ex);
664 dl 1.17 // Else the exception occurred within
665 dl 1.2 // afterExecute itself in which case we don't
666     // want to call it again.
667     throw ex;
668     }
669 tim 1.14 } finally {
670 dl 1.2 runLock.unlock();
671     }
672     }
673    
674     /**
675     * Main run loop
676     */
677     public void run() {
678     try {
679 dl 1.50 Runnable task = firstTask;
680     firstTask = null;
681     while (task != null || (task = getTask()) != null) {
682 dl 1.2 runTask(task);
683     task = null; // unnecessary but can help GC
684     }
685 tim 1.14 } finally {
686 dl 1.2 workerDone(this);
687     }
688     }
689     }
690 tim 1.1
691 dl 1.17 // Public methods
692    
693 tim 1.1 /**
694 dl 1.17 * Creates a new <tt>ThreadPoolExecutor</tt> with the given
695 dl 1.34 * initial parameters and default thread factory and handler. It
696     * may be more convenient to use one of the {@link Executors}
697     * factory methods instead of this general purpose constructor.
698 tim 1.1 *
699 dl 1.2 * @param corePoolSize the number of threads to keep in the
700 tim 1.1 * pool, even if they are idle.
701 dl 1.2 * @param maximumPoolSize the maximum number of threads to allow in the
702 tim 1.1 * pool.
703     * @param keepAliveTime when the number of threads is greater than
704 dl 1.2 * the core, this is the maximum time that excess idle threads
705 tim 1.1 * will wait for new tasks before terminating.
706 dl 1.2 * @param unit the time unit for the keepAliveTime
707 tim 1.1 * argument.
708 dl 1.36 * @param workQueue the queue to use for holding tasks before they
709 tim 1.1 * are executed. This queue will hold only the <tt>Runnable</tt>
710     * tasks submitted by the <tt>execute</tt> method.
711 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
712     * keepAliveTime less than zero, or if maximumPoolSize less than or
713     * equal to zero, or if corePoolSize greater than maximumPoolSize.
714 tim 1.1 * @throws NullPointerException if <tt>workQueue</tt> is null
715     */
716 dl 1.2 public ThreadPoolExecutor(int corePoolSize,
717     int maximumPoolSize,
718 tim 1.1 long keepAliveTime,
719 dl 1.2 TimeUnit unit,
720     BlockingQueue<Runnable> workQueue) {
721 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
722 dl 1.34 Executors.defaultThreadFactory(), defaultHandler);
723 dl 1.2 }
724 tim 1.1
725 dl 1.2 /**
726     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
727     * parameters.
728     *
729     * @param corePoolSize the number of threads to keep in the
730     * pool, even if they are idle.
731     * @param maximumPoolSize the maximum number of threads to allow in the
732     * pool.
733     * @param keepAliveTime when the number of threads is greater than
734     * the core, this is the maximum time that excess idle threads
735     * will wait for new tasks before terminating.
736     * @param unit the time unit for the keepAliveTime
737     * argument.
738 dl 1.36 * @param workQueue the queue to use for holding tasks before they
739 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
740     * tasks submitted by the <tt>execute</tt> method.
741     * @param threadFactory the factory to use when the executor
742 tim 1.10 * creates a new thread.
743 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
744     * keepAliveTime less than zero, or if maximumPoolSize less than or
745     * equal to zero, or if corePoolSize greater than maximumPoolSize.
746 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
747 dl 1.2 * or <tt>threadFactory</tt> are null.
748     */
749     public ThreadPoolExecutor(int corePoolSize,
750     int maximumPoolSize,
751     long keepAliveTime,
752     TimeUnit unit,
753     BlockingQueue<Runnable> workQueue,
754     ThreadFactory threadFactory) {
755 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
756 dl 1.2 threadFactory, defaultHandler);
757     }
758 tim 1.1
759 dl 1.2 /**
760     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
761     * parameters.
762     *
763     * @param corePoolSize the number of threads to keep in the
764     * pool, even if they are idle.
765     * @param maximumPoolSize the maximum number of threads to allow in the
766     * pool.
767     * @param keepAliveTime when the number of threads is greater than
768     * the core, this is the maximum time that excess idle threads
769     * will wait for new tasks before terminating.
770     * @param unit the time unit for the keepAliveTime
771     * argument.
772 dl 1.36 * @param workQueue the queue to use for holding tasks before they
773 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
774     * tasks submitted by the <tt>execute</tt> method.
775     * @param handler the handler to use when execution is blocked
776     * because the thread bounds and queue capacities are reached.
777     * @throws IllegalArgumentException if corePoolSize, or
778     * keepAliveTime less than zero, or if maximumPoolSize less than or
779     * equal to zero, or if corePoolSize greater than maximumPoolSize.
780 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
781 dl 1.2 * or <tt>handler</tt> are null.
782     */
783     public ThreadPoolExecutor(int corePoolSize,
784     int maximumPoolSize,
785     long keepAliveTime,
786     TimeUnit unit,
787     BlockingQueue<Runnable> workQueue,
788     RejectedExecutionHandler handler) {
789 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
790 dl 1.34 Executors.defaultThreadFactory(), handler);
791 dl 1.2 }
792 tim 1.1
793 dl 1.2 /**
794     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
795     * parameters.
796     *
797     * @param corePoolSize the number of threads to keep in the
798     * pool, even if they are idle.
799     * @param maximumPoolSize the maximum number of threads to allow in the
800     * pool.
801     * @param keepAliveTime when the number of threads is greater than
802     * the core, this is the maximum time that excess idle threads
803     * will wait for new tasks before terminating.
804     * @param unit the time unit for the keepAliveTime
805     * argument.
806 dl 1.36 * @param workQueue the queue to use for holding tasks before they
807 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
808     * tasks submitted by the <tt>execute</tt> method.
809     * @param threadFactory the factory to use when the executor
810 tim 1.10 * creates a new thread.
811 dl 1.2 * @param handler the handler to use when execution is blocked
812     * because the thread bounds and queue capacities are reached.
813     * @throws IllegalArgumentException if corePoolSize, or
814     * keepAliveTime less than zero, or if maximumPoolSize less than or
815     * equal to zero, or if corePoolSize greater than maximumPoolSize.
816 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
817 dl 1.2 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
818     */
819     public ThreadPoolExecutor(int corePoolSize,
820     int maximumPoolSize,
821     long keepAliveTime,
822     TimeUnit unit,
823     BlockingQueue<Runnable> workQueue,
824     ThreadFactory threadFactory,
825     RejectedExecutionHandler handler) {
826 tim 1.10 if (corePoolSize < 0 ||
827 dl 1.2 maximumPoolSize <= 0 ||
828 tim 1.10 maximumPoolSize < corePoolSize ||
829 dl 1.2 keepAliveTime < 0)
830     throw new IllegalArgumentException();
831     if (workQueue == null || threadFactory == null || handler == null)
832     throw new NullPointerException();
833     this.corePoolSize = corePoolSize;
834     this.maximumPoolSize = maximumPoolSize;
835     this.workQueue = workQueue;
836     this.keepAliveTime = unit.toNanos(keepAliveTime);
837     this.threadFactory = threadFactory;
838     this.handler = handler;
839 tim 1.1 }
840    
841 dl 1.2
842     /**
843     * Executes the given task sometime in the future. The task
844     * may execute in a new thread or in an existing pooled thread.
845     *
846     * If the task cannot be submitted for execution, either because this
847     * executor has been shutdown or because its capacity has been reached,
848 tim 1.10 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
849 dl 1.2 *
850     * @param command the task to execute
851     * @throws RejectedExecutionException at discretion of
852 dl 1.8 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
853     * for execution
854 dl 1.26 * @throws NullPointerException if command is null
855 dl 1.2 */
856 tim 1.10 public void execute(Runnable command) {
857 dl 1.26 if (command == null)
858     throw new NullPointerException();
859 dl 1.2 for (;;) {
860 dl 1.16 if (runState != RUNNING) {
861 dl 1.13 reject(command);
862 dl 1.2 return;
863     }
864     if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
865     return;
866     if (workQueue.offer(command))
867     return;
868     Runnable r = addIfUnderMaximumPoolSize(command);
869     if (r == command)
870     return;
871     if (r == null) {
872 dl 1.13 reject(command);
873 dl 1.2 return;
874     }
875     // else retry
876     }
877 tim 1.1 }
878 dl 1.4
879 dl 1.53 /**
880     * Initiates an orderly shutdown in which previously submitted
881     * tasks are executed, but no new tasks will be
882     * accepted. Invocation has no additional effect if already shut
883     * down.
884     * @throws SecurityException if a security manager exists and
885     * shutting down this ExecutorService may manipulate threads that
886     * the caller is not permitted to modify because it does not hold
887     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
888     * or the security manager's <tt>checkAccess</tt> method denies access.
889     */
890 dl 1.2 public void shutdown() {
891 dl 1.58 // Fail if caller doesn't have modifyThread permission. We
892 dl 1.60 // explicitly check permissions directly because we can't trust
893 dl 1.58 // implementations of SecurityManager to correctly override
894     // the "check access" methods such that our documented
895     // security policy is implemented.
896 dl 1.42 SecurityManager security = System.getSecurityManager();
897     if (security != null)
898 dl 1.43 java.security.AccessController.checkPermission(shutdownPerm);
899 dl 1.42
900 dl 1.25 boolean fullyTerminated = false;
901 dl 1.45 final ReentrantLock mainLock = this.mainLock;
902 dl 1.2 mainLock.lock();
903     try {
904 dl 1.25 if (workers.size() > 0) {
905 dl 1.50 // Check if caller can modify worker threads. This
906     // might not be true even if passed above check, if
907     // the SecurityManager treats some threads specially.
908 dl 1.43 if (security != null) {
909     for (Worker w: workers)
910     security.checkAccess(w.thread);
911     }
912    
913     int state = runState;
914     if (state == RUNNING) // don't override shutdownNow
915 dl 1.25 runState = SHUTDOWN;
916 dl 1.43
917     try {
918     for (Worker w: workers)
919     w.interruptIfIdle();
920     } catch(SecurityException se) {
921 dl 1.50 // If SecurityManager allows above checks, but
922     // then unexpectedly throws exception when
923     // interrupting threads (which it ought not do),
924     // back out as cleanly as we can. Some threads may
925     // have been killed but we remain in non-shutdown
926     // state.
927 dl 1.43 runState = state;
928     throw se;
929     }
930 dl 1.25 }
931     else { // If no workers, trigger full termination now
932     fullyTerminated = true;
933     runState = TERMINATED;
934     termination.signalAll();
935     }
936 tim 1.14 } finally {
937 dl 1.2 mainLock.unlock();
938     }
939 dl 1.25 if (fullyTerminated)
940     terminated();
941 tim 1.1 }
942    
943 dl 1.16
944 dl 1.53 /**
945     * Attempts to stop all actively executing tasks, halts the
946     * processing of waiting tasks, and returns a list of the tasks that were
947     * awaiting execution.
948     *
949     * <p>This implementation cancels tasks via {@link
950     * Thread#interrupt}, so if any tasks mask or fail to respond to
951     * interrupts, they may never terminate.
952     *
953     * @return list of tasks that never commenced execution
954     * @throws SecurityException if a security manager exists and
955     * shutting down this ExecutorService may manipulate threads that
956     * the caller is not permitted to modify because it does not hold
957     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
958     * or the security manager's <tt>checkAccess</tt> method denies access.
959     */
960 tim 1.39 public List<Runnable> shutdownNow() {
961 dl 1.43 // Almost the same code as shutdown()
962 dl 1.42 SecurityManager security = System.getSecurityManager();
963     if (security != null)
964 dl 1.43 java.security.AccessController.checkPermission(shutdownPerm);
965    
966 dl 1.25 boolean fullyTerminated = false;
967 dl 1.45 final ReentrantLock mainLock = this.mainLock;
968 dl 1.2 mainLock.lock();
969     try {
970 dl 1.25 if (workers.size() > 0) {
971 dl 1.43 if (security != null) {
972     for (Worker w: workers)
973     security.checkAccess(w.thread);
974     }
975    
976     int state = runState;
977     if (state != TERMINATED)
978 dl 1.25 runState = STOP;
979 dl 1.43 try {
980     for (Worker w : workers)
981     w.interruptNow();
982     } catch(SecurityException se) {
983     runState = state; // back out;
984     throw se;
985     }
986 dl 1.25 }
987     else { // If no workers, trigger full termination now
988     fullyTerminated = true;
989     runState = TERMINATED;
990     termination.signalAll();
991     }
992 tim 1.14 } finally {
993 dl 1.2 mainLock.unlock();
994     }
995 dl 1.25 if (fullyTerminated)
996     terminated();
997 tim 1.41 return Arrays.asList(workQueue.toArray(EMPTY_RUNNABLE_ARRAY));
998 tim 1.1 }
999    
1000 dl 1.2 public boolean isShutdown() {
1001 dl 1.16 return runState != RUNNING;
1002     }
1003    
1004     /**
1005 dl 1.55 * Returns true if this executor is in the process of terminating
1006 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1007     * completely terminated. This method may be useful for
1008     * debugging. A return of <tt>true</tt> reported a sufficient
1009     * period after shutdown may indicate that submitted tasks have
1010     * ignored or suppressed interruption, causing this executor not
1011     * to properly terminate.
1012     * @return true if terminating but not yet terminated.
1013     */
1014     public boolean isTerminating() {
1015     return runState == STOP;
1016 tim 1.1 }
1017    
1018 dl 1.2 public boolean isTerminated() {
1019 dl 1.16 return runState == TERMINATED;
1020 dl 1.2 }
1021 tim 1.1
1022 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1023     throws InterruptedException {
1024 dl 1.50 long nanos = unit.toNanos(timeout);
1025 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1026 dl 1.2 mainLock.lock();
1027     try {
1028 dl 1.25 for (;;) {
1029     if (runState == TERMINATED)
1030     return true;
1031     if (nanos <= 0)
1032     return false;
1033     nanos = termination.awaitNanos(nanos);
1034     }
1035 tim 1.14 } finally {
1036 dl 1.2 mainLock.unlock();
1037     }
1038 dl 1.15 }
1039    
1040     /**
1041     * Invokes <tt>shutdown</tt> when this executor is no longer
1042     * referenced.
1043     */
1044     protected void finalize() {
1045     shutdown();
1046 dl 1.2 }
1047 tim 1.10
1048 dl 1.2 /**
1049     * Sets the thread factory used to create new threads.
1050     *
1051     * @param threadFactory the new thread factory
1052 dl 1.30 * @throws NullPointerException if threadFactory is null
1053 tim 1.11 * @see #getThreadFactory
1054 dl 1.2 */
1055     public void setThreadFactory(ThreadFactory threadFactory) {
1056 dl 1.30 if (threadFactory == null)
1057     throw new NullPointerException();
1058 dl 1.2 this.threadFactory = threadFactory;
1059 tim 1.1 }
1060    
1061 dl 1.2 /**
1062     * Returns the thread factory used to create new threads.
1063     *
1064     * @return the current thread factory
1065 tim 1.11 * @see #setThreadFactory
1066 dl 1.2 */
1067     public ThreadFactory getThreadFactory() {
1068     return threadFactory;
1069 tim 1.1 }
1070    
1071 dl 1.2 /**
1072     * Sets a new handler for unexecutable tasks.
1073     *
1074     * @param handler the new handler
1075 dl 1.31 * @throws NullPointerException if handler is null
1076 tim 1.11 * @see #getRejectedExecutionHandler
1077 dl 1.2 */
1078     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1079 dl 1.31 if (handler == null)
1080     throw new NullPointerException();
1081 dl 1.2 this.handler = handler;
1082     }
1083 tim 1.1
1084 dl 1.2 /**
1085     * Returns the current handler for unexecutable tasks.
1086     *
1087     * @return the current handler
1088 tim 1.11 * @see #setRejectedExecutionHandler
1089 dl 1.2 */
1090     public RejectedExecutionHandler getRejectedExecutionHandler() {
1091     return handler;
1092 tim 1.1 }
1093    
1094 dl 1.2 /**
1095 dl 1.17 * Returns the task queue used by this executor. Access to the
1096     * task queue is intended primarily for debugging and monitoring.
1097 dl 1.27 * This queue may be in active use. Retrieving the task queue
1098 dl 1.2 * does not prevent queued tasks from executing.
1099     *
1100     * @return the task queue
1101     */
1102     public BlockingQueue<Runnable> getQueue() {
1103     return workQueue;
1104 tim 1.1 }
1105 dl 1.4
1106     /**
1107 dl 1.44 * Removes this task from the executor's internal queue if it is
1108     * present, thus causing it not to be run if it has not already
1109     * started.
1110     *
1111     * <p> This method may be useful as one part of a cancellation
1112     * scheme. It may fail to remove tasks that have been converted
1113     * into other forms before being placed on the internal queue. For
1114     * example, a task entered using <tt>submit</tt> might be
1115     * converted into a form that maintains <tt>Future</tt> status.
1116     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1117     * may be used to remove those Futures that have been cancelled.
1118     *
1119 tim 1.10 *
1120 dl 1.8 * @param task the task to remove
1121     * @return true if the task was removed
1122 dl 1.4 */
1123 dl 1.5 public boolean remove(Runnable task) {
1124 dl 1.4 return getQueue().remove(task);
1125     }
1126    
1127 dl 1.7
1128     /**
1129 dl 1.37 * Tries to remove from the work queue all {@link Future}
1130 dl 1.16 * tasks that have been cancelled. This method can be useful as a
1131     * storage reclamation operation, that has no other impact on
1132     * functionality. Cancelled tasks are never executed, but may
1133     * accumulate in work queues until worker threads can actively
1134     * remove them. Invoking this method instead tries to remove them now.
1135 dl 1.23 * However, this method may fail to remove tasks in
1136 dl 1.16 * the presence of interference by other threads.
1137 dl 1.7 */
1138     public void purge() {
1139 dl 1.16 // Fail if we encounter interference during traversal
1140     try {
1141     Iterator<Runnable> it = getQueue().iterator();
1142     while (it.hasNext()) {
1143     Runnable r = it.next();
1144 dl 1.37 if (r instanceof Future<?>) {
1145     Future<?> c = (Future<?>)r;
1146 dl 1.16 if (c.isCancelled())
1147     it.remove();
1148     }
1149 dl 1.7 }
1150     }
1151 dl 1.16 catch(ConcurrentModificationException ex) {
1152     return;
1153     }
1154 dl 1.7 }
1155 tim 1.1
1156     /**
1157 dl 1.2 * Sets the core number of threads. This overrides any value set
1158     * in the constructor. If the new value is smaller than the
1159     * current value, excess existing threads will be terminated when
1160 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1161     * be started to execute any queued tasks.
1162 tim 1.1 *
1163 dl 1.2 * @param corePoolSize the new core size
1164 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1165 dl 1.8 * less than zero
1166 tim 1.11 * @see #getCorePoolSize
1167 tim 1.1 */
1168 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1169     if (corePoolSize < 0)
1170     throw new IllegalArgumentException();
1171 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1172 dl 1.2 mainLock.lock();
1173     try {
1174     int extra = this.corePoolSize - corePoolSize;
1175     this.corePoolSize = corePoolSize;
1176 tim 1.38 if (extra < 0) {
1177 dl 1.56 int n = workQueue.size();
1178     // We have to create initially-idle threads here
1179     // because we otherwise have no recourse about
1180     // what to do with a dequeued task if addThread fails.
1181     while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize ) {
1182     Thread t = addThread(null);
1183     if (t != null)
1184     t.start();
1185     else
1186     break;
1187     }
1188 tim 1.38 }
1189     else if (extra > 0 && poolSize > corePoolSize) {
1190 dl 1.2 Iterator<Worker> it = workers.iterator();
1191 tim 1.10 while (it.hasNext() &&
1192 dl 1.34 extra-- > 0 &&
1193 dl 1.2 poolSize > corePoolSize &&
1194 dl 1.34 workQueue.remainingCapacity() == 0)
1195 dl 1.2 it.next().interruptIfIdle();
1196     }
1197 tim 1.14 } finally {
1198 dl 1.2 mainLock.unlock();
1199     }
1200     }
1201 tim 1.1
1202     /**
1203 dl 1.2 * Returns the core number of threads.
1204 tim 1.1 *
1205 dl 1.2 * @return the core number of threads
1206 tim 1.11 * @see #setCorePoolSize
1207 tim 1.1 */
1208 tim 1.10 public int getCorePoolSize() {
1209 dl 1.2 return corePoolSize;
1210 dl 1.16 }
1211    
1212     /**
1213 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1214 dl 1.16 * overrides the default policy of starting core threads only when
1215     * new tasks are executed. This method will return <tt>false</tt>
1216     * if all core threads have already been started.
1217     * @return true if a thread was started
1218     */
1219     public boolean prestartCoreThread() {
1220     return addIfUnderCorePoolSize(null);
1221     }
1222    
1223     /**
1224 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1225 dl 1.16 * overrides the default policy of starting core threads only when
1226     * new tasks are executed.
1227     * @return the number of threads started.
1228     */
1229     public int prestartAllCoreThreads() {
1230     int n = 0;
1231     while (addIfUnderCorePoolSize(null))
1232     ++n;
1233     return n;
1234 dl 1.2 }
1235 tim 1.1
1236     /**
1237 dl 1.62 * Returns true if this pool allows core threads to time out and
1238     * terminate if no tasks arrive within the keepAlive time, being
1239     * replaced if needed when new tasks arrive. When true, the same
1240     * keep-alive policy applying to non-core threads applies also to
1241     * core threads. When false (the default), core threads are never
1242     * terminated due to lack of incoming tasks.
1243     * @return <tt>true</tt> if core threads are allowed to time out,
1244     * else <tt>false</tt>
1245     */
1246     public boolean allowsCoreThreadTimeOut() {
1247     return allowCoreThreadTimeOut;
1248     }
1249    
1250     /**
1251     * Sets the policy governing whether core threads may time out and
1252     * terminate if no tasks arrive within the keep-alive time, being
1253     * replaced if needed when new tasks arrive. When false, core
1254     * threads are never terminated due to lack of incoming
1255     * tasks. When true, the same keep-alive policy applying to
1256     * non-core threads applies also to core threads. To avoid
1257     * continual thread replacement, the keep-alive time must be
1258     * greater than zero when setting <tt>true</tt>.
1259     * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1260     */
1261     public void allowCoreThreadTimeOut(boolean value) {
1262     allowCoreThreadTimeOut = value;
1263     }
1264    
1265     /**
1266 tim 1.1 * Sets the maximum allowed number of threads. This overrides any
1267 dl 1.2 * value set in the constructor. If the new value is smaller than
1268     * the current value, excess existing threads will be
1269     * terminated when they next become idle.
1270 tim 1.1 *
1271 dl 1.2 * @param maximumPoolSize the new maximum
1272     * @throws IllegalArgumentException if maximumPoolSize less than zero or
1273     * the {@link #getCorePoolSize core pool size}
1274 tim 1.11 * @see #getMaximumPoolSize
1275 dl 1.2 */
1276     public void setMaximumPoolSize(int maximumPoolSize) {
1277     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1278     throw new IllegalArgumentException();
1279 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1280 dl 1.2 mainLock.lock();
1281     try {
1282     int extra = this.maximumPoolSize - maximumPoolSize;
1283     this.maximumPoolSize = maximumPoolSize;
1284     if (extra > 0 && poolSize > maximumPoolSize) {
1285     Iterator<Worker> it = workers.iterator();
1286 tim 1.10 while (it.hasNext() &&
1287     extra > 0 &&
1288 dl 1.2 poolSize > maximumPoolSize) {
1289     it.next().interruptIfIdle();
1290     --extra;
1291     }
1292     }
1293 tim 1.14 } finally {
1294 dl 1.2 mainLock.unlock();
1295     }
1296     }
1297 tim 1.1
1298     /**
1299     * Returns the maximum allowed number of threads.
1300     *
1301 dl 1.2 * @return the maximum allowed number of threads
1302 tim 1.11 * @see #setMaximumPoolSize
1303 tim 1.1 */
1304 tim 1.10 public int getMaximumPoolSize() {
1305 dl 1.2 return maximumPoolSize;
1306     }
1307 tim 1.1
1308     /**
1309     * Sets the time limit for which threads may remain idle before
1310 dl 1.2 * being terminated. If there are more than the core number of
1311 tim 1.1 * threads currently in the pool, after waiting this amount of
1312     * time without processing a task, excess threads will be
1313     * terminated. This overrides any value set in the constructor.
1314     * @param time the time to wait. A time value of zero will cause
1315     * excess threads to terminate immediately after executing tasks.
1316 dl 1.2 * @param unit the time unit of the time argument
1317 dl 1.17 * @throws IllegalArgumentException if time less than zero
1318 tim 1.11 * @see #getKeepAliveTime
1319 tim 1.1 */
1320 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1321     if (time < 0)
1322     throw new IllegalArgumentException();
1323     this.keepAliveTime = unit.toNanos(time);
1324     }
1325 tim 1.1
1326     /**
1327     * Returns the thread keep-alive time, which is the amount of time
1328 dl 1.2 * which threads in excess of the core pool size may remain
1329 tim 1.10 * idle before being terminated.
1330 tim 1.1 *
1331 dl 1.2 * @param unit the desired time unit of the result
1332 tim 1.1 * @return the time limit
1333 tim 1.11 * @see #setKeepAliveTime
1334 tim 1.1 */
1335 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1336 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1337     }
1338 tim 1.1
1339     /* Statistics */
1340    
1341     /**
1342     * Returns the current number of threads in the pool.
1343     *
1344     * @return the number of threads
1345     */
1346 tim 1.10 public int getPoolSize() {
1347 dl 1.2 return poolSize;
1348     }
1349 tim 1.1
1350     /**
1351 dl 1.2 * Returns the approximate number of threads that are actively
1352 tim 1.1 * executing tasks.
1353     *
1354     * @return the number of threads
1355     */
1356 tim 1.10 public int getActiveCount() {
1357 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1358 dl 1.2 mainLock.lock();
1359     try {
1360     int n = 0;
1361 tim 1.39 for (Worker w : workers) {
1362     if (w.isActive())
1363 dl 1.2 ++n;
1364     }
1365     return n;
1366 tim 1.14 } finally {
1367 dl 1.2 mainLock.unlock();
1368     }
1369     }
1370 tim 1.1
1371     /**
1372 dl 1.2 * Returns the largest number of threads that have ever
1373     * simultaneously been in the pool.
1374 tim 1.1 *
1375     * @return the number of threads
1376     */
1377 tim 1.10 public int getLargestPoolSize() {
1378 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1379 dl 1.2 mainLock.lock();
1380     try {
1381     return largestPoolSize;
1382 tim 1.14 } finally {
1383 dl 1.2 mainLock.unlock();
1384     }
1385     }
1386 tim 1.1
1387     /**
1388 dl 1.2 * Returns the approximate total number of tasks that have been
1389     * scheduled for execution. Because the states of tasks and
1390     * threads may change dynamically during computation, the returned
1391 dl 1.17 * value is only an approximation, but one that does not ever
1392     * decrease across successive calls.
1393 tim 1.1 *
1394     * @return the number of tasks
1395     */
1396 tim 1.10 public long getTaskCount() {
1397 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1398 dl 1.2 mainLock.lock();
1399     try {
1400     long n = completedTaskCount;
1401 tim 1.39 for (Worker w : workers) {
1402 dl 1.2 n += w.completedTasks;
1403     if (w.isActive())
1404     ++n;
1405     }
1406     return n + workQueue.size();
1407 tim 1.14 } finally {
1408 dl 1.2 mainLock.unlock();
1409     }
1410     }
1411 tim 1.1
1412     /**
1413 dl 1.2 * Returns the approximate total number of tasks that have
1414     * completed execution. Because the states of tasks and threads
1415     * may change dynamically during computation, the returned value
1416 dl 1.17 * is only an approximation, but one that does not ever decrease
1417     * across successive calls.
1418 tim 1.1 *
1419     * @return the number of tasks
1420     */
1421 tim 1.10 public long getCompletedTaskCount() {
1422 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1423 dl 1.2 mainLock.lock();
1424     try {
1425     long n = completedTaskCount;
1426 tim 1.39 for (Worker w : workers)
1427     n += w.completedTasks;
1428 dl 1.2 return n;
1429 tim 1.14 } finally {
1430 dl 1.2 mainLock.unlock();
1431     }
1432     }
1433 tim 1.1
1434     /**
1435 dl 1.17 * Method invoked prior to executing the given Runnable in the
1436 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1437     * will execute task <tt>r</tt>, and may be used to re-initialize
1438 dl 1.17 * ThreadLocals, or to perform logging. Note: To properly nest
1439     * multiple overridings, subclasses should generally invoke
1440 dl 1.5 * <tt>super.beforeExecute</tt> at the end of this method.
1441 tim 1.1 *
1442 dl 1.2 * @param t the thread that will run task r.
1443     * @param r the task that will be executed.
1444 tim 1.1 */
1445 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1446 tim 1.1
1447     /**
1448 dl 1.2 * Method invoked upon completion of execution of the given
1449 dl 1.43 * Runnable. This method is invoked by the thread that executed
1450     * the task. If non-null, the Throwable is the uncaught exception
1451 dl 1.5 * that caused execution to terminate abruptly. Note: To properly
1452     * nest multiple overridings, subclasses should generally invoke
1453     * <tt>super.afterExecute</tt> at the beginning of this method.
1454 tim 1.1 *
1455 dl 1.2 * @param r the runnable that has completed.
1456 dl 1.24 * @param t the exception that caused termination, or null if
1457 dl 1.2 * execution completed normally.
1458 tim 1.1 */
1459 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1460 tim 1.1
1461 dl 1.2 /**
1462     * Method invoked when the Executor has terminated. Default
1463 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1464     * overridings, subclasses should generally invoke
1465     * <tt>super.terminated</tt> within this method.
1466 dl 1.2 */
1467     protected void terminated() { }
1468 tim 1.1
1469     /**
1470 dl 1.21 * A handler for rejected tasks that runs the rejected task
1471     * directly in the calling thread of the <tt>execute</tt> method,
1472     * unless the executor has been shut down, in which case the task
1473     * is discarded.
1474 tim 1.1 */
1475 dl 1.2 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1476 tim 1.1 /**
1477 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1478 tim 1.1 */
1479     public CallerRunsPolicy() { }
1480    
1481 dl 1.24 /**
1482     * Executes task r in the caller's thread, unless the executor
1483     * has been shut down, in which case the task is discarded.
1484     * @param r the runnable task requested to be executed
1485     * @param e the executor attempting to execute this task
1486     */
1487 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1488     if (!e.isShutdown()) {
1489 tim 1.1 r.run();
1490     }
1491     }
1492     }
1493    
1494     /**
1495 dl 1.21 * A handler for rejected tasks that throws a
1496 dl 1.8 * <tt>RejectedExecutionException</tt>.
1497 tim 1.1 */
1498 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1499 tim 1.1 /**
1500 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1501 tim 1.1 */
1502     public AbortPolicy() { }
1503    
1504 dl 1.24 /**
1505 dl 1.54 * Always throws RejectedExecutionException.
1506 dl 1.24 * @param r the runnable task requested to be executed
1507     * @param e the executor attempting to execute this task
1508     * @throws RejectedExecutionException always.
1509     */
1510 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1511     throw new RejectedExecutionException();
1512 tim 1.1 }
1513     }
1514    
1515     /**
1516 dl 1.21 * A handler for rejected tasks that silently discards the
1517     * rejected task.
1518 tim 1.1 */
1519 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1520 tim 1.1 /**
1521 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1522 tim 1.1 */
1523     public DiscardPolicy() { }
1524    
1525 dl 1.24 /**
1526     * Does nothing, which has the effect of discarding task r.
1527     * @param r the runnable task requested to be executed
1528     * @param e the executor attempting to execute this task
1529     */
1530 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1531 tim 1.1 }
1532     }
1533    
1534     /**
1535 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1536     * request and then retries <tt>execute</tt>, unless the executor
1537     * is shut down, in which case the task is discarded.
1538 tim 1.1 */
1539 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1540 tim 1.1 /**
1541 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1542 tim 1.1 */
1543     public DiscardOldestPolicy() { }
1544    
1545 dl 1.24 /**
1546     * Obtains and ignores the next task that the executor
1547     * would otherwise execute, if one is immediately available,
1548     * and then retries execution of task r, unless the executor
1549     * is shut down, in which case task r is instead discarded.
1550     * @param r the runnable task requested to be executed
1551     * @param e the executor attempting to execute this task
1552     */
1553 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1554     if (!e.isShutdown()) {
1555     e.getQueue().poll();
1556     e.execute(r);
1557 tim 1.1 }
1558     }
1559     }
1560     }