ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.75
Committed: Sat Aug 27 22:44:54 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.74: +6 -5 lines
Log Message:
un-masking docstrings

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