ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.73
Committed: Mon Aug 15 20:51:15 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.72: +10 -8 lines
Log Message:
doc fixes

File Contents

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