ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledExecutor.java
Revision: 1.10
Committed: Sat Jul 12 00:50:34 2003 UTC (20 years, 11 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRELIMINARY_TEST_RELEASE_2
Changes since 1.9: +6 -6 lines
Log Message:
Added LockSupport; moved nanoTime

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     * @since 1.5
36     * @see Executors
37     *
38     * @spec JSR-166
39 dl 1.9 * @author Doug Lea
40 tim 1.1 */
41     public class ScheduledExecutor extends ThreadPoolExecutor {
42    
43 dl 1.4 /**
44 dl 1.5 * Sequence number to break scheduling ties, and in turn to
45     * guarantee FIFO order among tied entries.
46     */
47     private static final AtomicLong sequencer = new AtomicLong(0);
48    
49     /**
50 dl 1.4 * A delayed or periodic action.
51     */
52 dl 1.8 public static class DelayedTask extends CancellableTask implements Delayed {
53 dl 1.9 /** Sequence number to break ties FIFO */
54 dl 1.4 private final long sequenceNumber;
55 dl 1.9 /** The time the task is enabled to execute in nanoTime units */
56 dl 1.4 private final long time;
57 dl 1.9 /** The delay forllowing next time, or <= 0 if non-periodic */
58 dl 1.4 private final long period;
59 dl 1.9 /** true if at fixed rate; false if fixed delay */
60     private final boolean rateBased;
61    
62 dl 1.4 /**
63 dl 1.5 * Creates a one-shot action with given nanoTime-based trigger time
64 dl 1.4 */
65     DelayedTask(Runnable r, long ns) {
66     super(r);
67     this.time = ns;
68     this.period = 0;
69 dl 1.7 rateBased = false;
70 dl 1.4 this.sequenceNumber = sequencer.getAndIncrement();
71     }
72    
73     /**
74 dl 1.5 * Creates a periodic action with given nano time and period
75 dl 1.4 */
76 dl 1.7 DelayedTask(Runnable r, long ns, long period, boolean rateBased) {
77 dl 1.4 super(r);
78     if (period <= 0)
79     throw new IllegalArgumentException();
80     this.time = ns;
81     this.period = period;
82 dl 1.7 this.rateBased = rateBased;
83 dl 1.4 this.sequenceNumber = sequencer.getAndIncrement();
84     }
85    
86    
87     public long getDelay(TimeUnit unit) {
88 dl 1.10 return unit.convert(time - System.nanoTime(),
89 dl 1.7 TimeUnit.NANOSECONDS);
90 dl 1.4 }
91    
92     public int compareTo(Object other) {
93     DelayedTask x = (DelayedTask)other;
94     long diff = time - x.time;
95     if (diff < 0)
96     return -1;
97     else if (diff > 0)
98     return 1;
99     else if (sequenceNumber < x.sequenceNumber)
100     return -1;
101     else
102     return 1;
103     }
104    
105     /**
106     * Return true if this is a periodic (not a one-shot) action.
107 dl 1.9 * @return true if periodic
108 dl 1.4 */
109     public boolean isPeriodic() {
110     return period > 0;
111     }
112    
113     /**
114     * Returns the period, or zero if non-periodic
115 dl 1.9 * @return the period
116 dl 1.4 */
117     public long getPeriod(TimeUnit unit) {
118     return unit.convert(period, TimeUnit.NANOSECONDS);
119     }
120    
121     /**
122     * Return a new DelayedTask that will trigger in the period
123     * subsequent to current task, or null if non-periodic
124     * or canceled.
125     */
126 dl 1.5 DelayedTask nextTask() {
127 dl 1.4 if (period <= 0 || isCancelled())
128     return null;
129 dl 1.10 long nextTime = period + (rateBased ? time : System.nanoTime());
130 dl 1.7 return new DelayedTask(getRunnable(), nextTime, period, rateBased);
131 dl 1.4 }
132 dl 1.2
133 dl 1.4 }
134 dl 1.2
135 dl 1.4 /**
136     * A delayed result-bearing action.
137     */
138 dl 1.8 public static class DelayedFutureTask<V> extends DelayedTask implements Future<V> {
139 dl 1.4 /**
140     * Creates a Future that may trigger after the given delay.
141     */
142     DelayedFutureTask(Callable<V> callable, long delay, TimeUnit unit) {
143     // must set after super ctor call to use inner class
144 dl 1.10 super(null, System.nanoTime() + unit.toNanos(delay));
145 dl 1.4 setRunnable(new InnerCancellableFuture<V>(callable));
146 dl 1.2 }
147    
148 dl 1.4 /**
149     * Creates a one-shot action that may trigger after the given date.
150     */
151     DelayedFutureTask(Callable<V> callable, Date date) {
152     super(null,
153     TimeUnit.MILLISECONDS.toNanos(date.getTime() -
154     System.currentTimeMillis()));
155     setRunnable(new InnerCancellableFuture<V>(callable));
156     }
157    
158     public V get() throws InterruptedException, ExecutionException {
159     return ((InnerCancellableFuture<V>)getRunnable()).get();
160 dl 1.2 }
161    
162 dl 1.4 public V get(long timeout, TimeUnit unit)
163     throws InterruptedException, ExecutionException, TimeoutException {
164     return ((InnerCancellableFuture<V>)getRunnable()).get(timeout, unit);
165 dl 1.2 }
166 tim 1.1
167 dl 1.4 protected void set(V v) {
168     ((InnerCancellableFuture<V>)getRunnable()).set(v);
169 dl 1.2 }
170 tim 1.1
171 dl 1.4 protected void setException(Throwable t) {
172     ((InnerCancellableFuture<V>)getRunnable()).setException(t);
173     }
174     }
175    
176    
177     /**
178     * An annoying wrapper class to convince generics compiler to
179 dl 1.7 * use a DelayQueue<DelayedTask> as a BlockingQueue<Runnable>
180 dl 1.4 */
181     private static class DelayedWorkQueue extends AbstractQueue<Runnable> implements BlockingQueue<Runnable> {
182     private final DelayQueue<DelayedTask> dq = new DelayQueue<DelayedTask>();
183     public Runnable poll() { return dq.poll(); }
184     public Runnable peek() { return dq.peek(); }
185     public Runnable take() throws InterruptedException { return dq.take(); }
186     public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
187     return dq.poll(timeout, unit);
188 dl 1.2 }
189 dl 1.4 public boolean offer(Runnable x) { return dq.offer((DelayedTask)x); }
190     public void put(Runnable x) throws InterruptedException {
191     dq.put((DelayedTask)x);
192 dl 1.2 }
193 dl 1.4 public boolean offer(Runnable x, long timeout, TimeUnit unit) throws InterruptedException {
194     return dq.offer((DelayedTask)x, timeout, unit);
195 dl 1.2 }
196 dl 1.4 public int remainingCapacity() { return dq.remainingCapacity(); }
197     public boolean remove(Object x) { return dq.remove(x); }
198     public boolean contains(Object x) { return dq.contains(x); }
199     public int size() { return dq.size(); }
200     public boolean isEmpty() { return dq.isEmpty(); }
201     public Iterator<Runnable> iterator() {
202     return new Iterator<Runnable>() {
203     private Iterator<DelayedTask> 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 tim 1.1 }
209 dl 1.4 }
210 tim 1.1
211 dl 1.4 /**
212     * Creates a new ScheduledExecutor with the given initial parameters.
213     *
214     * @param corePoolSize the number of threads to keep in the pool,
215     * even if they are idle.
216     */
217     public ScheduledExecutor(int corePoolSize) {
218     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
219     new DelayedWorkQueue());
220     }
221 tim 1.1
222 dl 1.4 /**
223     * Creates a new ScheduledExecutor 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     */
230     public ScheduledExecutor(int corePoolSize,
231     ThreadFactory threadFactory) {
232     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
233     new DelayedWorkQueue(), threadFactory);
234 tim 1.1 }
235    
236 dl 1.4 /**
237     * Creates a new ScheduledExecutor with the given initial parameters.
238     *
239     * @param corePoolSize the number of threads to keep in the pool,
240     * even if they are idle.
241     * @param handler the handler to use when execution is blocked
242     * because the thread bounds and queue capacities are reached.
243     */
244     public ScheduledExecutor(int corePoolSize,
245     RejectedExecutionHandler handler) {
246     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
247     new DelayedWorkQueue(), handler);
248     }
249 dl 1.2
250 tim 1.1 /**
251 dl 1.2 * Creates a new ScheduledExecutor with the given initial parameters.
252     *
253     * @param corePoolSize the number of threads to keep in the pool,
254     * even if they are idle.
255 dl 1.4 * @param threadFactory the factory to use when the executor
256     * creates a new thread.
257     * @param handler the handler to use when execution is blocked
258     * because the thread bounds and queue capacities are reached.
259 tim 1.1 */
260 dl 1.4 public ScheduledExecutor(int corePoolSize,
261     ThreadFactory threadFactory,
262     RejectedExecutionHandler handler) {
263 dl 1.2 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
264 dl 1.4 new DelayedWorkQueue(), threadFactory, handler);
265     }
266    
267     /**
268 dl 1.7 * Creates and executes a one-shot action that becomes enabled after
269 dl 1.4 * the given delay.
270 dl 1.6 * @param command the task to execute.
271     * @param delay the time from now to delay execution.
272     * @param unit the time unit of the delay parameter.
273     * @return a handle that can be used to cancel the task.
274 dl 1.4 */
275    
276 dl 1.6 public DelayedTask schedule(Runnable command, long delay, TimeUnit unit) {
277 dl 1.10 DelayedTask t = new DelayedTask(command, System.nanoTime() + unit.toNanos(delay));
278 dl 1.4 super.execute(t);
279     return t;
280     }
281    
282     /**
283 dl 1.9 * Creates and executes a one-shot action that becomes enabled
284     * after the given date.
285 dl 1.6 * @param command the task to execute.
286     * @param date the time to commence excution.
287     * @return a handle that can be used to cancel the task.
288     * @throws RejectedExecutionException if task cannot be scheduled
289     * for execution because the executor has been shut down.
290 dl 1.4 */
291 dl 1.6 public DelayedTask schedule(Runnable command, Date date) {
292 dl 1.4 DelayedTask t = new DelayedTask
293 dl 1.6 (command,
294 dl 1.4 TimeUnit.MILLISECONDS.toNanos(date.getTime() -
295     System.currentTimeMillis()));
296     super.execute(t);
297     return t;
298     }
299    
300     /**
301 dl 1.7 * Creates and executes a periodic action that becomes enabled first
302 dl 1.4 * after the given initial delay, and subsequently with the given
303 dl 1.7 * period; that is executions will commence after
304     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
305     * <tt>initialDelay + 2 * period</tt>, and so on.
306 dl 1.6 * @param command the task to execute.
307     * @param initialDelay the time to delay first execution.
308     * @param period the period between successive executions.
309     * @param unit the time unit of the delay and period parameters
310     * @return a handle that can be used to cancel the task.
311     * @throws RejectedExecutionException if task cannot be scheduled
312     * for execution because the executor has been shut down.
313 dl 1.4 */
314 dl 1.7 public DelayedTask scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
315 dl 1.4 DelayedTask t = new DelayedTask
316 dl 1.10 (command, System.nanoTime() + unit.toNanos(initialDelay),
317 dl 1.7 unit.toNanos(period), true);
318 dl 1.4 super.execute(t);
319     return t;
320     }
321    
322     /**
323 dl 1.7 * Creates a periodic action that becomes enabled first after the
324     * given date, and subsequently with the given period
325     * period; that is executions will commence after
326     * <tt>initialDate</tt> then <tt>initialDate+period</tt>, then
327     * <tt>initialDate + 2 * period</tt>, and so on.
328 dl 1.6 * @param command the task to execute.
329     * @param initialDate the time to delay first execution.
330 dl 1.7 * @param period the period between commencement of successive
331     * executions.
332 dl 1.6 * @param unit the time unit of the period parameter.
333     * @return a handle that can be used to cancel the task.
334     * @throws RejectedExecutionException if task cannot be scheduled
335     * for execution because the executor has been shut down.
336 dl 1.4 */
337 dl 1.7 public DelayedTask scheduleAtFixedRate(Runnable command, Date initialDate, long period, TimeUnit unit) {
338     DelayedTask t = new DelayedTask
339     (command,
340     TimeUnit.MILLISECONDS.toNanos(initialDate.getTime() -
341     System.currentTimeMillis()),
342     unit.toNanos(period), true);
343     super.execute(t);
344     return t;
345     }
346    
347     /**
348     * Creates and executes a periodic action that becomes enabled first
349     * after the given initial delay, and and subsequently with the
350     * given delay between the termination of one execution and the
351     * commencement of the next.
352     * @param command the task to execute.
353     * @param initialDelay the time to delay first execution.
354     * @param delay the delay between the termination of one
355     * execution and the commencement of the next.
356     * @param unit the time unit of the delay and delay parameters
357     * @return a handle that can be used to cancel the task.
358     * @throws RejectedExecutionException if task cannot be scheduled
359     * for execution because the executor has been shut down.
360     */
361     public DelayedTask scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
362     DelayedTask t = new DelayedTask
363 dl 1.10 (command, System.nanoTime() + unit.toNanos(initialDelay),
364 dl 1.7 unit.toNanos(delay), false);
365     super.execute(t);
366     return t;
367     }
368    
369     /**
370     * Creates a periodic action that becomes enabled first after the
371     * given date, and subsequently with the given delay between
372     * the termination of one execution and the commencement of the
373     * next.
374     * @param command the task to execute.
375     * @param initialDate the time to delay first execution.
376     * @param delay the delay between the termination of one
377     * execution and the commencement of the next.
378     * @param unit the time unit of the delay parameter.
379     * @return a handle that can be used to cancel the task.
380     * @throws RejectedExecutionException if task cannot be scheduled
381     * for execution because the executor has been shut down.
382     */
383     public DelayedTask scheduleWithFixedDelay(Runnable command, Date initialDate, long delay, TimeUnit unit) {
384 dl 1.4 DelayedTask t = new DelayedTask
385 dl 1.6 (command,
386     TimeUnit.MILLISECONDS.toNanos(initialDate.getTime() -
387 dl 1.4 System.currentTimeMillis()),
388 dl 1.7 unit.toNanos(delay), false);
389 dl 1.4 super.execute(t);
390     return t;
391 tim 1.1 }
392    
393    
394 dl 1.4 /**
395 dl 1.7 * Creates and executes a Future that becomes enabled after the
396     * given delay.
397 dl 1.6 * @param callable the function to execute.
398     * @param delay the time from now to delay execution.
399     * @param unit the time unit of the delay parameter.
400     * @return a Future that can be used to extract result or cancel.
401     * @throws RejectedExecutionException if task cannot be scheduled
402     * for execution because the executor has been shut down.
403 dl 1.4 */
404     public <V> DelayedFutureTask<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
405     DelayedFutureTask<V> t = new DelayedFutureTask<V>
406     (callable, delay, unit);
407     super.execute(t);
408     return t;
409     }
410    
411     /**
412 dl 1.7 * Creates and executes a one-shot action that becomes enabled after
413 dl 1.4 * the given date.
414 dl 1.6 * @param callable the function to execute.
415     * @param date the time to commence excution.
416     * @return a Future that can be used to extract result or cancel.
417     * @throws RejectedExecutionException if task cannot be scheduled
418     * for execution because the executor has been shut down.
419 dl 1.4 */
420     public <V> DelayedFutureTask<V> schedule(Callable<V> callable, Date date) {
421     DelayedFutureTask<V> t = new DelayedFutureTask<V>
422     (callable, date);
423     super.execute(t);
424     return t;
425 tim 1.1 }
426    
427 dl 1.4 /**
428     * Execute command with zero required delay
429 dl 1.6 * @param command the task to execute
430     * @throws RejectedExecutionException at discretion of
431     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
432     * for execution because the executor has been shut down.
433 dl 1.4 */
434     public void execute(Runnable command) {
435     schedule(command, 0, TimeUnit.NANOSECONDS);
436 tim 1.1 }
437    
438 dl 1.4 /**
439     * If executed task was periodic, cause the task for the next
440     * period to execute.
441 dl 1.9 * @param r the task (assumed to be a DelayedTask)
442     * @param t the exception
443 dl 1.4 */
444     protected void afterExecute(Runnable r, Throwable t) {
445     if (isShutdown())
446     return;
447     super.afterExecute(r, t);
448     DelayedTask d = (DelayedTask)r;
449     DelayedTask next = d.nextTask();
450 dl 1.6 if (next == null)
451     return;
452     try {
453 dl 1.4 super.execute(next);
454 dl 1.6 }
455     catch(RejectedExecutionException ex) {
456     // lost race to detect shutdown; ignore
457     }
458 dl 1.4 }
459 tim 1.1 }
460 dl 1.4
461