ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.69
Committed: Wed May 25 14:05:27 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.68: +13 -4 lines
Log Message:
Avoid generics warnings; clarify javadocs

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