ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledExecutor.java
Revision: 1.9
Committed: Tue Jun 24 14:34:48 2003 UTC (20 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.8: +13 -3 lines
Log Message:
Added missing javadoc tags; minor reformatting

File Contents

# Content
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 * 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 * <tt>java.util.Timer</tt> when multiple worker threads are needed,
15 * or when the additional flexibility or capabilities of
16 * <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 *
35 * @since 1.5
36 * @see Executors
37 *
38 * @spec JSR-166
39 * @author Doug Lea
40 */
41 public class ScheduledExecutor extends ThreadPoolExecutor {
42
43 /**
44 * 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 * A delayed or periodic action.
51 */
52 public static class DelayedTask extends CancellableTask implements Delayed {
53 /** Sequence number to break ties FIFO */
54 private final long sequenceNumber;
55 /** The time the task is enabled to execute in nanoTime units */
56 private final long time;
57 /** The delay forllowing next time, or <= 0 if non-periodic */
58 private final long period;
59 /** true if at fixed rate; false if fixed delay */
60 private final boolean rateBased;
61
62 /**
63 * Creates a one-shot action with given nanoTime-based trigger time
64 */
65 DelayedTask(Runnable r, long ns) {
66 super(r);
67 this.time = ns;
68 this.period = 0;
69 rateBased = false;
70 this.sequenceNumber = sequencer.getAndIncrement();
71 }
72
73 /**
74 * Creates a periodic action with given nano time and period
75 */
76 DelayedTask(Runnable r, long ns, long period, boolean rateBased) {
77 super(r);
78 if (period <= 0)
79 throw new IllegalArgumentException();
80 this.time = ns;
81 this.period = period;
82 this.rateBased = rateBased;
83 this.sequenceNumber = sequencer.getAndIncrement();
84 }
85
86
87 public long getDelay(TimeUnit unit) {
88 return unit.convert(time - TimeUnit.nanoTime(),
89 TimeUnit.NANOSECONDS);
90 }
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 * @return true if periodic
108 */
109 public boolean isPeriodic() {
110 return period > 0;
111 }
112
113 /**
114 * Returns the period, or zero if non-periodic
115 * @return the period
116 */
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 DelayedTask nextTask() {
127 if (period <= 0 || isCancelled())
128 return null;
129 long nextTime = period + (rateBased ? time : TimeUnit.nanoTime());
130 return new DelayedTask(getRunnable(), nextTime, period, rateBased);
131 }
132
133 }
134
135 /**
136 * A delayed result-bearing action.
137 */
138 public static class DelayedFutureTask<V> extends DelayedTask implements Future<V> {
139 /**
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 super(null, TimeUnit.nanoTime() + unit.toNanos(delay));
145 setRunnable(new InnerCancellableFuture<V>(callable));
146 }
147
148 /**
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 }
161
162 public V get(long timeout, TimeUnit unit)
163 throws InterruptedException, ExecutionException, TimeoutException {
164 return ((InnerCancellableFuture<V>)getRunnable()).get(timeout, unit);
165 }
166
167 protected void set(V v) {
168 ((InnerCancellableFuture<V>)getRunnable()).set(v);
169 }
170
171 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 * use a DelayQueue<DelayedTask> as a BlockingQueue<Runnable>
180 */
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 }
189 public boolean offer(Runnable x) { return dq.offer((DelayedTask)x); }
190 public void put(Runnable x) throws InterruptedException {
191 dq.put((DelayedTask)x);
192 }
193 public boolean offer(Runnable x, long timeout, TimeUnit unit) throws InterruptedException {
194 return dq.offer((DelayedTask)x, timeout, unit);
195 }
196 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 }
209 }
210
211 /**
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
222 /**
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 }
235
236 /**
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
250 /**
251 * 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 * @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 */
260 public ScheduledExecutor(int corePoolSize,
261 ThreadFactory threadFactory,
262 RejectedExecutionHandler handler) {
263 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
264 new DelayedWorkQueue(), threadFactory, handler);
265 }
266
267 /**
268 * Creates and executes a one-shot action that becomes enabled after
269 * the given delay.
270 * @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 */
275
276 public DelayedTask schedule(Runnable command, long delay, TimeUnit unit) {
277 DelayedTask t = new DelayedTask(command, TimeUnit.nanoTime() + unit.toNanos(delay));
278 super.execute(t);
279 return t;
280 }
281
282 /**
283 * Creates and executes a one-shot action that becomes enabled
284 * after the given date.
285 * @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 */
291 public DelayedTask schedule(Runnable command, Date date) {
292 DelayedTask t = new DelayedTask
293 (command,
294 TimeUnit.MILLISECONDS.toNanos(date.getTime() -
295 System.currentTimeMillis()));
296 super.execute(t);
297 return t;
298 }
299
300 /**
301 * Creates and executes a periodic action that becomes enabled first
302 * after the given initial delay, and subsequently with the given
303 * 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 * @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 */
314 public DelayedTask scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
315 DelayedTask t = new DelayedTask
316 (command, TimeUnit.nanoTime() + unit.toNanos(initialDelay),
317 unit.toNanos(period), true);
318 super.execute(t);
319 return t;
320 }
321
322 /**
323 * 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 * @param command the task to execute.
329 * @param initialDate the time to delay first execution.
330 * @param period the period between commencement of successive
331 * executions.
332 * @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 */
337 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 (command, TimeUnit.nanoTime() + unit.toNanos(initialDelay),
364 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 DelayedTask t = new DelayedTask
385 (command,
386 TimeUnit.MILLISECONDS.toNanos(initialDate.getTime() -
387 System.currentTimeMillis()),
388 unit.toNanos(delay), false);
389 super.execute(t);
390 return t;
391 }
392
393
394 /**
395 * Creates and executes a Future that becomes enabled after the
396 * given delay.
397 * @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 */
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 * Creates and executes a one-shot action that becomes enabled after
413 * the given date.
414 * @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 */
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 }
426
427 /**
428 * Execute command with zero required delay
429 * @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 */
434 public void execute(Runnable command) {
435 schedule(command, 0, TimeUnit.NANOSECONDS);
436 }
437
438 /**
439 * If executed task was periodic, cause the task for the next
440 * period to execute.
441 * @param r the task (assumed to be a DelayedTask)
442 * @param t the exception
443 */
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 if (next == null)
451 return;
452 try {
453 super.execute(next);
454 }
455 catch(RejectedExecutionException ex) {
456 // lost race to detect shutdown; ignore
457 }
458 }
459 }
460
461