ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadPoolExecutor.java
Revision: 1.49
Committed: Sun Jan 4 00:56:48 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.48: +0 -4 lines
Log Message:
Code walkthrough misc

File Contents

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