ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.22
Committed: Tue May 17 04:17:05 2005 UTC (19 years ago) by peierls
Branch: MAIN
Changes since 1.21: +24 -13 lines
Log Message:
Overridable RunnableFuture creation for AbstractExecutorService.
OverridableRunnableScheduledFuture decoration for ScheduledThreadPoolExecutor.

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