ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.13
Committed: Sun Jan 11 23:19:55 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.12: +148 -122 lines
Log Message:
formatting; grammar

File Contents

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