ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.26
Committed: Mon May 23 00:52:56 2005 UTC (19 years ago) by jsr166
Branch: MAIN
Changes since 1.25: +4 -2 lines
Log Message:
constructor doc fixes

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, as explained at
4 * http://creativecommons.org/licenses/publicdomain
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 additionally schedule
13 * commands to run after a given delay, or to execute
14 * periodically. This class is preferable to {@link java.util.Timer}
15 * when multiple worker threads are needed, or when the additional
16 * flexibility or capabilities of {@link ThreadPoolExecutor} (which
17 * this class extends) are required.
18 *
19 * <p> Delayed tasks execute no sooner than they are enabled, but
20 * without any real-time guarantees about when, after they are
21 * enabled, they will commence. Tasks scheduled for exactly the same
22 * execution time are enabled in first-in-first-out (FIFO) order of
23 * submission.
24 *
25 * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
26 * of the inherited tuning methods are not useful for it. In
27 * particular, because it acts as a fixed-sized pool using
28 * <tt>corePoolSize</tt> threads and an unbounded queue, adjustments
29 * to <tt>maximumPoolSize</tt> have no useful effect.
30 *
31 * <p>This class supports protected extension method
32 * <tt>decorateTask</tt> (one version each for <tt>Runnable</tt> and
33 * <tt>Callable</tt>) that can be used to customize the concrete task
34 * types used to execute commands. By default,
35 * a <tt>ScheduledThreadPoolExecutor</tt> uses
36 * a task type extending {@link FutureTask}. However, this may
37 * be modified or replaced using subclasses of the form:
38 * <pre>
39 * public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {
40 *
41 * static class CustomTask&lt;V&gt; implements RunnableScheduledFuture&lt;V&gt; { ... }
42 *
43 * protected &lt;V&gt; RunnableScheduledFuture&lt;V&gt; decorateTask(
44 * Runnable r, RunnableScheduledFuture&lt;V&gt; task) {
45 * return new CustomTask&lt;V&gt;(r, task);
46 * }
47 *
48 * protected &lt;V&gt; RunnableScheduledFuture&lt;V&gt; decorateTask(
49 * Callable&lt;V;gt; c, RunnableScheduledFuture&lt;V&gt; task) {
50 * return new CustomTask&lt;V&gt;(c, task);
51 * }
52 * // ... add constructors, etc.
53 * }
54 * </pre>
55 * @since 1.5
56 * @author Doug Lea
57 */
58 public class ScheduledThreadPoolExecutor
59 extends ThreadPoolExecutor
60 implements ScheduledExecutorService {
61
62 /**
63 * False if should cancel/suppress periodic tasks on shutdown.
64 */
65 private volatile boolean continueExistingPeriodicTasksAfterShutdown;
66
67 /**
68 * False if should cancel non-periodic tasks on shutdown.
69 */
70 private volatile boolean executeExistingDelayedTasksAfterShutdown = true;
71
72 /**
73 * Sequence number to break scheduling ties, and in turn to
74 * guarantee FIFO order among tied entries.
75 */
76 private static final AtomicLong sequencer = new AtomicLong(0);
77
78 /** Base of nanosecond timings, to avoid wrapping */
79 private static final long NANO_ORIGIN = System.nanoTime();
80
81 /**
82 * Returns nanosecond time offset by origin
83 */
84 final long now() {
85 return System.nanoTime() - NANO_ORIGIN;
86 }
87
88 private class ScheduledFutureTask<V>
89 extends FutureTask<V> implements RunnableScheduledFuture<V> {
90
91 /** Sequence number to break ties FIFO */
92 private final long sequenceNumber;
93 /** The time the task is enabled to execute in nanoTime units */
94 private long time;
95 /**
96 * Period in nanoseconds for repeating tasks. A positive
97 * value indicates fixed-rate execution. A negative value
98 * indicates fixed-delay execution. A value of 0 indicates a
99 * non-repeating task.
100 */
101 private final long period;
102
103 /**
104 * Creates a one-shot action with given nanoTime-based trigger time
105 */
106 ScheduledFutureTask(Runnable r, V result, long ns) {
107 super(r, result);
108 this.time = ns;
109 this.period = 0;
110 this.sequenceNumber = sequencer.getAndIncrement();
111 }
112
113 /**
114 * Creates a periodic action with given nano time and period
115 */
116 ScheduledFutureTask(Runnable r, V result, long ns, long period) {
117 super(r, result);
118 this.time = ns;
119 this.period = period;
120 this.sequenceNumber = sequencer.getAndIncrement();
121 }
122
123 /**
124 * Creates a one-shot action with given nanoTime-based trigger
125 */
126 ScheduledFutureTask(Callable<V> callable, long ns) {
127 super(callable);
128 this.time = ns;
129 this.period = 0;
130 this.sequenceNumber = sequencer.getAndIncrement();
131 }
132
133 public long getDelay(TimeUnit unit) {
134 long d = unit.convert(time - now(), TimeUnit.NANOSECONDS);
135 return d;
136 }
137
138 public int compareTo(Delayed other) {
139 if (other == this) // compare zero ONLY if same object
140 return 0;
141 ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
142 long diff = time - x.time;
143 if (diff < 0)
144 return -1;
145 else if (diff > 0)
146 return 1;
147 else if (sequenceNumber < x.sequenceNumber)
148 return -1;
149 else
150 return 1;
151 }
152
153 /**
154 * Returns true if this is a periodic (not a one-shot) action.
155 * @return true if periodic
156 */
157 public boolean isPeriodic() {
158 return period != 0;
159 }
160
161 /**
162 * Run a periodic task
163 */
164 private void runPeriodic() {
165 boolean ok = ScheduledFutureTask.super.runAndReset();
166 boolean down = isShutdown();
167 // Reschedule if not cancelled and not shutdown or policy allows
168 if (ok && (!down ||
169 (getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
170 !isTerminating()))) {
171 long p = period;
172 if (p > 0)
173 time += p;
174 else
175 time = now() - p;
176 ScheduledThreadPoolExecutor.super.getQueue().add(this);
177 }
178 // This might have been the final executed delayed
179 // task. Wake up threads to check.
180 else if (down)
181 interruptIdleWorkers();
182 }
183
184 /**
185 * Overrides FutureTask version so as to reset/requeue if periodic.
186 */
187 public void run() {
188 if (isPeriodic())
189 runPeriodic();
190 else
191 ScheduledFutureTask.super.run();
192 }
193 }
194
195 /**
196 * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
197 */
198 private void delayedExecute(Runnable command) {
199 if (isShutdown()) {
200 reject(command);
201 return;
202 }
203 // Prestart a thread if necessary. We cannot prestart it
204 // running the task because the task (probably) shouldn't be
205 // run yet, so thread will just idle until delay elapses.
206 if (getPoolSize() < getCorePoolSize())
207 prestartCoreThread();
208
209 super.getQueue().add(command);
210 }
211
212 /**
213 * Cancels and clears the queue of all tasks that should not be run
214 * due to shutdown policy.
215 */
216 private void cancelUnwantedTasks() {
217 boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
218 boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
219 if (!keepDelayed && !keepPeriodic)
220 super.getQueue().clear();
221 else if (keepDelayed || keepPeriodic) {
222 Object[] entries = super.getQueue().toArray();
223 for (int i = 0; i < entries.length; ++i) {
224 Object e = entries[i];
225 if (e instanceof RunnableScheduledFuture) {
226 RunnableScheduledFuture<?> t = (RunnableScheduledFuture<?>)e;
227 if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
228 t.cancel(false);
229 }
230 }
231 entries = null;
232 purge();
233 }
234 }
235
236 public boolean remove(Runnable task) {
237 if (!(task instanceof RunnableScheduledFuture))
238 return false;
239 return getQueue().remove(task);
240 }
241
242 /**
243 * Modify or replace the task used to execute a runnable.
244 * This method can be used to override the concrete
245 * class used for managing internal tasks.
246 * The default implementation simply returns the given
247 * task.
248 *
249 * @param runnable the submitted Runnable
250 * @param task the task created to execute the runnable
251 * @return a task that can execute the runnable
252 * @since 1.6
253 */
254 protected <V> RunnableScheduledFuture<V> decorateTask(
255 Runnable runnable, RunnableScheduledFuture<V> task) {
256 return task;
257 }
258
259 /**
260 * Modify or replace the task used to execute a callable.
261 * This method can be used to override the concrete
262 * class used for managing internal tasks.
263 * The default implementation simply returns the given
264 * task.
265 *
266 * @param callable the submitted Callable
267 * @param task the task created to execute the callable
268 * @return a task that can execute the callable
269 * @since 1.6
270 */
271 protected <V> RunnableScheduledFuture<V> decorateTask(
272 Callable<V> callable, RunnableScheduledFuture<V> task) {
273 return task;
274 }
275
276 /**
277 * Creates a new ScheduledThreadPoolExecutor with the given core
278 * pool size.
279 *
280 * @param corePoolSize the number of threads to keep in the pool,
281 * even if they are idle.
282 * @throws IllegalArgumentException if <tt>corePoolSize &lt;= 0</tt>
283 */
284 public ScheduledThreadPoolExecutor(int corePoolSize) {
285 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
286 new DelayedWorkQueue());
287 }
288
289 /**
290 * Creates a new ScheduledThreadPoolExecutor with the given
291 * initial parameters.
292 *
293 * @param corePoolSize the number of threads to keep in the pool,
294 * even if they are idle.
295 * @param threadFactory the factory to use when the executor
296 * creates a new thread.
297 * @throws IllegalArgumentException if <tt>corePoolSize &lt;= 0</tt>
298 * @throws NullPointerException if threadFactory is null
299 */
300 public ScheduledThreadPoolExecutor(int corePoolSize,
301 ThreadFactory threadFactory) {
302 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
303 new DelayedWorkQueue(), threadFactory);
304 }
305
306 /**
307 * Creates a new ScheduledThreadPoolExecutor with the given
308 * initial parameters.
309 *
310 * @param corePoolSize the number of threads to keep in the pool,
311 * even if they are idle.
312 * @param handler the handler to use when execution is blocked
313 * because the thread bounds and queue capacities are reached.
314 * @throws IllegalArgumentException if <tt>corePoolSize &lt;= 0</tt>
315 * @throws NullPointerException if handler is null
316 */
317 public ScheduledThreadPoolExecutor(int corePoolSize,
318 RejectedExecutionHandler handler) {
319 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
320 new DelayedWorkQueue(), handler);
321 }
322
323 /**
324 * Creates a new ScheduledThreadPoolExecutor with the given
325 * initial parameters.
326 *
327 * @param corePoolSize the number of threads to keep in the pool,
328 * even if they are idle.
329 * @param threadFactory the factory to use when the executor
330 * creates a new thread.
331 * @param handler the handler to use when execution is blocked
332 * because the thread bounds and queue capacities are reached.
333 * @throws IllegalArgumentException if <tt>corePoolSize &lt;= 0</tt>
334 * @throws NullPointerException if threadFactory or handler is null
335 */
336 public ScheduledThreadPoolExecutor(int corePoolSize,
337 ThreadFactory threadFactory,
338 RejectedExecutionHandler handler) {
339 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
340 new DelayedWorkQueue(), threadFactory, handler);
341 }
342
343 public ScheduledFuture<?> schedule(Runnable command,
344 long delay,
345 TimeUnit unit) {
346 if (command == null || unit == null)
347 throw new NullPointerException();
348 long triggerTime = now() + unit.toNanos(delay);
349 RunnableScheduledFuture<?> t = decorateTask(command,
350 new ScheduledFutureTask<Boolean>(command, null, triggerTime));
351 delayedExecute(t);
352 return t;
353 }
354
355 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
356 long delay,
357 TimeUnit unit) {
358 if (callable == null || unit == null)
359 throw new NullPointerException();
360 if (delay < 0) delay = 0;
361 long triggerTime = now() + unit.toNanos(delay);
362 RunnableScheduledFuture<V> t = decorateTask(callable,
363 new ScheduledFutureTask<V>(callable, triggerTime));
364 delayedExecute(t);
365 return t;
366 }
367
368 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
369 long initialDelay,
370 long period,
371 TimeUnit unit) {
372 if (command == null || unit == null)
373 throw new NullPointerException();
374 if (period <= 0)
375 throw new IllegalArgumentException();
376 if (initialDelay < 0) initialDelay = 0;
377 long triggerTime = now() + unit.toNanos(initialDelay);
378 RunnableScheduledFuture<?> t = decorateTask(command,
379 new ScheduledFutureTask<Object>(command,
380 null,
381 triggerTime,
382 unit.toNanos(period)));
383 delayedExecute(t);
384 return t;
385 }
386
387 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
388 long initialDelay,
389 long delay,
390 TimeUnit unit) {
391 if (command == null || unit == null)
392 throw new NullPointerException();
393 if (delay <= 0)
394 throw new IllegalArgumentException();
395 if (initialDelay < 0) initialDelay = 0;
396 long triggerTime = now() + unit.toNanos(initialDelay);
397 RunnableScheduledFuture<?> t = decorateTask(command,
398 new ScheduledFutureTask<Boolean>(command,
399 null,
400 triggerTime,
401 unit.toNanos(-delay)));
402 delayedExecute(t);
403 return t;
404 }
405
406
407 /**
408 * Executes command with zero required delay. This has effect
409 * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
410 * that inspections of the queue and of the list returned by
411 * <tt>shutdownNow</tt> will access the zero-delayed
412 * {@link ScheduledFuture}, not the <tt>command</tt> itself.
413 *
414 * @param command the task to execute
415 * @throws RejectedExecutionException at discretion of
416 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
417 * for execution because the executor has been shut down.
418 * @throws NullPointerException if command is null
419 */
420 public void execute(Runnable command) {
421 if (command == null)
422 throw new NullPointerException();
423 schedule(command, 0, TimeUnit.NANOSECONDS);
424 }
425
426 // Override AbstractExecutorService methods
427
428 public Future<?> submit(Runnable task) {
429 return schedule(task, 0, TimeUnit.NANOSECONDS);
430 }
431
432 public <T> Future<T> submit(Runnable task, T result) {
433 return schedule(Executors.callable(task, result),
434 0, TimeUnit.NANOSECONDS);
435 }
436
437 public <T> Future<T> submit(Callable<T> task) {
438 return schedule(task, 0, TimeUnit.NANOSECONDS);
439 }
440
441 /**
442 * Sets the policy on whether to continue executing existing periodic
443 * tasks even when this executor has been <tt>shutdown</tt>. In
444 * this case, these tasks will only terminate upon
445 * <tt>shutdownNow</tt>, or after setting the policy to
446 * <tt>false</tt> when already shutdown. This value is by default
447 * false.
448 * @param value if true, continue after shutdown, else don't.
449 * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy
450 */
451 public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
452 continueExistingPeriodicTasksAfterShutdown = value;
453 if (!value && isShutdown())
454 cancelUnwantedTasks();
455 }
456
457 /**
458 * Gets the policy on whether to continue executing existing
459 * periodic tasks even when this executor has been
460 * <tt>shutdown</tt>. In this case, these tasks will only
461 * terminate upon <tt>shutdownNow</tt> or after setting the policy
462 * to <tt>false</tt> when already shutdown. This value is by
463 * default false.
464 * @return true if will continue after shutdown.
465 * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy
466 */
467 public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
468 return continueExistingPeriodicTasksAfterShutdown;
469 }
470
471 /**
472 * Sets the policy on whether to execute existing delayed
473 * tasks even when this executor has been <tt>shutdown</tt>. In
474 * this case, these tasks will only terminate upon
475 * <tt>shutdownNow</tt>, or after setting the policy to
476 * <tt>false</tt> when already shutdown. This value is by default
477 * true.
478 * @param value if true, execute after shutdown, else don't.
479 * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
480 */
481 public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
482 executeExistingDelayedTasksAfterShutdown = value;
483 if (!value && isShutdown())
484 cancelUnwantedTasks();
485 }
486
487 /**
488 * Gets the policy on whether to execute existing delayed
489 * tasks even when this executor has been <tt>shutdown</tt>. In
490 * this case, these tasks will only terminate upon
491 * <tt>shutdownNow</tt>, or after setting the policy to
492 * <tt>false</tt> when already shutdown. This value is by default
493 * true.
494 * @return true if will execute after shutdown.
495 * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy
496 */
497 public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
498 return executeExistingDelayedTasksAfterShutdown;
499 }
500
501
502 /**
503 * Initiates an orderly shutdown in which previously submitted
504 * tasks are executed, but no new tasks will be accepted. If the
505 * <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
506 * been set <tt>false</tt>, existing delayed tasks whose delays
507 * have not yet elapsed are cancelled. And unless the
508 * <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
509 * been set <tt>true</tt>, future executions of existing periodic
510 * tasks will be cancelled.
511 */
512 public void shutdown() {
513 cancelUnwantedTasks();
514 super.shutdown();
515 }
516
517 /**
518 * Attempts to stop all actively executing tasks, halts the
519 * processing of waiting tasks, and returns a list of the tasks that were
520 * awaiting execution.
521 *
522 * <p>There are no guarantees beyond best-effort attempts to stop
523 * processing actively executing tasks. This implementation
524 * cancels tasks via {@link Thread#interrupt}, so if any tasks mask or
525 * fail to respond to interrupts, they may never terminate.
526 *
527 * @return list of tasks that never commenced execution. Each
528 * element of this list is a {@link ScheduledFuture},
529 * including those tasks submitted using <tt>execute</tt>, which
530 * are for scheduling purposes used as the basis of a zero-delay
531 * <tt>ScheduledFuture</tt>.
532 */
533 public List<Runnable> shutdownNow() {
534 return super.shutdownNow();
535 }
536
537 /**
538 * Returns the task queue used by this executor. Each element of
539 * this queue is a {@link ScheduledFuture}, including those
540 * tasks submitted using <tt>execute</tt> which are for scheduling
541 * purposes used as the basis of a zero-delay
542 * <tt>ScheduledFuture</tt>. Iteration over this queue is
543 * <em>not</em> guaranteed to traverse tasks in the order in
544 * which they will execute.
545 *
546 * @return the task queue
547 */
548 public BlockingQueue<Runnable> getQueue() {
549 return super.getQueue();
550 }
551
552 /**
553 * An annoying wrapper class to convince generics compiler to
554 * use a DelayQueue<RunnableScheduledFuture> as a BlockingQueue<Runnable>
555 */
556 private static class DelayedWorkQueue
557 extends AbstractCollection<Runnable>
558 implements BlockingQueue<Runnable> {
559
560 private final DelayQueue<RunnableScheduledFuture> dq = new DelayQueue<RunnableScheduledFuture>();
561 public Runnable poll() { return dq.poll(); }
562 public Runnable peek() { return dq.peek(); }
563 public Runnable take() throws InterruptedException { return dq.take(); }
564 public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
565 return dq.poll(timeout, unit);
566 }
567
568 public boolean add(Runnable x) { return dq.add((RunnableScheduledFuture)x); }
569 public boolean offer(Runnable x) { return dq.offer((RunnableScheduledFuture)x); }
570 public void put(Runnable x) {
571 dq.put((RunnableScheduledFuture)x);
572 }
573 public boolean offer(Runnable x, long timeout, TimeUnit unit) {
574 return dq.offer((RunnableScheduledFuture)x, timeout, unit);
575 }
576
577 public Runnable remove() { return dq.remove(); }
578 public Runnable element() { return dq.element(); }
579 public void clear() { dq.clear(); }
580 public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
581 public int drainTo(Collection<? super Runnable> c, int maxElements) {
582 return dq.drainTo(c, maxElements);
583 }
584
585 public int remainingCapacity() { return dq.remainingCapacity(); }
586 public boolean remove(Object x) { return dq.remove(x); }
587 public boolean contains(Object x) { return dq.contains(x); }
588 public int size() { return dq.size(); }
589 public boolean isEmpty() { return dq.isEmpty(); }
590 public Object[] toArray() { return dq.toArray(); }
591 public <T> T[] toArray(T[] array) { return dq.toArray(array); }
592 public Iterator<Runnable> iterator() {
593 return new Iterator<Runnable>() {
594 private Iterator<RunnableScheduledFuture> it = dq.iterator();
595 public boolean hasNext() { return it.hasNext(); }
596 public Runnable next() { return it.next(); }
597 public void remove() { it.remove(); }
598 };
599 }
600 }
601 }