ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledExecutor.java
Revision: 1.16
Committed: Mon Aug 11 19:41:03 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.15: +5 -1 lines
Log Message:
Clarified execute javadoc

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.4 * 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 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.4 import java.util.concurrent.atomic.*;
9 dl 1.2 import java.util.*;
10 tim 1.1
11     /**
12 dl 1.7 * An <tt>Executor</tt> that can schedule command to run after a given
13     * delay, or to execute periodically. This class is preferable to
14 tim 1.1 * <tt>java.util.Timer</tt> when multiple worker threads are needed,
15     * or when the additional flexibility or capabilities of
16 dl 1.7 * <tt>ThreadPoolExecutor</tt> (which this class extends) are
17     * required.
18     *
19     * <p> The <tt>schedule</tt> methods create tasks with various delays
20     * and return a task object that can be used to cancel or check
21     * execution. The <tt>scheduleAtFixedRate</tt> and
22     * <tt>scheduleWithFixedDelay</tt> methods create and execute tasks
23     * that run periodically until cancelled. Commands submitted using
24     * the <tt>execute</tt> method are scheduled with a requested delay of
25     * zero.
26     *
27     * <p> Delayed tasks execute no sooner than they are enabled, but
28     * without any real-time guarantees about when, after they are enabled
29     * they will commence. Tasks tied for the same execution time are
30     * enabled in first-in-first-out (FIFO) order of submission. An
31     * internal {@link DelayQueue} used for scheduling relies on relative
32     * delays, which may drift from absolute times (as returned by
33     * <tt>System.currentTimeMillis</tt>) over sufficiently long periods.
34 tim 1.1 *
35 dl 1.13 * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
36     * of the inherited tuning methods are not especially useful for
37     * it. In particular, because a <tt>ScheduledExecutor</tt> always acts
38     * as a fixed-sized pool using <tt>corePoolSize</tt> threads and an
39     * unbounded queue, adjustments to <tt>maximumPoolSize</tt> have no
40     * useful effect.
41     *
42 tim 1.1 * @since 1.5
43     * @see Executors
44     *
45     * @spec JSR-166
46 dl 1.9 * @author Doug Lea
47 tim 1.1 */
48     public class ScheduledExecutor extends ThreadPoolExecutor {
49    
50 dl 1.4 /**
51 dl 1.5 * Sequence number to break scheduling ties, and in turn to
52     * guarantee FIFO order among tied entries.
53     */
54     private static final AtomicLong sequencer = new AtomicLong(0);
55    
56     /**
57 dl 1.4 * A delayed or periodic action.
58     */
59 dl 1.8 public static class DelayedTask extends CancellableTask implements Delayed {
60 dl 1.9 /** Sequence number to break ties FIFO */
61 dl 1.4 private final long sequenceNumber;
62 dl 1.9 /** The time the task is enabled to execute in nanoTime units */
63 dl 1.4 private final long time;
64 dl 1.9 /** The delay forllowing next time, or <= 0 if non-periodic */
65 dl 1.4 private final long period;
66 dl 1.9 /** true if at fixed rate; false if fixed delay */
67     private final boolean rateBased;
68    
69 dl 1.4 /**
70 dl 1.5 * Creates a one-shot action with given nanoTime-based trigger time
71 dl 1.4 */
72     DelayedTask(Runnable r, long ns) {
73     super(r);
74     this.time = ns;
75     this.period = 0;
76 dl 1.7 rateBased = false;
77 dl 1.4 this.sequenceNumber = sequencer.getAndIncrement();
78     }
79    
80     /**
81 dl 1.5 * Creates a periodic action with given nano time and period
82 dl 1.4 */
83 dl 1.7 DelayedTask(Runnable r, long ns, long period, boolean rateBased) {
84 dl 1.4 super(r);
85     if (period <= 0)
86     throw new IllegalArgumentException();
87     this.time = ns;
88     this.period = period;
89 dl 1.7 this.rateBased = rateBased;
90 dl 1.4 this.sequenceNumber = sequencer.getAndIncrement();
91     }
92    
93    
94     public long getDelay(TimeUnit unit) {
95 dl 1.12 long d = unit.convert(time - System.nanoTime(),
96 dl 1.7 TimeUnit.NANOSECONDS);
97 dl 1.12 return d;
98 dl 1.4 }
99    
100     public int compareTo(Object other) {
101 dl 1.15 if (other == this)
102     return 0;
103 dl 1.4 DelayedTask x = (DelayedTask)other;
104     long diff = time - x.time;
105     if (diff < 0)
106     return -1;
107     else if (diff > 0)
108     return 1;
109     else if (sequenceNumber < x.sequenceNumber)
110     return -1;
111     else
112     return 1;
113     }
114    
115     /**
116     * Return true if this is a periodic (not a one-shot) action.
117 dl 1.9 * @return true if periodic
118 dl 1.4 */
119     public boolean isPeriodic() {
120     return period > 0;
121     }
122    
123     /**
124 tim 1.11 * Returns the period, or zero if non-periodic.
125     *
126 dl 1.9 * @return the period
127 dl 1.4 */
128     public long getPeriod(TimeUnit unit) {
129     return unit.convert(period, TimeUnit.NANOSECONDS);
130     }
131    
132     /**
133     * Return a new DelayedTask that will trigger in the period
134     * subsequent to current task, or null if non-periodic
135     * or canceled.
136     */
137 dl 1.5 DelayedTask nextTask() {
138 dl 1.4 if (period <= 0 || isCancelled())
139     return null;
140 dl 1.10 long nextTime = period + (rateBased ? time : System.nanoTime());
141 dl 1.7 return new DelayedTask(getRunnable(), nextTime, period, rateBased);
142 dl 1.4 }
143 dl 1.2
144 dl 1.4 }
145 dl 1.2
146 dl 1.4 /**
147     * A delayed result-bearing action.
148     */
149 dl 1.8 public static class DelayedFutureTask<V> extends DelayedTask implements Future<V> {
150 dl 1.4 /**
151     * Creates a Future that may trigger after the given delay.
152     */
153     DelayedFutureTask(Callable<V> callable, long delay, TimeUnit unit) {
154     // must set after super ctor call to use inner class
155 dl 1.10 super(null, System.nanoTime() + unit.toNanos(delay));
156 dl 1.4 setRunnable(new InnerCancellableFuture<V>(callable));
157 dl 1.2 }
158    
159 dl 1.4 /**
160     * Creates a one-shot action that may trigger after the given date.
161     */
162     DelayedFutureTask(Callable<V> callable, Date date) {
163     super(null,
164     TimeUnit.MILLISECONDS.toNanos(date.getTime() -
165     System.currentTimeMillis()));
166     setRunnable(new InnerCancellableFuture<V>(callable));
167     }
168    
169     public V get() throws InterruptedException, ExecutionException {
170     return ((InnerCancellableFuture<V>)getRunnable()).get();
171 dl 1.2 }
172    
173 dl 1.4 public V get(long timeout, TimeUnit unit)
174     throws InterruptedException, ExecutionException, TimeoutException {
175     return ((InnerCancellableFuture<V>)getRunnable()).get(timeout, unit);
176 dl 1.2 }
177 tim 1.1
178 dl 1.4 protected void set(V v) {
179     ((InnerCancellableFuture<V>)getRunnable()).set(v);
180 dl 1.2 }
181 tim 1.1
182 dl 1.4 protected void setException(Throwable t) {
183     ((InnerCancellableFuture<V>)getRunnable()).setException(t);
184     }
185     }
186    
187    
188     /**
189     * An annoying wrapper class to convince generics compiler to
190 dl 1.7 * use a DelayQueue<DelayedTask> as a BlockingQueue<Runnable>
191 dl 1.4 */
192 dl 1.12 private static class DelayedWorkQueue extends AbstractCollection<Runnable> implements BlockingQueue<Runnable> {
193 dl 1.4 private final DelayQueue<DelayedTask> dq = new DelayQueue<DelayedTask>();
194     public Runnable poll() { return dq.poll(); }
195     public Runnable peek() { return dq.peek(); }
196     public Runnable take() throws InterruptedException { return dq.take(); }
197     public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
198     return dq.poll(timeout, unit);
199 dl 1.2 }
200 dl 1.12
201     public boolean add(Runnable x) { return dq.add((DelayedTask)x); }
202 dl 1.4 public boolean offer(Runnable x) { return dq.offer((DelayedTask)x); }
203     public void put(Runnable x) throws InterruptedException {
204     dq.put((DelayedTask)x);
205 dl 1.2 }
206 dl 1.4 public boolean offer(Runnable x, long timeout, TimeUnit unit) throws InterruptedException {
207     return dq.offer((DelayedTask)x, timeout, unit);
208 dl 1.2 }
209 dl 1.12
210     public Runnable remove() { return dq.remove(); }
211     public Runnable element() { return dq.element(); }
212     public void clear() { dq.clear(); }
213    
214 dl 1.4 public int remainingCapacity() { return dq.remainingCapacity(); }
215     public boolean remove(Object x) { return dq.remove(x); }
216     public boolean contains(Object x) { return dq.contains(x); }
217     public int size() { return dq.size(); }
218 tim 1.11 public boolean isEmpty() { return dq.isEmpty(); }
219 dl 1.4 public Iterator<Runnable> iterator() {
220     return new Iterator<Runnable>() {
221     private Iterator<DelayedTask> it = dq.iterator();
222     public boolean hasNext() { return it.hasNext(); }
223     public Runnable next() { return it.next(); }
224     public void remove() { it.remove(); }
225     };
226 tim 1.1 }
227 dl 1.4 }
228 tim 1.1
229 dl 1.4 /**
230     * Creates a new ScheduledExecutor with the given initial parameters.
231     *
232     * @param corePoolSize the number of threads to keep in the pool,
233     * even if they are idle.
234     */
235     public ScheduledExecutor(int corePoolSize) {
236     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
237     new DelayedWorkQueue());
238     }
239 tim 1.1
240 dl 1.4 /**
241     * Creates a new ScheduledExecutor 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 threadFactory the factory to use when the executor
246     * creates a new thread.
247     */
248     public ScheduledExecutor(int corePoolSize,
249     ThreadFactory threadFactory) {
250     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
251     new DelayedWorkQueue(), threadFactory);
252 tim 1.1 }
253    
254 dl 1.4 /**
255     * Creates a new ScheduledExecutor 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 handler the handler to use when execution is blocked
260     * because the thread bounds and queue capacities are reached.
261     */
262     public ScheduledExecutor(int corePoolSize,
263     RejectedExecutionHandler handler) {
264     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
265     new DelayedWorkQueue(), handler);
266     }
267 dl 1.2
268 tim 1.1 /**
269 dl 1.2 * Creates a new ScheduledExecutor with the given initial parameters.
270     *
271     * @param corePoolSize the number of threads to keep in the pool,
272     * even if they are idle.
273 dl 1.4 * @param threadFactory the factory to use when the executor
274     * creates a new thread.
275     * @param handler the handler to use when execution is blocked
276     * because the thread bounds and queue capacities are reached.
277 tim 1.1 */
278 dl 1.4 public ScheduledExecutor(int corePoolSize,
279     ThreadFactory threadFactory,
280     RejectedExecutionHandler handler) {
281 dl 1.2 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
282 dl 1.4 new DelayedWorkQueue(), threadFactory, handler);
283 dl 1.13 }
284    
285     /**
286     * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
287     */
288     void delayedExecute(Runnable command) {
289     if (isShutdown()) {
290     reject(command);
291     return;
292     }
293     // Prestart thread if necessary. We cannot prestart it running
294     // the task because the task (probably) shouldn't be run yet,
295     // so thread will just idle until delay elapses.
296     if (getPoolSize() < getCorePoolSize())
297     addIfUnderCorePoolSize(null);
298    
299     getQueue().offer(command);
300 dl 1.4 }
301    
302     /**
303 dl 1.7 * Creates and executes a one-shot action that becomes enabled after
304 dl 1.4 * the given delay.
305 dl 1.6 * @param command the task to execute.
306     * @param delay the time from now to delay execution.
307     * @param unit the time unit of the delay parameter.
308     * @return a handle that can be used to cancel the task.
309 dl 1.4 */
310    
311 dl 1.6 public DelayedTask schedule(Runnable command, long delay, TimeUnit unit) {
312 dl 1.10 DelayedTask t = new DelayedTask(command, System.nanoTime() + unit.toNanos(delay));
313 dl 1.13 delayedExecute(t);
314 dl 1.4 return t;
315     }
316    
317     /**
318 dl 1.9 * Creates and executes a one-shot action that becomes enabled
319     * after the given date.
320 dl 1.6 * @param command the task to execute.
321     * @param date the time to commence excution.
322     * @return a handle that can be used to cancel the task.
323     * @throws RejectedExecutionException if task cannot be scheduled
324     * for execution because the executor has been shut down.
325 dl 1.4 */
326 dl 1.6 public DelayedTask schedule(Runnable command, Date date) {
327 dl 1.4 DelayedTask t = new DelayedTask
328 dl 1.6 (command,
329 dl 1.4 TimeUnit.MILLISECONDS.toNanos(date.getTime() -
330     System.currentTimeMillis()));
331 dl 1.13 delayedExecute(t);
332 dl 1.4 return t;
333     }
334    
335     /**
336 dl 1.7 * Creates and executes a periodic action that becomes enabled first
337 dl 1.4 * after the given initial delay, and subsequently with the given
338 dl 1.7 * period; that is executions will commence after
339     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
340     * <tt>initialDelay + 2 * period</tt>, and so on.
341 dl 1.6 * @param command the task to execute.
342     * @param initialDelay the time to delay first execution.
343     * @param period the period between successive executions.
344     * @param unit the time unit of the delay and period parameters
345     * @return a handle that can be used to cancel the task.
346     * @throws RejectedExecutionException if task cannot be scheduled
347     * for execution because the executor has been shut down.
348 dl 1.4 */
349 dl 1.7 public DelayedTask scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
350 dl 1.4 DelayedTask t = new DelayedTask
351 dl 1.10 (command, System.nanoTime() + unit.toNanos(initialDelay),
352 dl 1.7 unit.toNanos(period), true);
353 dl 1.13 delayedExecute(t);
354 dl 1.4 return t;
355     }
356    
357     /**
358 dl 1.7 * Creates a periodic action that becomes enabled first after the
359     * given date, and subsequently with the given period
360     * period; that is executions will commence after
361     * <tt>initialDate</tt> then <tt>initialDate+period</tt>, then
362     * <tt>initialDate + 2 * period</tt>, and so on.
363 dl 1.6 * @param command the task to execute.
364     * @param initialDate the time to delay first execution.
365 dl 1.7 * @param period the period between commencement of successive
366     * executions.
367 dl 1.6 * @param unit the time unit of the period parameter.
368     * @return a handle that can be used to cancel the task.
369     * @throws RejectedExecutionException if task cannot be scheduled
370     * for execution because the executor has been shut down.
371 dl 1.4 */
372 dl 1.7 public DelayedTask scheduleAtFixedRate(Runnable command, Date initialDate, long period, TimeUnit unit) {
373     DelayedTask t = new DelayedTask
374     (command,
375     TimeUnit.MILLISECONDS.toNanos(initialDate.getTime() -
376     System.currentTimeMillis()),
377     unit.toNanos(period), true);
378 dl 1.13 delayedExecute(t);
379 dl 1.7 return t;
380     }
381    
382     /**
383     * Creates and executes a periodic action that becomes enabled first
384     * after the given initial delay, and and subsequently with the
385     * given delay between the termination of one execution and the
386     * commencement of the next.
387     * @param command the task to execute.
388     * @param initialDelay the time to delay first execution.
389     * @param delay the delay between the termination of one
390     * execution and the commencement of the next.
391     * @param unit the time unit of the delay and delay parameters
392     * @return a handle that can be used to cancel the task.
393     * @throws RejectedExecutionException if task cannot be scheduled
394     * for execution because the executor has been shut down.
395     */
396     public DelayedTask scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
397     DelayedTask t = new DelayedTask
398 dl 1.10 (command, System.nanoTime() + unit.toNanos(initialDelay),
399 dl 1.7 unit.toNanos(delay), false);
400 dl 1.13 delayedExecute(t);
401 dl 1.7 return t;
402     }
403    
404     /**
405     * Creates a periodic action that becomes enabled first after the
406     * given date, and subsequently with the given delay between
407     * the termination of one execution and the commencement of the
408     * next.
409     * @param command the task to execute.
410     * @param initialDate the time to delay first execution.
411     * @param delay the delay between the termination of one
412     * execution and the commencement of the next.
413     * @param unit the time unit of the delay parameter.
414     * @return a handle that can be used to cancel the task.
415     * @throws RejectedExecutionException if task cannot be scheduled
416     * for execution because the executor has been shut down.
417     */
418     public DelayedTask scheduleWithFixedDelay(Runnable command, Date initialDate, long delay, TimeUnit unit) {
419 dl 1.4 DelayedTask t = new DelayedTask
420 dl 1.6 (command,
421     TimeUnit.MILLISECONDS.toNanos(initialDate.getTime() -
422 dl 1.4 System.currentTimeMillis()),
423 dl 1.7 unit.toNanos(delay), false);
424 dl 1.13 delayedExecute(t);
425 dl 1.4 return t;
426 tim 1.1 }
427    
428    
429 dl 1.4 /**
430 dl 1.7 * Creates and executes a Future that becomes enabled after the
431     * given delay.
432 dl 1.6 * @param callable the function to execute.
433     * @param delay the time from now to delay execution.
434     * @param unit the time unit of the delay parameter.
435     * @return a Future that can be used to extract result or cancel.
436     * @throws RejectedExecutionException if task cannot be scheduled
437     * for execution because the executor has been shut down.
438 dl 1.4 */
439     public <V> DelayedFutureTask<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
440     DelayedFutureTask<V> t = new DelayedFutureTask<V>
441     (callable, delay, unit);
442 dl 1.13 delayedExecute(t);
443 dl 1.4 return t;
444     }
445    
446     /**
447 dl 1.7 * Creates and executes a one-shot action that becomes enabled after
448 dl 1.4 * the given date.
449 dl 1.6 * @param callable the function to execute.
450     * @param date the time to commence excution.
451     * @return a Future that can be used to extract result or cancel.
452     * @throws RejectedExecutionException if task cannot be scheduled
453     * for execution because the executor has been shut down.
454 dl 1.4 */
455     public <V> DelayedFutureTask<V> schedule(Callable<V> callable, Date date) {
456     DelayedFutureTask<V> t = new DelayedFutureTask<V>
457     (callable, date);
458 dl 1.13 delayedExecute(t);
459 dl 1.4 return t;
460 tim 1.1 }
461    
462 dl 1.4 /**
463 dl 1.16 * Execute command with zero required delay. This has effect
464     * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
465     * that inspections of the queue and of the list returned by
466     * <tt>shutdownNow</tt> will access the zero-delayed
467     * <tt>DelayedTask</tt>, not the <tt>command</tt> itself.
468 tim 1.11 *
469 dl 1.6 * @param command the task to execute
470     * @throws RejectedExecutionException at discretion of
471     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
472     * for execution because the executor has been shut down.
473 dl 1.4 */
474     public void execute(Runnable command) {
475     schedule(command, 0, TimeUnit.NANOSECONDS);
476 tim 1.1 }
477    
478 dl 1.4 /**
479 dl 1.15 * Removes this task from internal queue if it is present, thus
480     * causing it not to be run if it has not already started. This
481     * method may be useful as one part of a cancellation scheme.
482     *
483     * @param task the task to remove
484     * @return true if the task was removed
485     */
486     public boolean remove(Runnable task) {
487     if (task instanceof DelayedTask && getQueue().remove(task))
488     return true;
489    
490     // The task might actually have been wrapped as a DelayedTask
491     // in execute(), in which case we need to maually traverse
492     // looking for it.
493    
494     DelayedTask wrap = null;
495     Object[] entries = getQueue().toArray();
496     for (int i = 0; i < entries.length; ++i) {
497     DelayedTask t = (DelayedTask)entries[i];
498     Runnable r = t.getRunnable();
499     if (task.equals(r)) {
500     wrap = t;
501     break;
502     }
503     }
504     entries = null;
505     return wrap != null && getQueue().remove(wrap);
506     }
507    
508     /**
509 dl 1.4 * If executed task was periodic, cause the task for the next
510     * period to execute.
511 dl 1.9 * @param r the task (assumed to be a DelayedTask)
512     * @param t the exception
513 dl 1.4 */
514     protected void afterExecute(Runnable r, Throwable t) {
515     if (isShutdown())
516     return;
517     super.afterExecute(r, t);
518     DelayedTask d = (DelayedTask)r;
519     DelayedTask next = d.nextTask();
520 dl 1.6 if (next == null)
521     return;
522     try {
523 dl 1.15 delayedExecute(next);
524 tim 1.14 } catch(RejectedExecutionException ex) {
525 dl 1.6 // lost race to detect shutdown; ignore
526     }
527 dl 1.4 }
528 tim 1.1 }
529 dl 1.4
530