ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.5
Committed: Sun Dec 14 15:50:13 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.4: +20 -40 lines
Log Message:
Added any/all methods

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