ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.2
Committed: Fri Dec 5 11:57:52 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.1: +6 -18 lines
Log Message:
Avoid needing package-private fields

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