Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: edu/emory/mathcs/util/concurrent/PooledExecutor.java


1   /*
2     File: PooledExecutor.java
3   
4     Originally written by Doug Lea and released into the public domain.
5     This may be used for any purposes whatsoever without acknowledgment.
6     Thanks for the assistance and support of Sun Microsystems Labs,
7     and everyone contributing, testing, and using this code.
8   
9     History:
10    Date       Who                What
11    19Jun1998  dl               Create public version
12    29aug1998  dl               rely on ThreadFactoryUser,
13                                remove ThreadGroup-based methods
14                                adjusted locking policies
15     3mar1999  dl               Worker threads sense decreases in pool size
16    31mar1999  dl               Allow supplied channel in constructor;
17                                add methods createThreads, drain
18    15may1999  dl               Allow infinite keepalives
19    21oct1999  dl               add minimumPoolSize methods
20     7sep2000  dl               BlockedExecutionHandler now an interface,
21                                new DiscardOldestWhenBlocked policy
22    12oct2000  dl               add shutdownAfterProcessingCurrentlyQueuedTasks
23    13nov2000  dl               null out task ref after run
24    08apr2001  dl               declare inner class ctor protected
25    12nov2001  dl               Better shutdown support
26                                Blocked exec handlers can throw IE
27                                Simplify locking scheme
28  */
29  
30  package edu.emory.mathcs.util.concurrent;
31  import java.util.*;
32  
33  /**
34   * A tunable, extensible thread pool class. The main supported public
35   * method is <code>execute(Runnable command)</code>, which can be
36   * called instead of directly creating threads to execute commands.
37   *
38   * <p>
39   * Thread pools can be useful for several, usually intertwined
40   * reasons:
41   *
42   * <ul>
43   *
44   *    <li> To bound resource use. A limit can be placed on the maximum
45   *    number of simultaneously executing threads.
46   *
47   *    <li> To manage concurrency levels. A targeted number of threads
48   *    can be allowed to execute simultaneously.
49   *
50   *    <li> To manage a set of threads performing related tasks.
51   *
52   *    <li> To minimize overhead, by reusing previously constructed
53   *    Thread objects rather than creating new ones.  (Note however
54   *    that pools are hardly ever cure-alls for performance problems
55   *    associated with thread construction, especially on JVMs that
56   *    themselves internally pool or recycle threads.)
57   *
58   * </ul>
59   *
60   * These goals introduce a number of policy parameters that are
61   * encapsulated in this class. All of these parameters have defaults
62   * and are tunable, either via get/set methods, or, in cases where
63   * decisions should hold across lifetimes, via methods that can be
64   * easily overridden in subclasses.  The main, most commonly set
65   * parameters can be established in constructors.  Policy choices
66   * across these dimensions can and do interact.  Be careful, and
67   * please read this documentation completely before using!  See also
68   * the usage examples below.
69   *
70   * <dl>
71   *   <dt> Queueing
72   *
73   *   <dd> By default, this pool uses queueless synchronous channels to
74   *   to hand off work to threads. This is a safe, conservative policy
75   *   that avoids lockups when handling sets of requests that might
76   *   have internal dependencies. (In these cases, queuing one task
77   *   could lock up another that would be able to continue if the
78   *   queued task were to run.)  If you are sure that this cannot
79   *   happen, then you can instead supply a queue of some sort (for
80   *   example, a BoundedBuffer or LinkedQueue) in the constructor.
81   *   This will cause new commands to be queued in cases where all
82   *   MaximumPoolSize threads are busy. Queues are sometimes
83   *   appropriate when each task is completely independent of others,
84   *   so tasks cannot affect each others execution.  For example, in an
85   *   http server.  <p>
86   *
87   *   When given a choice, this pool always prefers adding a new thread
88   *   rather than queueing if there are currently fewer than the
89   *   current getMinimumPoolSize threads running, but otherwise always
90   *   prefers queuing a request rather than adding a new thread. Thus,
91   *   if you use an unbounded buffer, you will never have more than
92   *   getMinimumPoolSize threads running. (Since the default
93   *   minimumPoolSize is one, you will probably want to explicitly
94   *   setMinimumPoolSize.)  <p>
95   *
96   *   While queuing can be useful in smoothing out transient bursts of
97   *   requests, especially in socket-based services, it is not very
98   *   well behaved when commands continue to arrive on average faster
99   *   than they can be processed.  Using bounds for both the queue and
100  *   the pool size, along with run-when-blocked policy is often a
101  *   reasonable response to such possibilities.  <p>
102  *
103  *   Queue sizes and maximum pool sizes can often be traded off for
104  *   each other. Using large queues and small pools minimizes CPU
105  *   usage, OS resources, and context-switching overhead, but can lead
106  *   to artifically low throughput. Especially if tasks frequently
107  *   block (for example if they are I/O bound), a JVM and underlying
108  *   OS may be able to schedule time for more threads than you
109  *   otherwise allow. Use of small queues or queueless handoffs
110  *   generally requires larger pool sizes, which keeps CPUs busier but
111  *   may encounter unacceptable scheduling overhead, which also
112  *   decreases throughput.  <p>
113  *
114  *   <dt> Maximum Pool size
115  *
116  *   <dd> The maximum number of threads to use, when needed.  The pool
117  *   does not by default preallocate threads.  Instead, a thread is
118  *   created, if necessary and if there are fewer than the maximum,
119  *   only when an <code>execute</code> request arrives.  The default
120  *   value is (for all practical purposes) infinite --
121  *   <code>Integer.MAX_VALUE</code>, so should be set in the
122  *   constructor or the set method unless you are just using the pool
123  *   to minimize construction overhead.  Because task handoffs to idle
124  *   worker threads require synchronization that in turn relies on JVM
125  *   scheduling policies to ensure progress, it is possible that a new
126  *   thread will be created even though an existing worker thread has
127  *   just become idle but has not progressed to the point at which it
128  *   can accept a new task. This phenomenon tends to occur on some
129  *   JVMs when bursts of short tasks are executed.  <p>
130  *
131  *   <dt> Minimum Pool size
132  *
133  *   <dd> The minimum number of threads to use, when needed (default
134  *   1).  When a new request is received, and fewer than the minimum
135  *   number of threads are running, a new thread is always created to
136  *   handle the request even if other worker threads are idly waiting
137  *   for work. Otherwise, a new thread is created only if there are
138  *   fewer than the maximum and the request cannot immediately be
139  *   queued.  <p>
140  *
141  *   <dt> Preallocation
142  *
143  *   <dd> You can override lazy thread construction policies via
144  *   method createThreads, which establishes a given number of warm
145  *   threads. Be aware that these preallocated threads will time out
146  *   and die (and later be replaced with others if needed) if not used
147  *   within the keep-alive time window. If you use preallocation, you
148  *   probably want to increase the keepalive time.  The difference
149  *   between setMinimumPoolSize and createThreads is that
150  *   createThreads immediately establishes threads, while setting the
151  *   minimum pool size waits until requests arrive.  <p>
152  *
153  *   <dt> Keep-alive time
154  *
155  *   <dd> If the pool maintained references to a fixed set of threads
156  *   in the pool, then it would impede garbage collection of otherwise
157  *   idle threads. This would defeat the resource-management aspects
158  *   of pools. One solution would be to use weak references.  However,
159  *   this would impose costly and difficult synchronization issues.
160  *   Instead, threads are simply allowed to terminate and thus be
161  *   GCable if they have been idle for the given keep-alive time.  The
162  *   value of this parameter represents a trade-off between GCability
163  *   and construction time. In most current Java VMs, thread
164  *   construction and cleanup overhead is on the order of
165  *   milliseconds. The default keep-alive value is one minute, which
166  *   means that the time needed to construct and then GC a thread is
167  *   expended at most once per minute.
168  *   <p>
169  *
170  *   To establish worker threads permanently, use a <em>negative</em>
171  *   argument to setKeepAliveTime.  <p>
172  *
173  *   <dt> Blocked execution policy
174  *
175  *   <dd> If the maximum pool size or queue size is bounded, then it
176  *   is possible for incoming <code>execute</code> requests to
177  *   block. There are four supported policies for handling this
178  *   problem, and mechanics (based on the Strategy Object pattern) to
179  *   allow others in subclasses: <p>
180  *
181  *   <dl>
182  *     <dt> Run (the default)
183  *     <dd> The thread making the <code>execute</code> request
184  *          runs the task itself. This policy helps guard against lockup.
185  *     <dt> Wait
186  *     <dd> Wait until a thread becomes available.
187  *     <dt> Abort
188  *     <dd> Throw a RuntimeException
189  *     <dt> Discard
190  *     <dd> Throw away the current request and return.
191  *     <dt> DiscardOldest
192  *     <dd> Throw away the oldest request and return.
193  *   </dl>
194  *
195  *   Other plausible policies include raising the maximum pool size
196  *   after checking with some other objects that this is OK.  <p>
197  *
198  *   These cases can never occur if the maximum pool size is unbounded
199  *   or the queue is unbounded.  In these cases you instead face
200  *   potential resource exhaustion.)  The execute method does not
201  *   throw any checked exceptions in any of these cases since any
202  *   errors associated with them must normally be dealt with via
203  *   handlers or callbacks. (Although in some cases, these might be
204  *   associated with throwing unchecked exceptions.)  You may wish to
205  *   add special implementations even if you choose one of the listed
206  *   policies. For example, the supplied Discard policy does not
207  *   inform the caller of the drop. You could add your own version
208  *   that does so.  Since choice of policies is normally a system-wide
209  *   decision, selecting a policy affects all calls to
210  *   <code>execute</code>.  If for some reason you would instead like
211  *   to make per-call decisions, you could add variant versions of the
212  *   <code>execute</code> method (for example,
213  *   <code>executeIfWouldNotBlock</code>) in subclasses.  <p>
214  *
215  *   <dt> Thread construction parameters
216  *
217  *   <dd> A settable ThreadFactory establishes each new thread.  By
218  *   default, it merely generates a new instance of class Thread, but
219  *   can be changed to use a Thread subclass, to set priorities,
220  *   ThreadLocals, etc.  <p>
221  *
222  *   <dt> Interruption policy
223  *
224  *   <dd> Worker threads check for interruption after processing each
225  *   command, and terminate upon interruption.  Fresh threads will
226  *   replace them if needed. Thus, new tasks will not start out in an
227  *   interrupted state due to an uncleared interruption in a previous
228  *   task. Also, unprocessed commands are never dropped upon
229  *   interruption. It would conceptually suffice simply to clear
230  *   interruption between tasks, but implementation characteristics of
231  *   interruption-based methods are uncertain enough to warrant this
232  *   conservative strategy. It is a good idea to be equally
233  *   conservative in your code for the tasks running within pools.
234  *   <p>
235  *
236  *   <dt> Shutdown policy
237  *
238  *   <dd> The interruptAll method interrupts, but does not disable the
239  *   pool. Two different shutdown methods are supported for use when
240  *   you do want to (permanently) stop processing tasks. Method
241  *   shutdownAfterProcessingCurrentlyQueuedTasks waits until all
242  *   current tasks are finished. The shutDownNow method interrupts
243  *   current threads and leaves other queued requests unprocessed.
244  *   <p>
245  *
246  *   <dt> Handling requests after shutdown
247  *
248  *   <dd> When the pool is shutdown, new incoming requests are handled
249  *   by the blockedExecutionHandler. By default, the handler is set to
250  *   discard new requests, but this can be set with an optional
251  *   argument to method
252  *   shutdownAfterProcessingCurrentlyQueuedTasks. <p> Also, if you are
253  *   using some form of queuing, you may wish to call method drain()
254  *   to remove (and return) unprocessed commands from the queue after
255  *   shutting down the pool and its clients. If you need to be sure
256  *   these commands are processed, you can then run() each of the
257  *   commands in the list returned by drain().
258  *
259  * </dl>
260  * <p>
261  *
262  * <b>Usage examples.</b>
263  * <p>
264  *
265  * Probably the most common use of pools is in statics or singletons
266  * accessible from a number of classes in a package; for example:
267  *
268  * <pre>
269  * class MyPool {
270  *   // initialize to use a maximum of 8 threads.
271  *   static PooledExecutor pool = new PooledExecutor(8);
272  * }
273  * </pre>
274  * Here are some sample variants in initialization:
275  * <ol>
276  *  <li> Using a bounded buffer of 10 tasks, at least 4 threads (started only
277  *       when needed due to incoming requests), but allowing
278  *       up to 100 threads if the buffer gets full.
279  *     <pre>
280  *        pool = new PooledExecutor(new BoundedBuffer(10), 100);
281  *        pool.setMinimumPoolSize(4);
282  *     </pre>
283  *  <li> Same as (1), except pre-start 9 threads, allowing them to
284  *        die if they are not used for five minutes.
285  *     <pre>
286  *        pool = new PooledExecutor(new BoundedBuffer(10), 100);
287  *        pool.setMinimumPoolSize(4);
288  *        pool.setKeepAliveTime(1000 * 60 * 5);
289  *        pool.createThreads(9);
290  *     </pre>
291  *  <li> Same as (2) except clients block if both the buffer is full and
292  *       all 100 threads are busy:
293  *     <pre>
294  *        pool = new PooledExecutor(new BoundedBuffer(10), 100);
295  *        pool.setMinimumPoolSize(4);
296  *        pool.setKeepAliveTime(1000 * 60 * 5);
297  *        pool.waitWhenBlocked();
298  *        pool.createThreads(9);
299  *     </pre>
300  *  <li> An unbounded queue serviced by exactly 5 threads:
301  *     <pre>
302  *        pool = new PooledExecutor(new LinkedQueue());
303  *        pool.setKeepAliveTime(-1); // live forever
304  *        pool.createThreads(5);
305  *     </pre>
306  *  </ol>
307  *
308  * <p>
309  * <b>Usage notes.</b>
310  * <p>
311  *
312  * Pools do not mesh well with using thread-specific storage via
313  * java.lang.ThreadLocal.  ThreadLocal relies on the identity of a
314  * thread executing a particular task. Pools use the same thread to
315  * perform different tasks.  <p>
316  *
317  * If you need a policy not handled by the parameters in this class
318  * consider writing a subclass.  <p>
319  *
320  * Version note: Previous versions of this class relied on
321  * ThreadGroups for aggregate control. This has been removed, and the
322  * method interruptAll added, to avoid differences in behavior across
323  * JVMs.
324  *
325  * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/edu/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
326  **/
327 
328 public class PooledExecutor extends ThreadFactoryUser implements Executor {
329 
330   /**
331    * The maximum pool size; used if not otherwise specified.  Default
332    * value is essentially infinite (Integer.MAX_VALUE)
333    **/
334   public static final int  DEFAULT_MAXIMUMPOOLSIZE = Integer.MAX_VALUE;
335 
336   /**
337    * The minimum pool size; used if not otherwise specified.  Default
338    * value is 1.
339    **/
340   public static final int  DEFAULT_MINIMUMPOOLSIZE = 1;
341 
342   /**
343    * The maximum time to keep worker threads alive waiting for new
344    * tasks; used if not otherwise specified. Default value is one
345    * minute (60000 milliseconds).
346    **/
347   public static final long DEFAULT_KEEPALIVETIME = 60 * 1000;
348 
349   /** The maximum number of threads allowed in pool. **/
350   protected int maximumPoolSize_ = DEFAULT_MAXIMUMPOOLSIZE;
351 
352   /** The minumum number of threads to maintain in pool. **/
353   protected int minimumPoolSize_ = DEFAULT_MINIMUMPOOLSIZE;
354 
355   /**  Current pool size.  **/
356   protected int poolSize_ = 0;
357 
358   /** The maximum time for an idle thread to wait for new task. **/
359   protected long keepAliveTime_ = DEFAULT_KEEPALIVETIME;
360 
361   /**
362    * Shutdown flag - latches true when a shutdown method is called
363    * in order to disable queuing/handoffs of new tasks.
364    **/
365   protected boolean shutdown_ = false;
366 
367   /**
368    * The channel used to hand off the command to a thread in the pool.
369    **/
370   protected final BlockingQueue handOff_;
371 
372   /**
373    * The set of active threads, declared as a map from workers to
374    * their threads.  This is needed by the interruptAll method.  It
375    * may also be useful in subclasses that need to perform other
376    * thread management chores.
377    **/
378   protected final Map threads_;
379 
380   /** The current handler for unserviceable requests. **/
381   protected BlockedExecutionHandler blockedExecutionHandler_;
382 
383   /**
384    * Create a new pool with all default settings
385    **/
386 
387   public PooledExecutor() {
388     this (new SynchronousQueue(), DEFAULT_MAXIMUMPOOLSIZE);
389   }
390 
391   /**
392    * Create a new pool with all default settings except
393    * for maximum pool size.
394    **/
395 
396   public PooledExecutor(int maxPoolSize) {
397     this(new SynchronousQueue(), maxPoolSize);
398   }
399 
400   /**
401    * Create a new pool that uses the supplied Queue for queuing, and
402    * with all default parameter settings.
403    **/
404 
405   public PooledExecutor(BlockingQueue queue) {
406     this(queue, DEFAULT_MAXIMUMPOOLSIZE);
407   }
408 
409   /**
410    * Create a new pool that uses the supplied Queue for queuing, and
411    * with all default parameter settings except for maximum pool size.
412    **/
413 
414   public PooledExecutor(BlockingQueue queue, int maxPoolSize) {
415     maximumPoolSize_ = maxPoolSize;
416     handOff_ = queue;
417     runWhenBlocked();
418     threads_ = new HashMap();
419   }
420 
421   /**
422    * Return the maximum number of threads to simultaneously execute
423    * New unqueued requests will be handled according to the current
424    * blocking policy once this limit is exceeded.
425    **/
426   public synchronized int getMaximumPoolSize() {
427     return maximumPoolSize_;
428   }
429 
430   /**
431    * Set the maximum number of threads to use. Decreasing the pool
432    * size will not immediately kill existing threads, but they may
433    * later die when idle.
434    * @exception IllegalArgumentException if less or equal to zero.
435    * (It is
436    * not considered an error to set the maximum to be less than than
437    * the minimum. However, in this case there are no guarantees
438    * about behavior.)
439    **/
440   public synchronized void setMaximumPoolSize(int newMaximum) {
441     if (newMaximum <= 0) throw new IllegalArgumentException();
442     maximumPoolSize_ = newMaximum;
443   }
444 
445   /**
446    * Return the minimum number of threads to simultaneously execute.
447    * (Default value is 1).  If fewer than the mininum number are
448    * running upon reception of a new request, a new thread is started
449    * to handle this request.
450    **/
451   public synchronized int getMinimumPoolSize() {
452     return minimumPoolSize_;
453   }
454 
455   /**
456    * Set the minimum number of threads to use.
457    * @exception IllegalArgumentException if less than zero. (It is not
458    * considered an error to set the minimum to be greater than the
459    * maximum. However, in this case there are no guarantees about
460    * behavior.)
461    **/
462   public synchronized void setMinimumPoolSize(int newMinimum) {
463     if (newMinimum < 0) throw new IllegalArgumentException();
464     minimumPoolSize_ = newMinimum;
465   }
466 
467   /**
468    * Return the current number of active threads in the pool.  This
469    * number is just a snaphot, and may change immediately upon
470    * returning
471    **/
472   public synchronized int getPoolSize() {
473     return poolSize_;
474   }
475 
476   /**
477    * Return the number of milliseconds to keep threads alive waiting
478    * for new commands. A negative value means to wait forever. A zero
479    * value means not to wait at all.
480    **/
481   public synchronized long getKeepAliveTime() {
482     return keepAliveTime_;
483   }
484 
485   /**
486    * Set the number of milliseconds to keep threads alive waiting for
487    * new commands. A negative value means to wait forever. A zero
488    * value means not to wait at all.
489    **/
490   public synchronized void setKeepAliveTime(long msecs) {
491     keepAliveTime_ = msecs;
492   }
493 
494   /** Get the handler for blocked execution **/
495   protected synchronized BlockedExecutionHandler getBlockedExecutionHandler() {
496     return blockedExecutionHandler_;
497   }
498 
499   /** Set the handler for blocked execution **/
500   protected synchronized void setBlockedExecutionHandler(BlockedExecutionHandler h) {
501     blockedExecutionHandler_ = h;
502   }
503 
504   /**
505    * Create and start a thread to handle a new command.  Call only
506    * when holding lock.
507    **/
508   protected void addThread(Runnable command) {
509     Worker worker = new Worker(command);
510     Thread thread = getThreadFactory().newThread(worker);
511     threads_.put(worker, thread);
512     ++poolSize_;
513     thread.start();
514   }
515 
516   /**
517    * Create and start up to numberOfThreads threads in the pool.
518    * Return the number created. This may be less than the number
519    * requested if creating more would exceed maximum pool size bound.
520    **/
521   public int createThreads(int numberOfThreads) {
522     int ncreated = 0;
523     for (int i = 0; i < numberOfThreads; ++i) {
524       synchronized(this) {
525         if (poolSize_ < maximumPoolSize_) {
526           addThread(null);
527           ++ncreated;
528         }
529         else
530           break;
531       }
532     }
533     return ncreated;
534   }
535 
536   /**
537    * Interrupt all threads in the pool, causing them all to
538    * terminate. Assuming that executed tasks do not disable (clear)
539    * interruptions, each thread will terminate after processing its
540    * current task. Threads will terminate sooner if the executed tasks
541    * themselves respond to interrupts.
542    **/
543   public synchronized void interruptAll() {
544     for (Iterator it = threads_.values().iterator(); it.hasNext(); ) {
545       Thread t = (Thread)(it.next());
546       t.interrupt();
547     }
548   }
549 
550   /**
551    * Interrupt all threads and disable construction of new
552    * threads. Any tasks entered after this point will be discarded. A
553    * shut down pool cannot be restarted.
554    */
555   public void shutdownNow() {
556     shutdownNow(new DiscardWhenBlocked());
557   }
558 
559   /**
560    * Interrupt all threads and disable construction of new
561    * threads. Any tasks entered after this point will be handled by
562    * the given BlockedExecutionHandler.  A shut down pool cannot be
563    * restarted.
564    */
565   public synchronized void shutdownNow(BlockedExecutionHandler handler) {
566     setBlockedExecutionHandler(handler);
567     shutdown_ = true; // don't allow new tasks
568     minimumPoolSize_ = maximumPoolSize_ = 0; // don't make new threads
569     interruptAll(); // interrupt all existing threads
570   }
571 
572   /**
573    * Terminate threads after processing all elements currently in
574    * queue. Any tasks entered after this point will be discarded. A
575    * shut down pool cannot be restarted.
576    **/
577   public void shutdownAfterProcessingCurrentlyQueuedTasks() {
578     shutdownAfterProcessingCurrentlyQueuedTasks(new DiscardWhenBlocked());
579   }
580 
581   /**
582    * Terminate threads after processing all elements currently in
583    * queue. Any tasks entered after this point will be handled by the
584    * given BlockedExecutionHandler.  A shut down pool cannot be
585    * restarted.
586    **/
587   public synchronized void shutdownAfterProcessingCurrentlyQueuedTasks(BlockedExecutionHandler handler) {
588     setBlockedExecutionHandler(handler);
589     shutdown_ = true;
590     if (poolSize_ == 0) // disable new thread construction when idle
591       minimumPoolSize_ = maximumPoolSize_ = 0;
592   }
593 
594   /**
595    * Return true if a shutDown method has succeeded in terminating all
596    * threads.
597    */
598   public synchronized boolean isTerminatedAfterShutdown() {
599     return shutdown_ && poolSize_ == 0;
600   }
601 
602   /**
603    * Wait for a shutdown pool to fully terminate, or until the timeout
604    * has expired. This method may only be called <em>after</em>
605    * invoking shutdownNow or
606    * shutdownAfterProcessingCurrentlyQueuedTasks.
607    *
608    * @param maxWaitTime  the maximum time in milliseconds to wait
609    * @return true if the pool has terminated within the max wait period
610    * @exception IllegalStateException if shutdown has not been requested
611    * @exception InterruptedException if the current thread has been interrupted in the course of waiting
612    */
613   public synchronized boolean awaitTerminationAfterShutdown(long maxWaitTime) throws InterruptedException {
614     if (!shutdown_)
615       throw new IllegalStateException();
616     if (poolSize_ == 0)
617       return true;
618     long waitTime = maxWaitTime;
619     if (waitTime <= 0)
620       return false;
621     long start = System.currentTimeMillis();
622     for (;;) {
623       wait(waitTime);
624       if (poolSize_ == 0)
625         return true;
626       waitTime = maxWaitTime - (System.currentTimeMillis() - start);
627       if (waitTime <= 0)
628         return false;
629     }
630   }
631 
632   /**
633    * Wait for a shutdown pool to fully terminate.  This method may
634    * only be called <em>after</em> invoking shutdownNow or
635    * shutdownAfterProcessingCurrentlyQueuedTasks.
636    *
637    * @exception IllegalStateException if shutdown has not been requested
638    * @exception InterruptedException if the current thread has been interrupted in the course of waiting
639    */
640   public synchronized void awaitTerminationAfterShutdown() throws InterruptedException {
641     if (!shutdown_)
642       throw new IllegalStateException();
643     while (poolSize_ > 0)
644       wait();
645   }
646 
647   /**
648    * Remove all unprocessed tasks from pool queue, and return them in
649    * a java.util.List. Thsi method should be used only when there are
650    * not any active clients of the pool. Otherwise you face the
651    * possibility that the method will loop pulling out tasks as
652    * clients are putting them in.  This method can be useful after
653    * shutting down a pool (via shutdownNow) to determine whether there
654    * are any pending tasks that were not processed.  You can then, for
655    * example execute all unprocessed commands via code along the lines
656    * of:
657    *
658    * <pre>
659    *   List tasks = pool.drain();
660    *   for (Iterator it = tasks.iterator(); it.hasNext();)
661    *     ( (Runnable)(it.next()) ).run();
662    * </pre>
663    **/
664   public List drain() {
665     boolean wasInterrupted = false;
666     Vector tasks = new Vector();
667     for (;;) {
668       Object x = handOff_.poll();
669       if (x == null)
670         break;
671       else
672         tasks.addElement(x);
673     }
674     return tasks;
675   }
676 
677   /**
678    * Cleanup method called upon termination of worker thread.
679    **/
680   protected synchronized void workerDone(Worker w) {
681     threads_.remove(w);
682     if (--poolSize_ == 0 && shutdown_) {
683       maximumPoolSize_ = minimumPoolSize_ = 0; // disable new threads
684       notifyAll(); // notify awaitTerminationAfterShutdown
685     }
686   }
687 
688   /**
689    * Get a task from the handoff queue, or null if shutting down.
690    **/
691   protected Runnable getTask() throws InterruptedException {
692     long waitTime;
693     synchronized(this) {
694       if (poolSize_ > maximumPoolSize_) // Cause to die if too many threads
695         return null;
696       waitTime = (shutdown_)? 0 : keepAliveTime_;
697     }
698     if (waitTime >= 0)
699       return (Runnable)(handOff_.poll(waitTime, TimeUnit.MILLISECONDS));
700     else
701       return (Runnable)(handOff_.take());
702   }
703 
704 
705   /**
706    * Class defining the basic run loop for pooled threads.
707    **/
708   protected class Worker implements Runnable {
709     protected Runnable firstTask_;
710 
711     protected Worker(Runnable firstTask) { firstTask_ = firstTask; }
712 
713     public void run() {
714       try {
715         Runnable task = firstTask_;
716         firstTask_ = null; // enable GC
717 
718         if (task != null)
719           task.run();
720 
721         while ( (task = getTask()) != null)
722           task.run();
723 
724       }
725       catch (InterruptedException ex) { } // fall through
726       finally {
727         workerDone(this);
728       }
729     }
730   }
731 
732   /**
733    * Class for actions to take when execute() blocks. Uses Strategy
734    * pattern to represent different actions. You can add more in
735    * subclasses, and/or create subclasses of these. If so, you will
736    * also want to add or modify the corresponding methods that set the
737    * current blockedExectionHandler_.
738    **/
739   protected interface BlockedExecutionHandler {
740     /**
741      * Return true if successfully handled so, execute should
742      * terminate; else return false if execute loop should be retried.
743      **/
744     boolean blockedAction(Runnable command);
745   }
746 
747   /** Class defining Run action. **/
748   protected class RunWhenBlocked implements BlockedExecutionHandler {
749     public boolean blockedAction(Runnable command) {
750       command.run();
751       return true;
752     }
753   }
754 
755   /**
756    * Set the policy for blocked execution to be that the current
757    * thread executes the command if there are no available threads in
758    * the pool.
759    **/
760   public void runWhenBlocked() {
761     setBlockedExecutionHandler(new RunWhenBlocked());
762   }
763 
764   /** Class defining Wait action. **/
765   protected class WaitWhenBlocked implements BlockedExecutionHandler {
766     public boolean blockedAction(Runnable command) {
767       try {
768         handOff_.put(command);
769         return true;
770       }
771       catch (InterruptedException ie) {
772         Thread.currentThread().interrupt();
773         throw new RejectedExecutionException(ie);
774       }
775     }
776   }
777 
778   /**
779    * Set the policy for blocked execution to be to wait until a thread
780    * is available.
781    **/
782   public void waitWhenBlocked() {
783     setBlockedExecutionHandler(new WaitWhenBlocked());
784   }
785 
786   /** Class defining Discard action. **/
787   protected class DiscardWhenBlocked implements BlockedExecutionHandler {
788     public boolean blockedAction(Runnable command) {
789       return true;
790     }
791   }
792 
793   /**
794    * Set the policy for blocked execution to be to return without
795    * executing the request.
796    **/
797   public void discardWhenBlocked() {
798     setBlockedExecutionHandler(new DiscardWhenBlocked());
799   }
800 
801 
802   /** Class defining Abort action. **/
803   protected class AbortWhenBlocked implements BlockedExecutionHandler {
804     public boolean blockedAction(Runnable command) {
805       throw new RuntimeException("Pool is blocked");
806     }
807   }
808 
809   /**
810    * Set the policy for blocked execution to be to
811    * throw a RuntimeException.
812    **/
813   public void abortWhenBlocked() {
814     setBlockedExecutionHandler(new AbortWhenBlocked());
815   }
816 
817 
818   /**
819    * Class defining DiscardOldest action.  Under this policy, at most
820    * one old unhandled task is discarded.  If the new task can then be
821    * handed off, it is.  Otherwise, the new task is run in the current
822    * thread (i.e., RunWhenBlocked is used as a backup policy.)
823    **/
824   protected class DiscardOldestWhenBlocked implements BlockedExecutionHandler {
825     public boolean blockedAction(Runnable command) {
826       handOff_.poll();
827       if (!handOff_.offer(command))
828         command.run();
829       return true;
830     }
831   }
832 
833   /**
834    * Set the policy for blocked execution to be to discard the oldest
835    * unhandled request
836    **/
837   public void discardOldestWhenBlocked() {
838     setBlockedExecutionHandler(new DiscardOldestWhenBlocked());
839   }
840 
841   /**
842    * Arrange for the given command to be executed by a thread in this
843    * pool.  The method normally returns when the command has been
844    * handed off for (possibly later) execution.
845    **/
846   public void execute(Runnable command) {
847     for (;;) {
848       synchronized(this) {
849         if (!shutdown_) {
850           int size = poolSize_;
851 
852           // Ensure minimum number of threads
853           if (size < minimumPoolSize_) {
854             addThread(command);
855             return;
856           }
857 
858           // Try to give to existing thread
859           if (handOff_.offer(command)) {
860             return;
861           }
862 
863           // If cannot handoff and still under maximum, create new thread
864           if (size < maximumPoolSize_) {
865             addThread(command);
866             return;
867           }
868         }
869       }
870 
871       // Cannot hand off and cannot create -- ask for help
872       if (getBlockedExecutionHandler().blockedAction(command)) {
873         return;
874       }
875     }
876   }
877 }