ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.16
Committed: Wed Jan 21 01:47:00 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.15: +22 -13 lines
Log Message:
Use j.u.Timer internal conventions

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