ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.4
Committed: Wed Dec 10 02:24:00 2003 UTC (20 years, 6 months ago) by tim
Branch: MAIN
Changes since 1.3: +1 -1 lines
Log Message:
Raw List returned by shutdownNow is really List<Runnable>.

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
5     */
6    
7     package java.util.concurrent;
8     import java.util.concurrent.atomic.*;
9     import java.util.*;
10    
11     /**
12     * A {@link ThreadPoolExecutor} that can schedule commands to run
13     * after a given delay, or to execute periodically. This class is
14     * preferable to {@link java.util.Timer} when multiple worker threads
15     * are needed, or when the additional flexibility or capabilities of
16     * {@link ThreadPoolExecutor} (which this class extends) are required.
17     *
18     * <p> Delayed tasks execute no sooner than they are enabled, but
19     * without any real-time guarantees about when, after they are enabled,
20     * they will commence. Tasks tied for the same execution time are
21     * enabled in first-in-first-out (FIFO) order of submission.
22     *
23     * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
24     * of the inherited tuning methods are not especially useful for
25     * it. In particular, because a <tt>ScheduledExecutor</tt> always acts
26     * as a fixed-sized pool using <tt>corePoolSize</tt> threads and an
27     * unbounded queue, adjustments to <tt>maximumPoolSize</tt> have no
28     * useful effect.
29     *
30     * @since 1.5
31     * @author Doug Lea
32     */
33 tim 1.3 public class ScheduledThreadPoolExecutor
34     extends ThreadPoolExecutor
35     implements ScheduledExecutorService {
36 dl 1.1
37     /**
38     * False if should cancel/suppress periodic tasks on shutdown.
39     */
40     private volatile boolean continueExistingPeriodicTasksAfterShutdown;
41    
42     /**
43     * False if should cancel non-periodic tasks on shutdown.
44     */
45     private volatile boolean executeExistingDelayedTasksAfterShutdown = true;
46    
47    
48     /**
49     * Sequence number to break scheduling ties, and in turn to
50     * guarantee FIFO order among tied entries.
51     */
52     private static final AtomicLong sequencer = new AtomicLong(0);
53    
54     private static class ScheduledFutureTask<V>
55     extends FutureTask<V> implements ScheduledFuture<V> {
56    
57     /** Sequence number to break ties FIFO */
58     private final long sequenceNumber;
59     /** The time the task is enabled to execute in nanoTime units */
60     private long time;
61     /** The delay following next time, or <= 0 if non-periodic */
62     private final long period;
63     /** true if at fixed rate; false if fixed delay */
64     private final boolean rateBased;
65    
66    
67     /**
68     * Creates a one-shot action with given nanoTime-based trigger time
69     */
70     ScheduledFutureTask(Runnable r, V result, long ns) {
71     super(r, result);
72     this.time = ns;
73     this.period = 0;
74     rateBased = false;
75     this.sequenceNumber = sequencer.getAndIncrement();
76     }
77    
78     /**
79     * Creates a periodic action with given nano time and period
80     */
81     ScheduledFutureTask(Runnable r, V result, long ns, long period, boolean rateBased) {
82     super(r, result);
83     this.time = ns;
84     this.period = period;
85     this.rateBased = rateBased;
86     this.sequenceNumber = sequencer.getAndIncrement();
87     }
88    
89     /**
90     * Creates a one-shot action with given nanoTime-based trigger
91     */
92     ScheduledFutureTask(Callable<V> callable, long ns) {
93     super(callable);
94     this.time = ns;
95     this.period = 0;
96     rateBased = false;
97     this.sequenceNumber = sequencer.getAndIncrement();
98     }
99    
100    
101     public long getDelay(TimeUnit unit) {
102     long d = unit.convert(time - System.nanoTime(),
103     TimeUnit.NANOSECONDS);
104     return d;
105     }
106    
107     public int compareTo(Object other) {
108     if (other == this) // compare zero ONLY if same object
109     return 0;
110     ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
111     long diff = time - x.time;
112     if (diff < 0)
113     return -1;
114     else if (diff > 0)
115     return 1;
116     else if (sequenceNumber < x.sequenceNumber)
117     return -1;
118     else
119     return 1;
120     }
121    
122     /**
123     * Return true if this is a periodic (not a one-shot) action.
124     * @return true if periodic
125     */
126     public boolean isPeriodic() {
127     return period > 0;
128     }
129    
130     /**
131     * Returns the period, or zero if non-periodic.
132     *
133     * @return the period
134     */
135     public long getPeriod(TimeUnit unit) {
136     return unit.convert(period, TimeUnit.NANOSECONDS);
137     }
138    
139     /**
140 dl 1.2 * Overrides FutureTask version so as to reset if periodic.
141 dl 1.1 */
142     public void run() {
143 dl 1.2 if (isPeriodic())
144     runAndReset();
145     else
146     super.run();
147 dl 1.1 }
148    
149     /**
150     * Return a task (which may be this task) that will trigger in
151     * the period subsequent to current task, or null if
152     * non-periodic or cancelled.
153     */
154     ScheduledFutureTask nextTask() {
155     if (period <= 0 || !reset())
156     return null;
157     time = period + (rateBased ? time : System.nanoTime());
158     return this;
159     }
160     }
161    
162     /**
163     * An annoying wrapper class to convince generics compiler to
164     * use a DelayQueue<ScheduledFutureTask> as a BlockingQueue<Runnable>
165     */
166     private static class DelayedWorkQueue
167     extends AbstractCollection<Runnable> implements BlockingQueue<Runnable> {
168    
169     private final DelayQueue<ScheduledFutureTask> dq = new DelayQueue<ScheduledFutureTask>();
170     public Runnable poll() { return dq.poll(); }
171     public Runnable peek() { return dq.peek(); }
172     public Runnable take() throws InterruptedException { return dq.take(); }
173     public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
174     return dq.poll(timeout, unit);
175     }
176    
177     public boolean add(Runnable x) { return dq.add((ScheduledFutureTask)x); }
178     public boolean offer(Runnable x) { return dq.offer((ScheduledFutureTask)x); }
179     public void put(Runnable x) {
180     dq.put((ScheduledFutureTask)x);
181     }
182     public boolean offer(Runnable x, long timeout, TimeUnit unit) {
183     return dq.offer((ScheduledFutureTask)x, timeout, unit);
184     }
185    
186     public Runnable remove() { return dq.remove(); }
187     public Runnable element() { return dq.element(); }
188     public void clear() { dq.clear(); }
189     public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
190     public int drainTo(Collection<? super Runnable> c, int maxElements) {
191     return dq.drainTo(c, maxElements);
192     }
193    
194     public int remainingCapacity() { return dq.remainingCapacity(); }
195     public boolean remove(Object x) { return dq.remove(x); }
196     public boolean contains(Object x) { return dq.contains(x); }
197     public int size() { return dq.size(); }
198     public boolean isEmpty() { return dq.isEmpty(); }
199     public Object[] toArray() { return dq.toArray(); }
200     public <T> T[] toArray(T[] array) { return dq.toArray(array); }
201     public Iterator<Runnable> iterator() {
202     return new Iterator<Runnable>() {
203     private Iterator<ScheduledFutureTask> it = dq.iterator();
204     public boolean hasNext() { return it.hasNext(); }
205     public Runnable next() { return it.next(); }
206     public void remove() { it.remove(); }
207     };
208     }
209     }
210    
211     /**
212     * Creates a new ScheduledThreadPoolExecutor with the given core pool size.
213     *
214     * @param corePoolSize the number of threads to keep in the pool,
215     * even if they are idle.
216     * @throws IllegalArgumentException if corePoolSize less than or
217     * equal to zero
218     */
219     public ScheduledThreadPoolExecutor(int corePoolSize) {
220     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
221     new DelayedWorkQueue());
222     }
223    
224     /**
225     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
226     *
227     * @param corePoolSize the number of threads to keep in the pool,
228     * even if they are idle.
229     * @param threadFactory the factory to use when the executor
230     * creates a new thread.
231     * @throws NullPointerException if threadFactory is null
232     */
233     public ScheduledThreadPoolExecutor(int corePoolSize,
234     ThreadFactory threadFactory) {
235     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
236     new DelayedWorkQueue(), threadFactory);
237     }
238    
239     /**
240     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
241     *
242     * @param corePoolSize the number of threads to keep in the pool,
243     * even if they are idle.
244     * @param handler the handler to use when execution is blocked
245     * because the thread bounds and queue capacities are reached.
246     * @throws NullPointerException if handler is null
247     */
248     public ScheduledThreadPoolExecutor(int corePoolSize,
249     RejectedExecutionHandler handler) {
250     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
251     new DelayedWorkQueue(), handler);
252     }
253    
254     /**
255     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
256     *
257     * @param corePoolSize the number of threads to keep in the pool,
258     * even if they are idle.
259     * @param threadFactory the factory to use when the executor
260     * creates a new thread.
261     * @param handler the handler to use when execution is blocked
262     * because the thread bounds and queue capacities are reached.
263     * @throws NullPointerException if threadFactory or handler is null
264     */
265     public ScheduledThreadPoolExecutor(int corePoolSize,
266     ThreadFactory threadFactory,
267     RejectedExecutionHandler handler) {
268     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
269     new DelayedWorkQueue(), threadFactory, handler);
270     }
271    
272     /**
273     * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
274     */
275     private void delayedExecute(Runnable command) {
276     if (isShutdown()) {
277     reject(command);
278     return;
279     }
280     // Prestart a thread if necessary. We cannot prestart it
281     // running the task because the task (probably) shouldn't be
282     // run yet, so thread will just idle until delay elapses.
283     if (getPoolSize() < getCorePoolSize())
284     prestartCoreThread();
285    
286     super.getQueue().add(command);
287     }
288    
289     /**
290     * Creates and executes a one-shot action that becomes enabled after
291     * the given delay.
292     * @param command the task to execute.
293     * @param delay the time from now to delay execution.
294     * @param unit the time unit of the delay parameter.
295     * @return a Future representing pending completion of the task,
296     * and whose <tt>get()</tt> method will return <tt>Boolean.TRUE</tt>
297     * upon completion.
298     * @throws RejectedExecutionException if task cannot be scheduled
299     * for execution because the executor has been shut down.
300     * @throws NullPointerException if command is null
301     */
302    
303     public ScheduledFuture<Boolean> schedule(Runnable command, long delay, TimeUnit unit) {
304     if (command == null)
305     throw new NullPointerException();
306     long triggerTime = System.nanoTime() + unit.toNanos(delay);
307     ScheduledFutureTask<Boolean> t = new ScheduledFutureTask<Boolean>(command, Boolean.TRUE, triggerTime);
308     delayedExecute(t);
309     return t;
310     }
311    
312     /**
313     * Creates and executes a ScheduledFuture that becomes enabled after the
314     * given delay.
315     * @param callable the function to execute.
316     * @param delay the time from now to delay execution.
317     * @param unit the time unit of the delay parameter.
318     * @return a ScheduledFuture that can be used to extract result or cancel.
319     * @throws RejectedExecutionException if task cannot be scheduled
320     * for execution because the executor has been shut down.
321     * @throws NullPointerException if callable is null
322     */
323     public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
324     if (callable == null)
325     throw new NullPointerException();
326     long triggerTime = System.nanoTime() + unit.toNanos(delay);
327     ScheduledFutureTask<V> t = new ScheduledFutureTask<V>(callable, triggerTime);
328     delayedExecute(t);
329     return t;
330     }
331    
332     /**
333     * Creates and executes a periodic action that becomes enabled first
334     * after the given initial delay, and subsequently with the given
335     * period; that is executions will commence after
336     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
337     * <tt>initialDelay + 2 * period</tt>, and so on. The
338     * task will only terminate via cancellation.
339     * @param command the task to execute.
340     * @param initialDelay the time to delay first execution.
341     * @param period the period between successive executions.
342     * @param unit the time unit of the delay and period parameters
343     * @return a Future representing pending completion of the task,
344     * and whose <tt>get()</tt> method will throw an exception upon
345     * cancellation.
346     * @throws RejectedExecutionException if task cannot be scheduled
347     * for execution because the executor has been shut down.
348     * @throws NullPointerException if command is null
349     * @throws IllegalArgumentException if period less than or equal to zero.
350     */
351     public ScheduledFuture<Boolean> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
352     if (command == null)
353     throw new NullPointerException();
354     if (period <= 0)
355     throw new IllegalArgumentException();
356     long triggerTime = System.nanoTime() + unit.toNanos(initialDelay);
357     ScheduledFutureTask<Boolean> t = new ScheduledFutureTask<Boolean>
358     (command, Boolean.TRUE,
359     triggerTime,
360     unit.toNanos(period),
361     true);
362     delayedExecute(t);
363     return t;
364     }
365    
366     /**
367     * Creates and executes a periodic action that becomes enabled first
368     * after the given initial delay, and subsequently with the
369     * given delay between the termination of one execution and the
370     * commencement of the next.
371     * The task will only terminate via cancellation.
372     * @param command the task to execute.
373     * @param initialDelay the time to delay first execution.
374     * @param delay the delay between the termination of one
375     * execution and the commencement of the next.
376     * @param unit the time unit of the delay and delay parameters
377     * @return a Future representing pending completion of the task,
378     * and whose <tt>get()</tt> method will throw an exception upon
379     * cancellation.
380     * @throws RejectedExecutionException if task cannot be scheduled
381     * for execution because the executor has been shut down.
382     * @throws NullPointerException if command is null
383     * @throws IllegalArgumentException if delay less than or equal to zero.
384     */
385     public ScheduledFuture<Boolean> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
386     if (command == null)
387     throw new NullPointerException();
388     if (delay <= 0)
389     throw new IllegalArgumentException();
390     long triggerTime = System.nanoTime() + unit.toNanos(initialDelay);
391     ScheduledFutureTask<Boolean> t = new ScheduledFutureTask<Boolean>
392     (command,
393     Boolean.TRUE,
394     triggerTime,
395     unit.toNanos(delay),
396     false);
397     delayedExecute(t);
398     return t;
399     }
400    
401    
402     /**
403     * Execute command with zero required delay. This has effect
404     * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
405     * that inspections of the queue and of the list returned by
406     * <tt>shutdownNow</tt> will access the zero-delayed
407     * {@link ScheduledFuture}, not the <tt>command</tt> itself.
408     *
409     * @param command the task to execute
410     * @throws RejectedExecutionException at discretion of
411     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
412     * for execution because the executor has been shut down.
413     * @throws NullPointerException if command is null
414     */
415     public void execute(Runnable command) {
416     if (command == null)
417     throw new NullPointerException();
418     schedule(command, 0, TimeUnit.NANOSECONDS);
419     }
420    
421    
422     /**
423     * Set policy on whether to continue executing existing periodic
424     * tasks even when this executor has been <tt>shutdown</tt>. In
425     * this case, these tasks will only terminate upon
426     * <tt>shutdownNow</tt>, or after setting the policy to
427     * <tt>false</tt> when already shutdown. This value is by default
428     * false.
429     * @param value if true, continue after shutdown, else don't.
430     */
431     public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
432     continueExistingPeriodicTasksAfterShutdown = value;
433     if (!value && isShutdown())
434     cancelUnwantedTasks();
435     }
436    
437     /**
438     * Get the policy on whether to continue executing existing
439     * periodic tasks even when this executor has been
440     * <tt>shutdown</tt>. In this case, these tasks will only
441     * terminate upon <tt>shutdownNow</tt> or after setting the policy
442     * to <tt>false</tt> when already shutdown. This value is by
443     * default false.
444     * @return true if will continue after shutdown.
445     */
446     public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
447     return continueExistingPeriodicTasksAfterShutdown;
448     }
449    
450     /**
451     * Set policy on whether to execute existing delayed
452     * tasks even when this executor has been <tt>shutdown</tt>. In
453     * this case, these tasks will only terminate upon
454     * <tt>shutdownNow</tt>, or after setting the policy to
455     * <tt>false</tt> when already shutdown. This value is by default
456     * true.
457     * @param value if true, execute after shutdown, else don't.
458     */
459     public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
460     executeExistingDelayedTasksAfterShutdown = value;
461     if (!value && isShutdown())
462     cancelUnwantedTasks();
463     }
464    
465     /**
466     * Get policy on whether to execute existing delayed
467     * tasks even when this executor has been <tt>shutdown</tt>. In
468     * this case, these tasks will only terminate upon
469     * <tt>shutdownNow</tt>, or after setting the policy to
470     * <tt>false</tt> when already shutdown. This value is by default
471     * true.
472     * @return true if will execute after shutdown.
473     */
474     public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
475     return executeExistingDelayedTasksAfterShutdown;
476     }
477    
478     /**
479     * Cancel and clear the queue of all tasks that should not be run
480     * due to shutdown policy.
481     */
482     private void cancelUnwantedTasks() {
483     boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
484     boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
485     if (!keepDelayed && !keepPeriodic)
486     super.getQueue().clear();
487     else if (keepDelayed || keepPeriodic) {
488     Object[] entries = super.getQueue().toArray();
489     for (int i = 0; i < entries.length; ++i) {
490     ScheduledFutureTask<?> t = (ScheduledFutureTask<?>)entries[i];
491     if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
492     t.cancel(false);
493     }
494     entries = null;
495     purge();
496     }
497     }
498    
499     /**
500     * Initiates an orderly shutdown in which previously submitted
501     * tasks are executed, but no new tasks will be accepted. If the
502     * <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
503     * been set <tt>false</tt>, existing delayed tasks whose delays
504     * have not yet elapsed are cancelled. And unless the
505     * <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
506     * been set <tt>true</tt>, future executions of existing periodic
507     * tasks will be cancelled.
508     */
509     public void shutdown() {
510     cancelUnwantedTasks();
511     super.shutdown();
512     }
513    
514     /**
515     * Attempts to stop all actively executing tasks, halts the
516     * processing of waiting tasks, and returns a list of the tasks that were
517     * awaiting execution.
518     *
519     * <p>There are no guarantees beyond best-effort attempts to stop
520     * processing actively executing tasks. This implementations
521     * cancels via {@link Thread#interrupt}, so if any tasks mask or
522     * fail to respond to interrupts, they may never terminate.
523     *
524     * @return list of tasks that never commenced execution. Each
525     * element of this list is a {@link ScheduledFuture},
526     * including those tasks submitted using <tt>execute</tt> which
527     * are for scheduling purposes used as the basis of a zero-delay
528     * <tt>ScheduledFuture</tt>.
529     */
530 tim 1.4 public List<Runnable> shutdownNow() {
531 dl 1.1 return super.shutdownNow();
532     }
533    
534     /**
535     * Removes this task from internal queue if it is present, thus
536     * causing it not to be run if it has not already started. This
537     * method may be useful as one part of a cancellation scheme.
538     *
539     * @param task the task to remove
540     * @return true if the task was removed
541     */
542     public boolean remove(Runnable task) {
543     if (task instanceof ScheduledFuture)
544     return super.remove(task);
545    
546     // The task might actually have been wrapped as a ScheduledFuture
547     // in execute(), in which case we need to manually traverse
548     // looking for it.
549    
550     ScheduledFuture wrap = null;
551     Object[] entries = super.getQueue().toArray();
552     for (int i = 0; i < entries.length; ++i) {
553     ScheduledFutureTask<?> t = (ScheduledFutureTask<?>)entries[i];
554 dl 1.2 Object r = t.getTask();
555 dl 1.1 if (task.equals(r)) {
556     wrap = t;
557     break;
558     }
559     }
560     entries = null;
561     return wrap != null && super.getQueue().remove(wrap);
562     }
563    
564    
565     /**
566     * Returns the task queue used by this executor. Each element of
567     * this queue is a {@link ScheduledFuture}, including those
568     * tasks submitted using <tt>execute</tt> which are for scheduling
569     * purposes used as the basis of a zero-delay
570     * <tt>ScheduledFuture</tt>. Iteration over this queue is
571     * </em>not</em> guaranteed to traverse tasks in the order in
572     * which they will execute.
573     *
574     * @return the task queue
575     */
576     public BlockingQueue<Runnable> getQueue() {
577     return super.getQueue();
578     }
579    
580     /**
581     * Override of <tt>Executor</tt> hook method to support periodic
582     * tasks. If the executed task was periodic, causes the task for
583     * the next period to execute.
584     * @param r the task (assumed to be a ScheduledFuture)
585     * @param t the exception
586     */
587     protected void afterExecute(Runnable r, Throwable t) {
588     super.afterExecute(r, t);
589     ScheduledFutureTask<?> next = ((ScheduledFutureTask<?>)r).nextTask();
590     if (next != null &&
591     (!isShutdown() ||
592     (getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
593     !isTerminating())))
594     super.getQueue().add(next);
595    
596     // This might have been the final executed delayed task. Wake
597     // up threads to check.
598     else if (isShutdown())
599     interruptIdleWorkers();
600     }
601     }