ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.85
Committed: Fri Jun 16 18:49:43 2006 UTC (17 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.84: +147 -108 lines
Log Message:
Improve shutdownNow guarantees

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.85
294     /*
295     * A TPE manages a largish set of control fields, mainly runState,
296     * poolSize, corePoolSize, maximumPoolSize. In general, state
297     * changes only occur within mainLock regions, but nearly all
298     * fields are volatile, so can be read outside of locked
299     * regions. This enables the most performance-critical actions,
300     * such as enqueuing and dequeing tasks in workQueue, to normally
301     * proceed without holding this lock when they see that the state
302     * allows actions. This sometimes requires a form of double-check.
303     * For example when it appears that poolSize is less than
304     * corePoolSize, addIfUnderCorePoolSize is called, which checks
305     * sizes and runState under the lock before actually creating a
306     * new thread.
307     *
308     * The main lifecyle control is via runState, taking on values:
309     * RUNNING: Accept new tasks and process queued tasks
310     * SHUTDOWN: Don't accept new tasks, but process queued tasks
311     * STOP: Don't accept new tasks, don't process queued tasks,
312     * and interrupt in-progress tasks
313     * TERMINATED: Same as stop, plus all threads have terminated
314     * with transitions:
315     *
316     * RUNNING -> SHUTDOWN
317     * On invocation of shutdown() when pool or queue nonempty
318     * {RUNNING or SHUTDOWN} -> STOP
319     * On invocation of shutdownNow() when pool or queue nonempty
320     * {SHUTDOWN or STOP} -> TERMINATED
321     * When both queue and pool become empty
322     * RUNNING -> TERMINATED
323     * On invocation of shutdown when both queue and pool empty
324     * (This bypasses creating a new thread just to cause termination)
325     *
326 tim 1.41 */
327    
328     /**
329 dl 1.43 * Permission for checking shutdown
330     */
331     private static final RuntimePermission shutdownPerm =
332     new RuntimePermission("modifyThread");
333    
334     /**
335 dl 1.2 * Queue used for holding tasks and handing off to worker threads.
336 tim 1.10 */
337 dl 1.2 private final BlockingQueue<Runnable> workQueue;
338    
339     /**
340 dl 1.85 * Lock held on updates to poolSize, corePoolSize,
341     * maximumPoolSize, runState, and workers set.
342 tim 1.10 */
343 dl 1.2 private final ReentrantLock mainLock = new ReentrantLock();
344    
345     /**
346     * Wait condition to support awaitTermination
347 tim 1.10 */
348 dl 1.46 private final Condition termination = mainLock.newCondition();
349 dl 1.2
350     /**
351     * Set containing all worker threads in pool.
352 tim 1.10 */
353 dl 1.17 private final HashSet<Worker> workers = new HashSet<Worker>();
354 dl 1.2
355     /**
356 dl 1.35 * Timeout in nanoseconds for idle threads waiting for work.
357 dl 1.2 * Threads use this timeout only when there are more than
358     * corePoolSize present. Otherwise they wait forever for new work.
359 tim 1.10 */
360 dl 1.2 private volatile long keepAliveTime;
361    
362     /**
363 dl 1.62 * If false (default) core threads stay alive even when idle.
364     * If true, core threads use keepAliveTime to time out waiting for work.
365     */
366 dl 1.82 private volatile boolean allowCoreThreadTimeOut;
367 dl 1.62
368     /**
369 dl 1.2 * Core pool size, updated only while holding mainLock,
370     * but volatile to allow concurrent readability even
371     * during updates.
372 tim 1.10 */
373 dl 1.2 private volatile int corePoolSize;
374    
375     /**
376     * Maximum pool size, updated only while holding mainLock
377     * but volatile to allow concurrent readability even
378     * during updates.
379 tim 1.10 */
380 dl 1.2 private volatile int maximumPoolSize;
381    
382     /**
383     * Current pool size, updated only while holding mainLock
384     * but volatile to allow concurrent readability even
385     * during updates.
386 tim 1.10 */
387 dl 1.2 private volatile int poolSize;
388    
389     /**
390 dl 1.16 * Lifecycle state
391 tim 1.10 */
392 dl 1.52 volatile int runState;
393 dl 1.2
394 dl 1.85 /*
395     * Special values for runState. The numerical order among values
396     * matters. The runState monotonically increases over time, but
397     * need not hit each state.
398     */
399 dl 1.8 /** Normal, not-shutdown mode */
400 dl 1.52 static final int RUNNING = 0;
401 dl 1.8 /** Controlled shutdown mode */
402 dl 1.52 static final int SHUTDOWN = 1;
403 dl 1.16 /** Immediate shutdown mode */
404 dl 1.52 static final int STOP = 2;
405 dl 1.16 /** Final state */
406 dl 1.52 static final int TERMINATED = 3;
407 dl 1.2
408     /**
409     * Handler called when saturated or shutdown in execute.
410 tim 1.10 */
411 dl 1.33 private volatile RejectedExecutionHandler handler;
412 dl 1.2
413     /**
414     * Factory for new threads.
415 tim 1.10 */
416 dl 1.33 private volatile ThreadFactory threadFactory;
417 dl 1.2
418     /**
419     * Tracks largest attained pool size.
420 tim 1.10 */
421 dl 1.2 private int largestPoolSize;
422    
423     /**
424     * Counter for completed tasks. Updated only on termination of
425     * worker threads.
426 tim 1.10 */
427 dl 1.2 private long completedTaskCount;
428 jsr166 1.66
429 dl 1.8 /**
430 dl 1.35 * The default rejected execution handler
431 dl 1.8 */
432 tim 1.10 private static final RejectedExecutionHandler defaultHandler =
433 dl 1.2 new AbortPolicy();
434    
435     /**
436 jsr166 1.66 * Invokes the rejected execution handler for the given command.
437 dl 1.13 */
438     void reject(Runnable command) {
439     handler.rejectedExecution(command, this);
440     }
441    
442 dl 1.33 /**
443 jsr166 1.66 * Creates and returns a new thread running firstTask as its first
444     * task. Call only while holding mainLock.
445 dl 1.8 * @param firstTask the task the new thread should run first (or
446     * null if none)
447 dl 1.56 * @return the new thread, or null if threadFactory fails to create thread
448 dl 1.2 */
449     private Thread addThread(Runnable firstTask) {
450     Worker w = new Worker(firstTask);
451 dl 1.57 Thread t = threadFactory.newThread(w);
452 dl 1.56 if (t != null) {
453     w.thread = t;
454     workers.add(w);
455     int nt = ++poolSize;
456     if (nt > largestPoolSize)
457     largestPoolSize = nt;
458     }
459 dl 1.2 return t;
460     }
461 dl 1.15
462 dl 1.2 /**
463 jsr166 1.66 * Creates and starts a new thread running firstTask as its first
464 dl 1.50 * task, only if fewer than corePoolSize threads are running.
465 dl 1.8 * @param firstTask the task the new thread should run first (or
466     * null if none)
467 dl 1.2 * @return true if successful.
468     */
469 dl 1.16 private boolean addIfUnderCorePoolSize(Runnable firstTask) {
470 dl 1.2 Thread t = null;
471 dl 1.45 final ReentrantLock mainLock = this.mainLock;
472 dl 1.2 mainLock.lock();
473     try {
474 dl 1.85 if (poolSize < corePoolSize && runState == RUNNING)
475 dl 1.8 t = addThread(firstTask);
476 tim 1.14 } finally {
477 dl 1.2 mainLock.unlock();
478     }
479     if (t == null)
480     return false;
481     t.start();
482     return true;
483     }
484    
485     /**
486 jsr166 1.66 * Creates and starts a new thread only if fewer than maximumPoolSize
487 dl 1.2 * threads are running. The new thread runs as its first task the
488     * next task in queue, or if there is none, the given task.
489 dl 1.8 * @param firstTask the task the new thread should run first (or
490     * null if none)
491 dl 1.74 * @return 0 if a new thread cannot be created, a positive number
492     * if firstTask will be run in a new thread, or a negative number
493     * if a new thread was created but is running some other task, in
494     * which case the caller must try some other way to run firstTask
495     * (perhaps by calling this method again).
496 dl 1.2 */
497 dl 1.74 private int addIfUnderMaximumPoolSize(Runnable firstTask) {
498 dl 1.2 Thread t = null;
499 dl 1.74 int status = 0;
500 dl 1.45 final ReentrantLock mainLock = this.mainLock;
501 dl 1.2 mainLock.lock();
502     try {
503 dl 1.85 if (poolSize < maximumPoolSize && runState == RUNNING) {
504 dl 1.74 Runnable next = workQueue.poll();
505     if (next == null) {
506 dl 1.8 next = firstTask;
507 dl 1.74 status = 1;
508     } else
509     status = -1;
510 dl 1.2 t = addThread(next);
511     }
512 tim 1.14 } finally {
513 dl 1.2 mainLock.unlock();
514     }
515     if (t == null)
516 dl 1.74 return 0;
517 dl 1.2 t.start();
518 dl 1.74 return status;
519 dl 1.2 }
520    
521     /**
522 jsr166 1.66 * Gets the next task for a worker thread to run.
523 dl 1.8 * @return the task
524 dl 1.2 */
525 dl 1.63 Runnable getTask() {
526 dl 1.2 for (;;) {
527 dl 1.63 try {
528 jsr166 1.73 switch (runState) {
529 dl 1.63 case RUNNING: {
530     // untimed wait if core and not allowing core timeout
531     if (poolSize <= corePoolSize && !allowCoreThreadTimeOut)
532     return workQueue.take();
533 jsr166 1.66
534 dl 1.63 long timeout = keepAliveTime;
535     if (timeout <= 0) // die immediately for 0 timeout
536     return null;
537 jsr166 1.70 Runnable r = workQueue.poll(timeout, TimeUnit.NANOSECONDS);
538 dl 1.63 if (r != null)
539     return r;
540 jsr166 1.66 if (poolSize > corePoolSize || allowCoreThreadTimeOut)
541 dl 1.63 return null; // timed out
542     // Else, after timeout, the pool shrank. Retry
543     break;
544     }
545 jsr166 1.66
546 dl 1.63 case SHUTDOWN: {
547 jsr166 1.66 // Help drain queue
548 dl 1.63 Runnable r = workQueue.poll();
549     if (r != null)
550     return r;
551 jsr166 1.66
552 dl 1.63 // Check if can terminate
553     if (workQueue.isEmpty()) {
554     interruptIdleWorkers();
555     return null;
556     }
557 jsr166 1.66
558 dl 1.63 // Else there could still be delayed tasks in queue.
559 dl 1.16 return workQueue.take();
560 dl 1.63 }
561 jsr166 1.66
562 dl 1.85 default: // stopping/stopped
563 dl 1.16 return null;
564     }
565 jsr166 1.66 } catch (InterruptedException ie) {
566 dl 1.63 // On interruption, re-check runstate
567 dl 1.16 }
568     }
569     }
570    
571 dl 1.85
572     /**
573     * Rejects a task that was queued concurrently with a call to
574     * shutdownNow. If still present in the queue, this task must be
575     * removed and rejected to preserve shutdownNow guarantees.
576     * @param command the task
577     */
578     private void rejectIfQueued(Runnable command) {
579     final ReentrantLock mainLock = this.mainLock;
580     mainLock.lock();
581     boolean present;
582     try {
583     present = workQueue.remove(command);
584     } finally {
585     mainLock.unlock();
586     }
587     if (present)
588     reject(command);
589     }
590    
591 dl 1.16 /**
592 jsr166 1.66 * Wakes up all threads that might be waiting for tasks.
593 dl 1.16 */
594     void interruptIdleWorkers() {
595 dl 1.45 final ReentrantLock mainLock = this.mainLock;
596 dl 1.16 mainLock.lock();
597     try {
598 tim 1.39 for (Worker w : workers)
599     w.interruptIfIdle();
600 dl 1.16 } finally {
601     mainLock.unlock();
602 dl 1.2 }
603     }
604    
605     /**
606 jsr166 1.66 * Performs bookkeeping for a terminated worker thread.
607 tim 1.10 * @param w the worker
608 dl 1.2 */
609 dl 1.52 void workerDone(Worker w) {
610 dl 1.45 final ReentrantLock mainLock = this.mainLock;
611 dl 1.2 mainLock.lock();
612     try {
613     completedTaskCount += w.completedTasks;
614     workers.remove(w);
615 dl 1.85 if (--poolSize == 0) { // Deal with potential shutdown.
616     int state = runState;
617     // If not stopping and there are queued tasks but no
618     // threads, create replacement thread. We must create
619     // it initially idle to avoid orphaned tasks in case
620     // addThread fails. This also handles case of delayed
621     // tasks that will sometime later become runnable.
622     if (state < STOP && !workQueue.isEmpty()) {
623 dl 1.56 Thread t = addThread(null);
624     if (t != null)
625     t.start();
626 dl 1.85 state = RUNNING; // to cause termination check to fail
627     }
628     if (state == STOP || state == SHUTDOWN) { // can terminate
629     runState = TERMINATED;
630     termination.signalAll();
631     terminated();
632 dl 1.16 }
633 dl 1.2 }
634 tim 1.14 } finally {
635 dl 1.2 mainLock.unlock();
636     }
637     }
638    
639     /**
640 tim 1.10 * Worker threads
641 dl 1.2 */
642 dl 1.85 private final class Worker implements Runnable {
643 dl 1.2
644     /**
645     * The runLock is acquired and released surrounding each task
646     * execution. It mainly protects against interrupts that are
647     * intended to cancel the worker thread from instead
648     * interrupting the task being run.
649     */
650     private final ReentrantLock runLock = new ReentrantLock();
651    
652     /**
653     * Initial task to run before entering run loop
654     */
655     private Runnable firstTask;
656    
657     /**
658     * Per thread completed task counter; accumulated
659     * into completedTaskCount upon termination.
660     */
661     volatile long completedTasks;
662    
663     /**
664     * Thread this worker is running in. Acts as a final field,
665     * but cannot be set until thread is created.
666     */
667     Thread thread;
668    
669     Worker(Runnable firstTask) {
670     this.firstTask = firstTask;
671     }
672    
673     boolean isActive() {
674     return runLock.isLocked();
675     }
676    
677     /**
678 jsr166 1.73 * Interrupts thread if not running a task.
679 tim 1.10 */
680 dl 1.2 void interruptIfIdle() {
681 dl 1.45 final ReentrantLock runLock = this.runLock;
682 dl 1.2 if (runLock.tryLock()) {
683     try {
684     thread.interrupt();
685 tim 1.14 } finally {
686 dl 1.2 runLock.unlock();
687     }
688     }
689     }
690    
691     /**
692 jsr166 1.73 * Interrupts thread even if running a task.
693 tim 1.10 */
694 dl 1.2 void interruptNow() {
695     thread.interrupt();
696     }
697    
698     /**
699 jsr166 1.73 * Runs a single task between before/after methods.
700 dl 1.2 */
701     private void runTask(Runnable task) {
702 dl 1.45 final ReentrantLock runLock = this.runLock;
703 dl 1.2 runLock.lock();
704     try {
705 dl 1.81 // If not shutting down then clear an outstanding interrupt.
706 dl 1.85 if (runState < STOP &&
707 dl 1.81 Thread.interrupted() &&
708 dl 1.85 runState >= STOP) // Re-interrupt if stopped after clearing
709 dl 1.81 thread.interrupt();
710 dl 1.2 boolean ran = false;
711     beforeExecute(thread, task);
712     try {
713     task.run();
714     ran = true;
715     afterExecute(task, null);
716     ++completedTasks;
717 jsr166 1.66 } catch (RuntimeException ex) {
718 dl 1.2 if (!ran)
719     afterExecute(task, ex);
720 dl 1.17 // Else the exception occurred within
721 dl 1.2 // afterExecute itself in which case we don't
722     // want to call it again.
723     throw ex;
724     }
725 tim 1.14 } finally {
726 dl 1.2 runLock.unlock();
727     }
728     }
729    
730     /**
731     * Main run loop
732     */
733     public void run() {
734     try {
735 dl 1.50 Runnable task = firstTask;
736     firstTask = null;
737     while (task != null || (task = getTask()) != null) {
738 dl 1.2 runTask(task);
739 dl 1.85 task = null;
740 dl 1.2 }
741 tim 1.14 } finally {
742 dl 1.2 workerDone(this);
743     }
744     }
745     }
746 tim 1.1
747 dl 1.17 // Public methods
748    
749 tim 1.1 /**
750 jsr166 1.67 * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
751     * parameters and default thread factory and rejected execution handler.
752     * It may be more convenient to use one of the {@link Executors} factory
753     * methods instead of this general purpose constructor.
754 tim 1.1 *
755 dl 1.2 * @param corePoolSize the number of threads to keep in the
756 tim 1.1 * pool, even if they are idle.
757 dl 1.2 * @param maximumPoolSize the maximum number of threads to allow in the
758 tim 1.1 * pool.
759     * @param keepAliveTime when the number of threads is greater than
760 dl 1.2 * the core, this is the maximum time that excess idle threads
761 tim 1.1 * will wait for new tasks before terminating.
762 dl 1.2 * @param unit the time unit for the keepAliveTime
763 tim 1.1 * argument.
764 dl 1.36 * @param workQueue the queue to use for holding tasks before they
765 tim 1.1 * are executed. This queue will hold only the <tt>Runnable</tt>
766     * tasks submitted by the <tt>execute</tt> method.
767 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
768     * keepAliveTime less than zero, or if maximumPoolSize less than or
769     * equal to zero, or if corePoolSize greater than maximumPoolSize.
770 tim 1.1 * @throws NullPointerException if <tt>workQueue</tt> is null
771     */
772 dl 1.2 public ThreadPoolExecutor(int corePoolSize,
773     int maximumPoolSize,
774 tim 1.1 long keepAliveTime,
775 dl 1.2 TimeUnit unit,
776     BlockingQueue<Runnable> workQueue) {
777 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
778 dl 1.34 Executors.defaultThreadFactory(), defaultHandler);
779 dl 1.2 }
780 tim 1.1
781 dl 1.2 /**
782     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
783 jsr166 1.67 * parameters and default rejected execution handler.
784 dl 1.2 *
785     * @param corePoolSize the number of threads to keep in the
786     * pool, even if they are idle.
787     * @param maximumPoolSize the maximum number of threads to allow in the
788     * pool.
789     * @param keepAliveTime when the number of threads is greater than
790     * the core, this is the maximum time that excess idle threads
791     * will wait for new tasks before terminating.
792     * @param unit the time unit for the keepAliveTime
793     * argument.
794 dl 1.36 * @param workQueue the queue to use for holding tasks before they
795 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
796     * tasks submitted by the <tt>execute</tt> method.
797     * @param threadFactory the factory to use when the executor
798 tim 1.10 * creates a new thread.
799 dl 1.2 * @throws IllegalArgumentException if corePoolSize, or
800     * keepAliveTime less than zero, or if maximumPoolSize less than or
801     * equal to zero, or if corePoolSize greater than maximumPoolSize.
802 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
803 dl 1.2 * or <tt>threadFactory</tt> are null.
804     */
805     public ThreadPoolExecutor(int corePoolSize,
806     int maximumPoolSize,
807     long keepAliveTime,
808     TimeUnit unit,
809     BlockingQueue<Runnable> workQueue,
810     ThreadFactory threadFactory) {
811 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
812 dl 1.2 threadFactory, defaultHandler);
813     }
814 tim 1.1
815 dl 1.2 /**
816     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
817 jsr166 1.67 * parameters and default thread factory.
818 dl 1.2 *
819     * @param corePoolSize the number of threads to keep in the
820     * pool, even if they are idle.
821     * @param maximumPoolSize the maximum number of threads to allow in the
822     * pool.
823     * @param keepAliveTime when the number of threads is greater than
824     * the core, this is the maximum time that excess idle threads
825     * will wait for new tasks before terminating.
826     * @param unit the time unit for the keepAliveTime
827     * argument.
828 dl 1.36 * @param workQueue the queue to use for holding tasks before they
829 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
830     * tasks submitted by the <tt>execute</tt> method.
831     * @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 jsr166 1.68 * or <tt>handler</tt> are null.
838 dl 1.2 */
839     public ThreadPoolExecutor(int corePoolSize,
840     int maximumPoolSize,
841     long keepAliveTime,
842     TimeUnit unit,
843     BlockingQueue<Runnable> workQueue,
844     RejectedExecutionHandler handler) {
845 tim 1.10 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
846 dl 1.34 Executors.defaultThreadFactory(), handler);
847 dl 1.2 }
848 tim 1.1
849 dl 1.2 /**
850     * Creates a new <tt>ThreadPoolExecutor</tt> with the given initial
851     * parameters.
852     *
853     * @param corePoolSize the number of threads to keep in the
854     * pool, even if they are idle.
855     * @param maximumPoolSize the maximum number of threads to allow in the
856     * pool.
857     * @param keepAliveTime when the number of threads is greater than
858     * the core, this is the maximum time that excess idle threads
859     * will wait for new tasks before terminating.
860     * @param unit the time unit for the keepAliveTime
861     * argument.
862 dl 1.36 * @param workQueue the queue to use for holding tasks before they
863 dl 1.2 * are executed. This queue will hold only the <tt>Runnable</tt>
864     * tasks submitted by the <tt>execute</tt> method.
865     * @param threadFactory the factory to use when the executor
866 tim 1.10 * creates a new thread.
867 dl 1.2 * @param handler the handler to use when execution is blocked
868     * because the thread bounds and queue capacities are reached.
869     * @throws IllegalArgumentException if corePoolSize, or
870     * keepAliveTime less than zero, or if maximumPoolSize less than or
871     * equal to zero, or if corePoolSize greater than maximumPoolSize.
872 tim 1.10 * @throws NullPointerException if <tt>workQueue</tt>
873 dl 1.2 * or <tt>threadFactory</tt> or <tt>handler</tt> are null.
874     */
875     public ThreadPoolExecutor(int corePoolSize,
876     int maximumPoolSize,
877     long keepAliveTime,
878     TimeUnit unit,
879     BlockingQueue<Runnable> workQueue,
880     ThreadFactory threadFactory,
881     RejectedExecutionHandler handler) {
882 tim 1.10 if (corePoolSize < 0 ||
883 dl 1.2 maximumPoolSize <= 0 ||
884 tim 1.10 maximumPoolSize < corePoolSize ||
885 dl 1.2 keepAliveTime < 0)
886     throw new IllegalArgumentException();
887     if (workQueue == null || threadFactory == null || handler == null)
888     throw new NullPointerException();
889     this.corePoolSize = corePoolSize;
890     this.maximumPoolSize = maximumPoolSize;
891     this.workQueue = workQueue;
892     this.keepAliveTime = unit.toNanos(keepAliveTime);
893     this.threadFactory = threadFactory;
894     this.handler = handler;
895 tim 1.1 }
896    
897 dl 1.2 /**
898     * Executes the given task sometime in the future. The task
899     * may execute in a new thread or in an existing pooled thread.
900     *
901     * If the task cannot be submitted for execution, either because this
902     * executor has been shutdown or because its capacity has been reached,
903 tim 1.10 * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
904 dl 1.2 *
905     * @param command the task to execute
906     * @throws RejectedExecutionException at discretion of
907 dl 1.8 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
908     * for execution
909 dl 1.26 * @throws NullPointerException if command is null
910 dl 1.2 */
911 tim 1.10 public void execute(Runnable command) {
912 dl 1.26 if (command == null)
913     throw new NullPointerException();
914 dl 1.85 while (runState == RUNNING) {
915 dl 1.2 if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
916     return;
917 dl 1.85 if (workQueue.offer(command)) {// recheck state after queuing
918     if (runState != RUNNING)
919     rejectIfQueued(command);
920     else if (poolSize < corePoolSize)
921     addIfUnderCorePoolSize(null);
922 dl 1.2 return;
923 dl 1.85 }
924 dl 1.74 int status = addIfUnderMaximumPoolSize(command);
925 dl 1.85 if (status > 0) // Created new thread to handle task
926 dl 1.2 return;
927 dl 1.85 if (status == 0) // Cannot create thread
928     break;
929     // Retry if created thread but it is busy with another task
930 dl 1.2 }
931 dl 1.85
932     reject(command); // is shutdown or can't create thread or queue task
933     return;
934 tim 1.1 }
935 dl 1.4
936 dl 1.53 /**
937     * Initiates an orderly shutdown in which previously submitted
938     * tasks are executed, but no new tasks will be
939     * accepted. Invocation has no additional effect if already shut
940     * down.
941     * @throws SecurityException if a security manager exists and
942     * shutting down this ExecutorService may manipulate threads that
943     * the caller is not permitted to modify because it does not hold
944     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
945 jsr166 1.68 * or the security manager's <tt>checkAccess</tt> method denies access.
946 dl 1.53 */
947 dl 1.2 public void shutdown() {
948 jsr166 1.80 // Fail if caller doesn't have modifyThread permission.
949 dl 1.42 SecurityManager security = System.getSecurityManager();
950 jsr166 1.66 if (security != null)
951 dl 1.78 security.checkPermission(shutdownPerm);
952 dl 1.42
953 dl 1.45 final ReentrantLock mainLock = this.mainLock;
954 dl 1.2 mainLock.lock();
955     try {
956 dl 1.85 if (security != null) {
957 dl 1.50 // Check if caller can modify worker threads. This
958     // might not be true even if passed above check, if
959     // the SecurityManager treats some threads specially.
960 dl 1.85 for (Worker w: workers)
961     security.checkAccess(w.thread);
962     }
963 dl 1.43
964 dl 1.85 int state = runState;
965     if (state == RUNNING) // don't override shutdownNow
966     runState = SHUTDOWN;
967     int nworkers = 0;
968 dl 1.43
969 dl 1.85 try {
970     for (Worker w: workers) {
971     w.interruptIfIdle();
972     ++nworkers;
973 dl 1.43 }
974 dl 1.85 } catch (SecurityException se) {
975     // If SecurityManager allows above checks, but
976     // then unexpectedly throws exception when
977     // interrupting threads (which it ought not do),
978     // back out as cleanly as we can. Some threads may
979     // have been killed but we remain in non-shutdown
980     // state.
981     runState = state;
982     throw se;
983 dl 1.25 }
984 dl 1.85
985     // If no live workers, act on one's behalf to terminate
986     if (nworkers == 0 && state != TERMINATED) {
987 dl 1.25 runState = TERMINATED;
988     termination.signalAll();
989 dl 1.85 terminated();
990 dl 1.25 }
991 tim 1.14 } finally {
992 dl 1.2 mainLock.unlock();
993     }
994 tim 1.1 }
995    
996 dl 1.16
997 dl 1.53 /**
998     * Attempts to stop all actively executing tasks, halts the
999 jsr166 1.75 * processing of waiting tasks, and returns a list of the tasks
1000 dl 1.85 * that were awaiting execution. These tasks are drained (removed)
1001     * from the task queue upon return from this method.
1002 jsr166 1.66 *
1003 jsr166 1.75 * <p>There are no guarantees beyond best-effort attempts to stop
1004     * processing actively executing tasks. This implementation
1005     * cancels tasks via {@link Thread#interrupt}, so any task that
1006     * fails to respond to interrupts may never terminate.
1007 dl 1.53 *
1008     * @return list of tasks that never commenced execution
1009     * @throws SecurityException if a security manager exists and
1010     * shutting down this ExecutorService may manipulate threads that
1011     * the caller is not permitted to modify because it does not hold
1012     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
1013     * or the security manager's <tt>checkAccess</tt> method denies access.
1014     */
1015 tim 1.39 public List<Runnable> shutdownNow() {
1016 dl 1.43 // Almost the same code as shutdown()
1017 dl 1.42 SecurityManager security = System.getSecurityManager();
1018 jsr166 1.66 if (security != null)
1019 dl 1.78 security.checkPermission(shutdownPerm);
1020 dl 1.43
1021 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1022 dl 1.2 mainLock.lock();
1023     try {
1024 dl 1.85 if (security != null) {
1025     for (Worker w: workers)
1026     security.checkAccess(w.thread);
1027     }
1028 dl 1.43
1029 dl 1.85 int state = runState;
1030     if (state != TERMINATED)
1031     runState = STOP;
1032     int nworkers = 0;
1033     try {
1034     for (Worker w : workers) {
1035     w.interruptNow();
1036     ++nworkers;
1037 dl 1.43 }
1038 dl 1.85 } catch (SecurityException se) {
1039     runState = state; // back out;
1040     throw se;
1041 dl 1.25 }
1042 dl 1.85
1043     if (nworkers == 0 && state != TERMINATED) {
1044 dl 1.25 runState = TERMINATED;
1045     termination.signalAll();
1046 dl 1.85 terminated();
1047 dl 1.25 }
1048 dl 1.85
1049     List<Runnable> taskList = new ArrayList<Runnable>();
1050     workQueue.drainTo(taskList);
1051     return taskList;
1052 tim 1.14 } finally {
1053 dl 1.2 mainLock.unlock();
1054     }
1055 tim 1.1 }
1056    
1057 dl 1.2 public boolean isShutdown() {
1058 dl 1.16 return runState != RUNNING;
1059     }
1060    
1061 jsr166 1.66 /**
1062 dl 1.55 * Returns true if this executor is in the process of terminating
1063 dl 1.16 * after <tt>shutdown</tt> or <tt>shutdownNow</tt> but has not
1064     * completely terminated. This method may be useful for
1065     * debugging. A return of <tt>true</tt> reported a sufficient
1066     * period after shutdown may indicate that submitted tasks have
1067     * ignored or suppressed interruption, causing this executor not
1068     * to properly terminate.
1069     * @return true if terminating but not yet terminated.
1070     */
1071     public boolean isTerminating() {
1072     return runState == STOP;
1073 tim 1.1 }
1074    
1075 dl 1.2 public boolean isTerminated() {
1076 dl 1.16 return runState == TERMINATED;
1077 dl 1.2 }
1078 tim 1.1
1079 dl 1.2 public boolean awaitTermination(long timeout, TimeUnit unit)
1080     throws InterruptedException {
1081 dl 1.50 long nanos = unit.toNanos(timeout);
1082 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1083 dl 1.2 mainLock.lock();
1084     try {
1085 dl 1.25 for (;;) {
1086 jsr166 1.66 if (runState == TERMINATED)
1087 dl 1.25 return true;
1088     if (nanos <= 0)
1089     return false;
1090     nanos = termination.awaitNanos(nanos);
1091     }
1092 tim 1.14 } finally {
1093 dl 1.2 mainLock.unlock();
1094     }
1095 dl 1.15 }
1096    
1097     /**
1098     * Invokes <tt>shutdown</tt> when this executor is no longer
1099     * referenced.
1100 jsr166 1.66 */
1101 dl 1.15 protected void finalize() {
1102     shutdown();
1103 dl 1.2 }
1104 tim 1.10
1105 dl 1.2 /**
1106     * Sets the thread factory used to create new threads.
1107     *
1108     * @param threadFactory the new thread factory
1109 dl 1.30 * @throws NullPointerException if threadFactory is null
1110 tim 1.11 * @see #getThreadFactory
1111 dl 1.2 */
1112     public void setThreadFactory(ThreadFactory threadFactory) {
1113 dl 1.30 if (threadFactory == null)
1114     throw new NullPointerException();
1115 dl 1.2 this.threadFactory = threadFactory;
1116 tim 1.1 }
1117    
1118 dl 1.2 /**
1119     * Returns the thread factory used to create new threads.
1120     *
1121     * @return the current thread factory
1122 tim 1.11 * @see #setThreadFactory
1123 dl 1.2 */
1124     public ThreadFactory getThreadFactory() {
1125     return threadFactory;
1126 tim 1.1 }
1127    
1128 dl 1.2 /**
1129     * Sets a new handler for unexecutable tasks.
1130     *
1131     * @param handler the new handler
1132 dl 1.31 * @throws NullPointerException if handler is null
1133 tim 1.11 * @see #getRejectedExecutionHandler
1134 dl 1.2 */
1135     public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
1136 dl 1.31 if (handler == null)
1137     throw new NullPointerException();
1138 dl 1.2 this.handler = handler;
1139     }
1140 tim 1.1
1141 dl 1.2 /**
1142     * Returns the current handler for unexecutable tasks.
1143     *
1144     * @return the current handler
1145 tim 1.11 * @see #setRejectedExecutionHandler
1146 dl 1.2 */
1147     public RejectedExecutionHandler getRejectedExecutionHandler() {
1148     return handler;
1149 tim 1.1 }
1150    
1151 dl 1.2 /**
1152 dl 1.17 * Returns the task queue used by this executor. Access to the
1153     * task queue is intended primarily for debugging and monitoring.
1154 dl 1.27 * This queue may be in active use. Retrieving the task queue
1155 dl 1.2 * does not prevent queued tasks from executing.
1156     *
1157     * @return the task queue
1158     */
1159     public BlockingQueue<Runnable> getQueue() {
1160     return workQueue;
1161 tim 1.1 }
1162 dl 1.4
1163     /**
1164 dl 1.44 * Removes this task from the executor's internal queue if it is
1165     * present, thus causing it not to be run if it has not already
1166     * started.
1167 jsr166 1.66 *
1168 dl 1.44 * <p> This method may be useful as one part of a cancellation
1169     * scheme. It may fail to remove tasks that have been converted
1170     * into other forms before being placed on the internal queue. For
1171     * example, a task entered using <tt>submit</tt> might be
1172     * converted into a form that maintains <tt>Future</tt> status.
1173     * However, in such cases, method {@link ThreadPoolExecutor#purge}
1174     * may be used to remove those Futures that have been cancelled.
1175 jsr166 1.66 *
1176 dl 1.8 * @param task the task to remove
1177     * @return true if the task was removed
1178 dl 1.4 */
1179 dl 1.5 public boolean remove(Runnable task) {
1180 dl 1.4 return getQueue().remove(task);
1181     }
1182    
1183 dl 1.7
1184     /**
1185 dl 1.37 * Tries to remove from the work queue all {@link Future}
1186 dl 1.16 * tasks that have been cancelled. This method can be useful as a
1187     * storage reclamation operation, that has no other impact on
1188     * functionality. Cancelled tasks are never executed, but may
1189     * accumulate in work queues until worker threads can actively
1190     * remove them. Invoking this method instead tries to remove them now.
1191 dl 1.23 * However, this method may fail to remove tasks in
1192 dl 1.16 * the presence of interference by other threads.
1193 dl 1.7 */
1194     public void purge() {
1195 dl 1.16 // Fail if we encounter interference during traversal
1196     try {
1197     Iterator<Runnable> it = getQueue().iterator();
1198     while (it.hasNext()) {
1199     Runnable r = it.next();
1200 dl 1.37 if (r instanceof Future<?>) {
1201     Future<?> c = (Future<?>)r;
1202 dl 1.16 if (c.isCancelled())
1203     it.remove();
1204     }
1205 dl 1.7 }
1206     }
1207 jsr166 1.66 catch (ConcurrentModificationException ex) {
1208     return;
1209 dl 1.16 }
1210 dl 1.7 }
1211 tim 1.1
1212     /**
1213 dl 1.2 * Sets the core number of threads. This overrides any value set
1214     * in the constructor. If the new value is smaller than the
1215     * current value, excess existing threads will be terminated when
1216 dl 1.34 * they next become idle. If larger, new threads will, if needed,
1217     * be started to execute any queued tasks.
1218 tim 1.1 *
1219 dl 1.2 * @param corePoolSize the new core size
1220 tim 1.10 * @throws IllegalArgumentException if <tt>corePoolSize</tt>
1221 dl 1.8 * less than zero
1222 tim 1.11 * @see #getCorePoolSize
1223 tim 1.1 */
1224 dl 1.2 public void setCorePoolSize(int corePoolSize) {
1225     if (corePoolSize < 0)
1226     throw new IllegalArgumentException();
1227 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1228 dl 1.2 mainLock.lock();
1229     try {
1230     int extra = this.corePoolSize - corePoolSize;
1231     this.corePoolSize = corePoolSize;
1232 tim 1.38 if (extra < 0) {
1233 dl 1.56 int n = workQueue.size();
1234     // We have to create initially-idle threads here
1235     // because we otherwise have no recourse about
1236     // what to do with a dequeued task if addThread fails.
1237 dl 1.85 while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize &&
1238     runState < STOP) {
1239 dl 1.56 Thread t = addThread(null);
1240 jsr166 1.66 if (t != null)
1241 dl 1.56 t.start();
1242     else
1243     break;
1244     }
1245 tim 1.38 }
1246     else if (extra > 0 && poolSize > corePoolSize) {
1247 dl 1.2 Iterator<Worker> it = workers.iterator();
1248 tim 1.10 while (it.hasNext() &&
1249 dl 1.34 extra-- > 0 &&
1250 dl 1.2 poolSize > corePoolSize &&
1251 jsr166 1.66 workQueue.remainingCapacity() == 0)
1252 dl 1.2 it.next().interruptIfIdle();
1253     }
1254 tim 1.14 } finally {
1255 dl 1.2 mainLock.unlock();
1256     }
1257     }
1258 tim 1.1
1259     /**
1260 dl 1.2 * Returns the core number of threads.
1261 tim 1.1 *
1262 dl 1.2 * @return the core number of threads
1263 tim 1.11 * @see #setCorePoolSize
1264 tim 1.1 */
1265 tim 1.10 public int getCorePoolSize() {
1266 dl 1.2 return corePoolSize;
1267 dl 1.16 }
1268    
1269     /**
1270 dl 1.55 * Starts a core thread, causing it to idly wait for work. This
1271 dl 1.16 * overrides the default policy of starting core threads only when
1272     * new tasks are executed. This method will return <tt>false</tt>
1273     * if all core threads have already been started.
1274     * @return true if a thread was started
1275 jsr166 1.66 */
1276 dl 1.16 public boolean prestartCoreThread() {
1277     return addIfUnderCorePoolSize(null);
1278     }
1279    
1280     /**
1281 dl 1.55 * Starts all core threads, causing them to idly wait for work. This
1282 dl 1.16 * overrides the default policy of starting core threads only when
1283 jsr166 1.66 * new tasks are executed.
1284 dl 1.16 * @return the number of threads started.
1285 jsr166 1.66 */
1286 dl 1.16 public int prestartAllCoreThreads() {
1287     int n = 0;
1288     while (addIfUnderCorePoolSize(null))
1289     ++n;
1290     return n;
1291 dl 1.2 }
1292 tim 1.1
1293     /**
1294 dl 1.62 * Returns true if this pool allows core threads to time out and
1295     * terminate if no tasks arrive within the keepAlive time, being
1296     * replaced if needed when new tasks arrive. When true, the same
1297     * keep-alive policy applying to non-core threads applies also to
1298     * core threads. When false (the default), core threads are never
1299     * terminated due to lack of incoming tasks.
1300     * @return <tt>true</tt> if core threads are allowed to time out,
1301     * else <tt>false</tt>
1302 jsr166 1.72 *
1303     * @since 1.6
1304 dl 1.62 */
1305     public boolean allowsCoreThreadTimeOut() {
1306     return allowCoreThreadTimeOut;
1307     }
1308    
1309     /**
1310     * Sets the policy governing whether core threads may time out and
1311     * terminate if no tasks arrive within the keep-alive time, being
1312     * replaced if needed when new tasks arrive. When false, core
1313     * threads are never terminated due to lack of incoming
1314     * tasks. When true, the same keep-alive policy applying to
1315     * non-core threads applies also to core threads. To avoid
1316     * continual thread replacement, the keep-alive time must be
1317 dl 1.64 * greater than zero when setting <tt>true</tt>. This method
1318     * should in general be called before the pool is actively used.
1319 dl 1.62 * @param value <tt>true</tt> if should time out, else <tt>false</tt>
1320 dl 1.64 * @throws IllegalArgumentException if value is <tt>true</tt>
1321     * and the current keep-alive time is not greater than zero.
1322 jsr166 1.72 *
1323     * @since 1.6
1324 dl 1.62 */
1325     public void allowCoreThreadTimeOut(boolean value) {
1326 dl 1.64 if (value && keepAliveTime <= 0)
1327     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1328    
1329 dl 1.62 allowCoreThreadTimeOut = value;
1330     }
1331    
1332     /**
1333 tim 1.1 * Sets the maximum allowed number of threads. This overrides any
1334 dl 1.2 * value set in the constructor. If the new value is smaller than
1335     * the current value, excess existing threads will be
1336     * terminated when they next become idle.
1337 tim 1.1 *
1338 dl 1.2 * @param maximumPoolSize the new maximum
1339 jsr166 1.84 * @throws IllegalArgumentException if the new maximum is
1340     * less than or equal to zero, or
1341     * less than the {@linkplain #getCorePoolSize core pool size}
1342 tim 1.11 * @see #getMaximumPoolSize
1343 dl 1.2 */
1344     public void setMaximumPoolSize(int maximumPoolSize) {
1345     if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
1346     throw new IllegalArgumentException();
1347 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1348 dl 1.2 mainLock.lock();
1349     try {
1350     int extra = this.maximumPoolSize - maximumPoolSize;
1351     this.maximumPoolSize = maximumPoolSize;
1352     if (extra > 0 && poolSize > maximumPoolSize) {
1353     Iterator<Worker> it = workers.iterator();
1354 tim 1.10 while (it.hasNext() &&
1355     extra > 0 &&
1356 dl 1.2 poolSize > maximumPoolSize) {
1357     it.next().interruptIfIdle();
1358     --extra;
1359     }
1360     }
1361 tim 1.14 } finally {
1362 dl 1.2 mainLock.unlock();
1363     }
1364     }
1365 tim 1.1
1366     /**
1367     * Returns the maximum allowed number of threads.
1368     *
1369 dl 1.2 * @return the maximum allowed number of threads
1370 tim 1.11 * @see #setMaximumPoolSize
1371 tim 1.1 */
1372 tim 1.10 public int getMaximumPoolSize() {
1373 dl 1.2 return maximumPoolSize;
1374     }
1375 tim 1.1
1376     /**
1377     * Sets the time limit for which threads may remain idle before
1378 dl 1.2 * being terminated. If there are more than the core number of
1379 tim 1.1 * threads currently in the pool, after waiting this amount of
1380     * time without processing a task, excess threads will be
1381     * terminated. This overrides any value set in the constructor.
1382     * @param time the time to wait. A time value of zero will cause
1383     * excess threads to terminate immediately after executing tasks.
1384 dl 1.2 * @param unit the time unit of the time argument
1385 dl 1.64 * @throws IllegalArgumentException if time less than zero or
1386     * if time is zero and allowsCoreThreadTimeOut
1387 tim 1.11 * @see #getKeepAliveTime
1388 tim 1.1 */
1389 dl 1.2 public void setKeepAliveTime(long time, TimeUnit unit) {
1390     if (time < 0)
1391     throw new IllegalArgumentException();
1392 dl 1.64 if (time == 0 && allowsCoreThreadTimeOut())
1393     throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
1394 dl 1.2 this.keepAliveTime = unit.toNanos(time);
1395     }
1396 tim 1.1
1397     /**
1398     * Returns the thread keep-alive time, which is the amount of time
1399 dl 1.2 * which threads in excess of the core pool size may remain
1400 tim 1.10 * idle before being terminated.
1401 tim 1.1 *
1402 dl 1.2 * @param unit the desired time unit of the result
1403 tim 1.1 * @return the time limit
1404 tim 1.11 * @see #setKeepAliveTime
1405 tim 1.1 */
1406 tim 1.10 public long getKeepAliveTime(TimeUnit unit) {
1407 dl 1.2 return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
1408     }
1409 tim 1.1
1410     /* Statistics */
1411    
1412     /**
1413     * Returns the current number of threads in the pool.
1414     *
1415     * @return the number of threads
1416     */
1417 tim 1.10 public int getPoolSize() {
1418 dl 1.2 return poolSize;
1419     }
1420 tim 1.1
1421     /**
1422 dl 1.2 * Returns the approximate number of threads that are actively
1423 tim 1.1 * executing tasks.
1424     *
1425     * @return the number of threads
1426     */
1427 tim 1.10 public int getActiveCount() {
1428 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1429 dl 1.2 mainLock.lock();
1430     try {
1431     int n = 0;
1432 tim 1.39 for (Worker w : workers) {
1433     if (w.isActive())
1434 dl 1.2 ++n;
1435     }
1436     return n;
1437 tim 1.14 } finally {
1438 dl 1.2 mainLock.unlock();
1439     }
1440     }
1441 tim 1.1
1442     /**
1443 dl 1.2 * Returns the largest number of threads that have ever
1444     * simultaneously been in the pool.
1445 tim 1.1 *
1446     * @return the number of threads
1447     */
1448 tim 1.10 public int getLargestPoolSize() {
1449 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1450 dl 1.2 mainLock.lock();
1451     try {
1452     return largestPoolSize;
1453 tim 1.14 } finally {
1454 dl 1.2 mainLock.unlock();
1455     }
1456     }
1457 tim 1.1
1458     /**
1459 dl 1.85 * Returns the approximate total number of tasks that have ever been
1460 dl 1.2 * scheduled for execution. Because the states of tasks and
1461     * threads may change dynamically during computation, the returned
1462 dl 1.17 * value is only an approximation, but one that does not ever
1463     * decrease across successive calls.
1464 tim 1.1 *
1465     * @return the number of tasks
1466     */
1467 tim 1.10 public long getTaskCount() {
1468 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1469 dl 1.2 mainLock.lock();
1470     try {
1471     long n = completedTaskCount;
1472 tim 1.39 for (Worker w : workers) {
1473 dl 1.2 n += w.completedTasks;
1474     if (w.isActive())
1475     ++n;
1476     }
1477     return n + workQueue.size();
1478 tim 1.14 } finally {
1479 dl 1.2 mainLock.unlock();
1480     }
1481     }
1482 tim 1.1
1483     /**
1484 dl 1.2 * Returns the approximate total number of tasks that have
1485     * completed execution. Because the states of tasks and threads
1486     * may change dynamically during computation, the returned value
1487 dl 1.17 * is only an approximation, but one that does not ever decrease
1488     * across successive calls.
1489 tim 1.1 *
1490     * @return the number of tasks
1491     */
1492 tim 1.10 public long getCompletedTaskCount() {
1493 dl 1.45 final ReentrantLock mainLock = this.mainLock;
1494 dl 1.2 mainLock.lock();
1495     try {
1496     long n = completedTaskCount;
1497 tim 1.39 for (Worker w : workers)
1498     n += w.completedTasks;
1499 dl 1.2 return n;
1500 tim 1.14 } finally {
1501 dl 1.2 mainLock.unlock();
1502     }
1503     }
1504 tim 1.1
1505     /**
1506 dl 1.17 * Method invoked prior to executing the given Runnable in the
1507 dl 1.43 * given thread. This method is invoked by thread <tt>t</tt> that
1508     * will execute task <tt>r</tt>, and may be used to re-initialize
1509 jsr166 1.73 * ThreadLocals, or to perform logging.
1510     *
1511     * <p>This implementation does nothing, but may be customized in
1512     * subclasses. Note: To properly nest multiple overridings, subclasses
1513     * should generally invoke <tt>super.beforeExecute</tt> at the end of
1514     * this method.
1515 tim 1.1 *
1516 dl 1.2 * @param t the thread that will run task r.
1517     * @param r the task that will be executed.
1518 tim 1.1 */
1519 dl 1.2 protected void beforeExecute(Thread t, Runnable r) { }
1520 tim 1.1
1521     /**
1522 jsr166 1.70 * Method invoked upon completion of execution of the given Runnable.
1523     * This method is invoked by the thread that executed the task. If
1524     * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
1525     * or <tt>Error</tt> that caused execution to terminate abruptly.
1526 dl 1.69 *
1527     * <p><b>Note:</b> When actions are enclosed in tasks (such as
1528     * {@link FutureTask}) either explicitly or via methods such as
1529     * <tt>submit</tt>, these task objects catch and maintain
1530     * computational exceptions, and so they do not cause abrupt
1531 jsr166 1.70 * termination, and the internal exceptions are <em>not</em>
1532 dl 1.69 * passed to this method.
1533     *
1534 jsr166 1.70 * <p>This implementation does nothing, but may be customized in
1535     * subclasses. Note: To properly nest multiple overridings, subclasses
1536     * should generally invoke <tt>super.afterExecute</tt> at the
1537     * beginning of this method.
1538 tim 1.1 *
1539 dl 1.2 * @param r the runnable that has completed.
1540 dl 1.24 * @param t the exception that caused termination, or null if
1541 dl 1.2 * execution completed normally.
1542 tim 1.1 */
1543 dl 1.2 protected void afterExecute(Runnable r, Throwable t) { }
1544 tim 1.1
1545 dl 1.2 /**
1546     * Method invoked when the Executor has terminated. Default
1547 dl 1.17 * implementation does nothing. Note: To properly nest multiple
1548     * overridings, subclasses should generally invoke
1549     * <tt>super.terminated</tt> within this method.
1550 dl 1.2 */
1551     protected void terminated() { }
1552 tim 1.1
1553     /**
1554 dl 1.21 * A handler for rejected tasks that runs the rejected task
1555     * directly in the calling thread of the <tt>execute</tt> method,
1556     * unless the executor has been shut down, in which case the task
1557     * is discarded.
1558 tim 1.1 */
1559 jsr166 1.71 public static class CallerRunsPolicy implements RejectedExecutionHandler {
1560 tim 1.1 /**
1561 dl 1.24 * Creates a <tt>CallerRunsPolicy</tt>.
1562 tim 1.1 */
1563     public CallerRunsPolicy() { }
1564    
1565 dl 1.24 /**
1566     * Executes task r in the caller's thread, unless the executor
1567     * has been shut down, in which case the task is discarded.
1568     * @param r the runnable task requested to be executed
1569     * @param e the executor attempting to execute this task
1570     */
1571 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1572     if (!e.isShutdown()) {
1573 tim 1.1 r.run();
1574     }
1575     }
1576     }
1577    
1578     /**
1579 dl 1.21 * A handler for rejected tasks that throws a
1580 dl 1.8 * <tt>RejectedExecutionException</tt>.
1581 tim 1.1 */
1582 dl 1.2 public static class AbortPolicy implements RejectedExecutionHandler {
1583 tim 1.1 /**
1584 dl 1.29 * Creates an <tt>AbortPolicy</tt>.
1585 tim 1.1 */
1586     public AbortPolicy() { }
1587    
1588 dl 1.24 /**
1589 dl 1.54 * Always throws RejectedExecutionException.
1590 dl 1.24 * @param r the runnable task requested to be executed
1591     * @param e the executor attempting to execute this task
1592     * @throws RejectedExecutionException always.
1593     */
1594 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1595     throw new RejectedExecutionException();
1596 tim 1.1 }
1597     }
1598    
1599     /**
1600 dl 1.21 * A handler for rejected tasks that silently discards the
1601     * rejected task.
1602 tim 1.1 */
1603 dl 1.2 public static class DiscardPolicy implements RejectedExecutionHandler {
1604 tim 1.1 /**
1605 dl 1.54 * Creates a <tt>DiscardPolicy</tt>.
1606 tim 1.1 */
1607     public DiscardPolicy() { }
1608    
1609 dl 1.24 /**
1610     * Does nothing, which has the effect of discarding task r.
1611     * @param r the runnable task requested to be executed
1612     * @param e the executor attempting to execute this task
1613     */
1614 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1615 tim 1.1 }
1616     }
1617    
1618     /**
1619 dl 1.21 * A handler for rejected tasks that discards the oldest unhandled
1620     * request and then retries <tt>execute</tt>, unless the executor
1621     * is shut down, in which case the task is discarded.
1622 tim 1.1 */
1623 dl 1.2 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
1624 tim 1.1 /**
1625 dl 1.24 * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
1626 tim 1.1 */
1627     public DiscardOldestPolicy() { }
1628    
1629 dl 1.24 /**
1630     * Obtains and ignores the next task that the executor
1631     * would otherwise execute, if one is immediately available,
1632     * and then retries execution of task r, unless the executor
1633     * is shut down, in which case task r is instead discarded.
1634     * @param r the runnable task requested to be executed
1635     * @param e the executor attempting to execute this task
1636     */
1637 dl 1.2 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
1638     if (!e.isShutdown()) {
1639     e.getQueue().poll();
1640     e.execute(r);
1641 tim 1.1 }
1642     }
1643     }
1644     }