ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.14
Committed: Fri Jan 16 18:15:59 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.13: +18 -9 lines
Log Message:
Avoid overflow

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 /** The delay following next time, or <= 0 if non-periodic */
72 private final long period;
73 /** true if at fixed rate; false if fixed delay */
74 private final boolean rateBased;
75
76 /**
77 * Creates a one-shot action with given nanoTime-based trigger time
78 */
79 ScheduledFutureTask(Runnable r, V result, long ns) {
80 super(r, result);
81 this.time = ns;
82 this.period = 0;
83 rateBased = false;
84 this.sequenceNumber = sequencer.getAndIncrement();
85 }
86
87 /**
88 * Creates a periodic action with given nano time and period
89 */
90 ScheduledFutureTask(Runnable r, V result, long ns, long period, boolean rateBased) {
91 super(r, result);
92 this.time = ns;
93 this.period = period;
94 this.rateBased = rateBased;
95 this.sequenceNumber = sequencer.getAndIncrement();
96 }
97
98 /**
99 * Creates a one-shot action with given nanoTime-based trigger
100 */
101 ScheduledFutureTask(Callable<V> callable, long ns) {
102 super(callable);
103 this.time = ns;
104 this.period = 0;
105 rateBased = false;
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 time = period + (rateBased ? time : now());
157 ScheduledThreadPoolExecutor.super.getQueue().add(this);
158 }
159 // This might have been the final executed delayed
160 // task. Wake up threads to check.
161 else if (down)
162 interruptIdleWorkers();
163 }
164
165 /**
166 * Overrides FutureTask version so as to reset/requeue if periodic.
167 */
168 public void run() {
169 if (isPeriodic())
170 runPeriodic();
171 else
172 ScheduledFutureTask.super.run();
173 }
174 }
175
176 /**
177 * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
178 */
179 private void delayedExecute(Runnable command) {
180 if (isShutdown()) {
181 reject(command);
182 return;
183 }
184 // Prestart a thread if necessary. We cannot prestart it
185 // running the task because the task (probably) shouldn't be
186 // run yet, so thread will just idle until delay elapses.
187 if (getPoolSize() < getCorePoolSize())
188 prestartCoreThread();
189
190 super.getQueue().add(command);
191 }
192
193 /**
194 * Cancel and clear the queue of all tasks that should not be run
195 * due to shutdown policy.
196 */
197 private void cancelUnwantedTasks() {
198 boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
199 boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
200 if (!keepDelayed && !keepPeriodic)
201 super.getQueue().clear();
202 else if (keepDelayed || keepPeriodic) {
203 Object[] entries = super.getQueue().toArray();
204 for (int i = 0; i < entries.length; ++i) {
205 Object e = entries[i];
206 if (e instanceof ScheduledFutureTask) {
207 ScheduledFutureTask<?> t = (ScheduledFutureTask<?>)e;
208 if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
209 t.cancel(false);
210 }
211 }
212 entries = null;
213 purge();
214 }
215 }
216
217 /**
218 * Creates a new ScheduledThreadPoolExecutor with the given core
219 * pool size.
220 *
221 * @param corePoolSize the number of threads to keep in the pool,
222 * even if they are idle.
223 * @throws IllegalArgumentException if corePoolSize less than or
224 * equal to zero
225 */
226 public ScheduledThreadPoolExecutor(int corePoolSize) {
227 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
228 new DelayedWorkQueue());
229 }
230
231 /**
232 * Creates a new ScheduledThreadPoolExecutor with the given
233 * initial parameters.
234 *
235 * @param corePoolSize the number of threads to keep in the pool,
236 * even if they are idle.
237 * @param threadFactory the factory to use when the executor
238 * creates a new thread.
239 * @throws NullPointerException if threadFactory is null
240 */
241 public ScheduledThreadPoolExecutor(int corePoolSize,
242 ThreadFactory threadFactory) {
243 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
244 new DelayedWorkQueue(), threadFactory);
245 }
246
247 /**
248 * Creates a new ScheduledThreadPoolExecutor with the given
249 * initial parameters.
250 *
251 * @param corePoolSize the number of threads to keep in the pool,
252 * even if they are idle.
253 * @param handler the handler to use when execution is blocked
254 * because the thread bounds and queue capacities are reached.
255 * @throws NullPointerException if handler is null
256 */
257 public ScheduledThreadPoolExecutor(int corePoolSize,
258 RejectedExecutionHandler handler) {
259 super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
260 new DelayedWorkQueue(), handler);
261 }
262
263 /**
264 * Creates a new ScheduledThreadPoolExecutor with the given
265 * 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 public ScheduledFuture<?> schedule(Runnable command,
283 long delay,
284 TimeUnit unit) {
285 if (command == null || unit == null)
286 throw new NullPointerException();
287 long triggerTime = now() + unit.toNanos(delay);
288 ScheduledFutureTask<?> t =
289 new ScheduledFutureTask<Boolean>(command, null, triggerTime);
290 delayedExecute(t);
291 return t;
292 }
293
294 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
295 long delay,
296 TimeUnit unit) {
297 if (callable == null || unit == null)
298 throw new NullPointerException();
299 long triggerTime = now() + unit.toNanos(delay);
300 ScheduledFutureTask<V> t =
301 new ScheduledFutureTask<V>(callable, triggerTime);
302 delayedExecute(t);
303 return t;
304 }
305
306 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
307 long initialDelay,
308 long period,
309 TimeUnit unit) {
310 if (command == null || unit == null)
311 throw new NullPointerException();
312 if (period <= 0)
313 throw new IllegalArgumentException();
314 long triggerTime = now() + unit.toNanos(initialDelay);
315 ScheduledFutureTask<?> t =
316 new ScheduledFutureTask<Object>(command,
317 null,
318 triggerTime,
319 unit.toNanos(period),
320 true);
321 delayedExecute(t);
322 return t;
323 }
324
325 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
326 long initialDelay,
327 long delay,
328 TimeUnit unit) {
329 if (command == null || unit == null)
330 throw new NullPointerException();
331 if (delay <= 0)
332 throw new IllegalArgumentException();
333 long triggerTime = now() + unit.toNanos(initialDelay);
334 ScheduledFutureTask<?> t =
335 new ScheduledFutureTask<Boolean>(command,
336 null,
337 triggerTime,
338 unit.toNanos(delay),
339 false);
340 delayedExecute(t);
341 return t;
342 }
343
344
345 /**
346 * Execute command with zero required delay. This has effect
347 * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
348 * that inspections of the queue and of the list returned by
349 * <tt>shutdownNow</tt> will access the zero-delayed
350 * {@link ScheduledFuture}, not the <tt>command</tt> itself.
351 *
352 * @param command the task to execute
353 * @throws RejectedExecutionException at discretion of
354 * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
355 * for execution because the executor has been shut down.
356 * @throws NullPointerException if command is null
357 */
358 public void execute(Runnable command) {
359 if (command == null)
360 throw new NullPointerException();
361 schedule(command, 0, TimeUnit.NANOSECONDS);
362 }
363
364 // Override AbstractExecutorService methods
365
366 public Future<?> submit(Runnable task) {
367 return schedule(task, 0, TimeUnit.NANOSECONDS);
368 }
369
370 public <T> Future<T> submit(Runnable task, T result) {
371 return schedule(Executors.callable(task, result),
372 0, TimeUnit.NANOSECONDS);
373 }
374
375 public <T> Future<T> submit(Callable<T> task) {
376 return schedule(task, 0, TimeUnit.NANOSECONDS);
377 }
378
379 /**
380 * Set policy on whether to continue executing existing periodic
381 * tasks even when this executor has been <tt>shutdown</tt>. In
382 * this case, these tasks will only terminate upon
383 * <tt>shutdownNow</tt>, or after setting the policy to
384 * <tt>false</tt> when already shutdown. This value is by default
385 * false.
386 * @param value if true, continue after shutdown, else don't.
387 */
388 public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
389 continueExistingPeriodicTasksAfterShutdown = value;
390 if (!value && isShutdown())
391 cancelUnwantedTasks();
392 }
393
394 /**
395 * Get the policy on whether to continue executing existing
396 * periodic tasks even when this executor has been
397 * <tt>shutdown</tt>. In this case, these tasks will only
398 * terminate upon <tt>shutdownNow</tt> or after setting the policy
399 * to <tt>false</tt> when already shutdown. This value is by
400 * default false.
401 * @return true if will continue after shutdown.
402 */
403 public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
404 return continueExistingPeriodicTasksAfterShutdown;
405 }
406
407 /**
408 * Set policy on whether to execute existing delayed
409 * tasks even when this executor has been <tt>shutdown</tt>. In
410 * this case, these tasks will only terminate upon
411 * <tt>shutdownNow</tt>, or after setting the policy to
412 * <tt>false</tt> when already shutdown. This value is by default
413 * true.
414 * @param value if true, execute after shutdown, else don't.
415 */
416 public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
417 executeExistingDelayedTasksAfterShutdown = value;
418 if (!value && isShutdown())
419 cancelUnwantedTasks();
420 }
421
422 /**
423 * Get policy on whether to execute existing delayed
424 * tasks even when this executor has been <tt>shutdown</tt>. In
425 * this case, these tasks will only terminate upon
426 * <tt>shutdownNow</tt>, or after setting the policy to
427 * <tt>false</tt> when already shutdown. This value is by default
428 * true.
429 * @return true if will execute after shutdown.
430 */
431 public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
432 return executeExistingDelayedTasksAfterShutdown;
433 }
434
435
436 /**
437 * Initiates an orderly shutdown in which previously submitted
438 * tasks are executed, but no new tasks will be accepted. If the
439 * <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
440 * been set <tt>false</tt>, existing delayed tasks whose delays
441 * have not yet elapsed are cancelled. And unless the
442 * <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
443 * been set <tt>true</tt>, future executions of existing periodic
444 * tasks will be cancelled.
445 */
446 public void shutdown() {
447 cancelUnwantedTasks();
448 super.shutdown();
449 }
450
451 /**
452 * Attempts to stop all actively executing tasks, halts the
453 * processing of waiting tasks, and returns a list of the tasks that were
454 * awaiting execution.
455 *
456 * <p>There are no guarantees beyond best-effort attempts to stop
457 * processing actively executing tasks. This implementations
458 * cancels via {@link Thread#interrupt}, so if any tasks mask or
459 * fail to respond to interrupts, they may never terminate.
460 *
461 * @return list of tasks that never commenced execution. Each
462 * element of this list is a {@link ScheduledFuture},
463 * including those tasks submitted using <tt>execute</tt> which
464 * are for scheduling purposes used as the basis of a zero-delay
465 * <tt>ScheduledFuture</tt>.
466 */
467 public List<Runnable> shutdownNow() {
468 return super.shutdownNow();
469 }
470
471 /**
472 * Returns the task queue used by this executor. Each element of
473 * this queue is a {@link ScheduledFuture}, including those
474 * tasks submitted using <tt>execute</tt> which are for scheduling
475 * purposes used as the basis of a zero-delay
476 * <tt>ScheduledFuture</tt>. Iteration over this queue is
477 * </em>not</em> guaranteed to traverse tasks in the order in
478 * which they will execute.
479 *
480 * @return the task queue
481 */
482 public BlockingQueue<Runnable> getQueue() {
483 return super.getQueue();
484 }
485
486 /**
487 * An annoying wrapper class to convince generics compiler to
488 * use a DelayQueue<ScheduledFutureTask> as a BlockingQueue<Runnable>
489 */
490 private static class DelayedWorkQueue
491 extends AbstractCollection<Runnable>
492 implements BlockingQueue<Runnable> {
493
494 private final DelayQueue<ScheduledFutureTask> dq = new DelayQueue<ScheduledFutureTask>();
495 public Runnable poll() { return dq.poll(); }
496 public Runnable peek() { return dq.peek(); }
497 public Runnable take() throws InterruptedException { return dq.take(); }
498 public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
499 return dq.poll(timeout, unit);
500 }
501
502 public boolean add(Runnable x) { return dq.add((ScheduledFutureTask)x); }
503 public boolean offer(Runnable x) { return dq.offer((ScheduledFutureTask)x); }
504 public void put(Runnable x) {
505 dq.put((ScheduledFutureTask)x);
506 }
507 public boolean offer(Runnable x, long timeout, TimeUnit unit) {
508 return dq.offer((ScheduledFutureTask)x, timeout, unit);
509 }
510
511 public Runnable remove() { return dq.remove(); }
512 public Runnable element() { return dq.element(); }
513 public void clear() { dq.clear(); }
514 public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
515 public int drainTo(Collection<? super Runnable> c, int maxElements) {
516 return dq.drainTo(c, maxElements);
517 }
518
519 public int remainingCapacity() { return dq.remainingCapacity(); }
520 public boolean remove(Object x) { return dq.remove(x); }
521 public boolean contains(Object x) { return dq.contains(x); }
522 public int size() { return dq.size(); }
523 public boolean isEmpty() { return dq.isEmpty(); }
524 public Object[] toArray() { return dq.toArray(); }
525 public <T> T[] toArray(T[] array) { return dq.toArray(array); }
526 public Iterator<Runnable> iterator() {
527 return new Iterator<Runnable>() {
528 private Iterator<ScheduledFutureTask> it = dq.iterator();
529 public boolean hasNext() { return it.hasNext(); }
530 public Runnable next() { return it.next(); }
531 public void remove() { it.remove(); }
532 };
533 }
534 }
535 }