ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.82
Committed: Thu Jun 8 10:58:00 2006 UTC (17 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.81: +1 -1 lines
Log Message:
allowCoreTimeout should be volatile

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