ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.1
Committed: Fri Dec 5 11:27:02 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Log Message:
Separated interface from concrete class

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