ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.12
Committed: Wed Jan 7 21:43:57 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.11: +3 -4 lines
Log Message:
Improve shutdown detection

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    
100     public long getDelay(TimeUnit unit) {
101     long d = unit.convert(time - System.nanoTime(),
102     TimeUnit.NANOSECONDS);
103     return d;
104     }
105    
106     public int compareTo(Object other) {
107     if (other == this) // compare zero ONLY if same object
108     return 0;
109     ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
110     long diff = time - x.time;
111     if (diff < 0)
112     return -1;
113     else if (diff > 0)
114     return 1;
115     else if (sequenceNumber < x.sequenceNumber)
116     return -1;
117     else
118     return 1;
119     }
120    
121     /**
122     * Return true if this is a periodic (not a one-shot) action.
123     * @return true if periodic
124     */
125 dl 1.10 boolean isPeriodic() {
126 dl 1.1 return period > 0;
127     }
128    
129     /**
130     * Returns the period, or zero if non-periodic.
131     *
132     * @return the period
133     */
134 dl 1.10 long getPeriod(TimeUnit unit) {
135 dl 1.1 return unit.convert(period, TimeUnit.NANOSECONDS);
136     }
137    
138     /**
139 dl 1.5 * Overrides FutureTask version so as to reset/requeue if periodic.
140 dl 1.1 */
141     public void run() {
142 dl 1.5 if (!isPeriodic())
143     ScheduledFutureTask.super.run();
144     else {
145 dl 1.12 boolean ok = (ScheduledFutureTask.super.runAndReset());
146 dl 1.5 boolean down = isShutdown();
147 dl 1.12 if (ok && (!down ||
148 dl 1.5 (getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
149 dl 1.12 !isTerminating()))) {
150 dl 1.5 time = period + (rateBased ? time : System.nanoTime());
151     ScheduledThreadPoolExecutor.super.getQueue().add(this);
152     }
153     // This might have been the final executed delayed
154     // task. Wake up threads to check.
155     else if (down)
156     interruptIdleWorkers();
157     }
158 dl 1.1 }
159     }
160    
161     /**
162     * An annoying wrapper class to convince generics compiler to
163     * use a DelayQueue<ScheduledFutureTask> as a BlockingQueue<Runnable>
164     */
165     private static class DelayedWorkQueue
166     extends AbstractCollection<Runnable> implements BlockingQueue<Runnable> {
167    
168     private final DelayQueue<ScheduledFutureTask> dq = new DelayQueue<ScheduledFutureTask>();
169     public Runnable poll() { return dq.poll(); }
170     public Runnable peek() { return dq.peek(); }
171     public Runnable take() throws InterruptedException { return dq.take(); }
172     public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
173     return dq.poll(timeout, unit);
174     }
175    
176     public boolean add(Runnable x) { return dq.add((ScheduledFutureTask)x); }
177     public boolean offer(Runnable x) { return dq.offer((ScheduledFutureTask)x); }
178     public void put(Runnable x) {
179     dq.put((ScheduledFutureTask)x);
180     }
181     public boolean offer(Runnable x, long timeout, TimeUnit unit) {
182     return dq.offer((ScheduledFutureTask)x, timeout, unit);
183     }
184    
185     public Runnable remove() { return dq.remove(); }
186     public Runnable element() { return dq.element(); }
187     public void clear() { dq.clear(); }
188     public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
189     public int drainTo(Collection<? super Runnable> c, int maxElements) {
190     return dq.drainTo(c, maxElements);
191     }
192    
193     public int remainingCapacity() { return dq.remainingCapacity(); }
194     public boolean remove(Object x) { return dq.remove(x); }
195     public boolean contains(Object x) { return dq.contains(x); }
196     public int size() { return dq.size(); }
197     public boolean isEmpty() { return dq.isEmpty(); }
198     public Object[] toArray() { return dq.toArray(); }
199     public <T> T[] toArray(T[] array) { return dq.toArray(array); }
200     public Iterator<Runnable> iterator() {
201     return new Iterator<Runnable>() {
202     private Iterator<ScheduledFutureTask> it = dq.iterator();
203     public boolean hasNext() { return it.hasNext(); }
204     public Runnable next() { return it.next(); }
205     public void remove() { it.remove(); }
206     };
207     }
208     }
209    
210     /**
211     * Creates a new ScheduledThreadPoolExecutor with the given core pool size.
212     *
213     * @param corePoolSize the number of threads to keep in the pool,
214     * even if they are idle.
215     * @throws IllegalArgumentException if corePoolSize less than or
216     * equal to zero
217     */
218     public ScheduledThreadPoolExecutor(int corePoolSize) {
219     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
220     new DelayedWorkQueue());
221     }
222    
223     /**
224     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
225     *
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     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
240     *
241     * @param corePoolSize the number of threads to keep in the pool,
242     * even if they are idle.
243     * @param handler the handler to use when execution is blocked
244     * because the thread bounds and queue capacities are reached.
245     * @throws NullPointerException if handler is null
246     */
247     public ScheduledThreadPoolExecutor(int corePoolSize,
248     RejectedExecutionHandler handler) {
249     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
250     new DelayedWorkQueue(), handler);
251     }
252    
253     /**
254     * Creates a new ScheduledThreadPoolExecutor with the given initial parameters.
255     *
256     * @param corePoolSize the number of threads to keep in the pool,
257     * even if they are idle.
258     * @param threadFactory the factory to use when the executor
259     * creates a new thread.
260     * @param handler the handler to use when execution is blocked
261     * because the thread bounds and queue capacities are reached.
262     * @throws NullPointerException if threadFactory or handler is null
263     */
264     public ScheduledThreadPoolExecutor(int corePoolSize,
265     ThreadFactory threadFactory,
266     RejectedExecutionHandler handler) {
267     super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
268     new DelayedWorkQueue(), threadFactory, handler);
269     }
270    
271     /**
272     * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
273     */
274     private void delayedExecute(Runnable command) {
275     if (isShutdown()) {
276     reject(command);
277     return;
278     }
279     // Prestart a thread if necessary. We cannot prestart it
280     // running the task because the task (probably) shouldn't be
281     // run yet, so thread will just idle until delay elapses.
282     if (getPoolSize() < getCorePoolSize())
283     prestartCoreThread();
284    
285     super.getQueue().add(command);
286     }
287    
288 dl 1.6 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
289 dl 1.9 if (command == null || unit == null)
290 dl 1.1 throw new NullPointerException();
291     long triggerTime = System.nanoTime() + unit.toNanos(delay);
292 dl 1.6 ScheduledFutureTask<?> t = new ScheduledFutureTask<Boolean>(command, null, triggerTime);
293 dl 1.1 delayedExecute(t);
294     return t;
295     }
296    
297     public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
298 dl 1.9 if (callable == null || unit == null)
299 dl 1.1 throw new NullPointerException();
300     long triggerTime = System.nanoTime() + unit.toNanos(delay);
301     ScheduledFutureTask<V> t = new ScheduledFutureTask<V>(callable, triggerTime);
302     delayedExecute(t);
303     return t;
304     }
305    
306 dl 1.6 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
307 dl 1.9 if (command == null || unit == null)
308 dl 1.1 throw new NullPointerException();
309     if (period <= 0)
310     throw new IllegalArgumentException();
311     long triggerTime = System.nanoTime() + unit.toNanos(initialDelay);
312 dl 1.6 ScheduledFutureTask<?> t = new ScheduledFutureTask<Object>
313     (command, null,
314 dl 1.1 triggerTime,
315     unit.toNanos(period),
316     true);
317     delayedExecute(t);
318     return t;
319     }
320    
321 dl 1.6 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
322 dl 1.9 if (command == null || unit == null)
323 dl 1.1 throw new NullPointerException();
324     if (delay <= 0)
325     throw new IllegalArgumentException();
326     long triggerTime = System.nanoTime() + unit.toNanos(initialDelay);
327 dl 1.6 ScheduledFutureTask<?> t = new ScheduledFutureTask<Boolean>
328 dl 1.1 (command,
329 dl 1.6 null,
330 dl 1.1 triggerTime,
331     unit.toNanos(delay),
332     false);
333     delayedExecute(t);
334     return t;
335     }
336    
337    
338     /**
339     * Execute command with zero required delay. This has effect
340     * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
341     * that inspections of the queue and of the list returned by
342     * <tt>shutdownNow</tt> will access the zero-delayed
343     * {@link ScheduledFuture}, not the <tt>command</tt> itself.
344     *
345     * @param command the task to execute
346     * @throws RejectedExecutionException at discretion of
347     * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
348     * for execution because the executor has been shut down.
349     * @throws NullPointerException if command is null
350     */
351     public void execute(Runnable command) {
352     if (command == null)
353     throw new NullPointerException();
354     schedule(command, 0, TimeUnit.NANOSECONDS);
355     }
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     return schedule(Executors.callable(task, result), 0, TimeUnit.NANOSECONDS);
363     }
364    
365     public <T> Future<T> submit(Callable<T> task) {
366     return schedule(task, 0, TimeUnit.NANOSECONDS);
367     }
368 dl 1.1
369     /**
370     * Set policy on whether to continue executing existing periodic
371     * tasks even when this executor has been <tt>shutdown</tt>. In
372     * this case, these tasks will only terminate upon
373     * <tt>shutdownNow</tt>, or after setting the policy to
374     * <tt>false</tt> when already shutdown. This value is by default
375     * false.
376     * @param value if true, continue after shutdown, else don't.
377     */
378     public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
379     continueExistingPeriodicTasksAfterShutdown = value;
380     if (!value && isShutdown())
381     cancelUnwantedTasks();
382     }
383    
384     /**
385     * Get the policy on whether to continue executing existing
386     * periodic tasks even when this executor has been
387     * <tt>shutdown</tt>. In this case, these tasks will only
388     * terminate upon <tt>shutdownNow</tt> or after setting the policy
389     * to <tt>false</tt> when already shutdown. This value is by
390     * default false.
391     * @return true if will continue after shutdown.
392     */
393     public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
394     return continueExistingPeriodicTasksAfterShutdown;
395     }
396    
397     /**
398     * Set policy on whether to execute existing delayed
399     * tasks even when this executor has been <tt>shutdown</tt>. In
400     * this case, these tasks will only terminate upon
401     * <tt>shutdownNow</tt>, or after setting the policy to
402     * <tt>false</tt> when already shutdown. This value is by default
403     * true.
404     * @param value if true, execute after shutdown, else don't.
405     */
406     public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
407     executeExistingDelayedTasksAfterShutdown = value;
408     if (!value && isShutdown())
409     cancelUnwantedTasks();
410     }
411    
412     /**
413     * Get policy on whether to execute existing delayed
414     * tasks even when this executor has been <tt>shutdown</tt>. In
415     * this case, these tasks will only terminate upon
416     * <tt>shutdownNow</tt>, or after setting the policy to
417     * <tt>false</tt> when already shutdown. This value is by default
418     * true.
419     * @return true if will execute after shutdown.
420     */
421     public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
422     return executeExistingDelayedTasksAfterShutdown;
423     }
424    
425     /**
426     * Cancel and clear the queue of all tasks that should not be run
427     * due to shutdown policy.
428     */
429     private void cancelUnwantedTasks() {
430     boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
431     boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
432     if (!keepDelayed && !keepPeriodic)
433     super.getQueue().clear();
434     else if (keepDelayed || keepPeriodic) {
435     Object[] entries = super.getQueue().toArray();
436     for (int i = 0; i < entries.length; ++i) {
437 dl 1.7 Object e = entries[i];
438     if (e instanceof ScheduledFutureTask) {
439     ScheduledFutureTask<?> t = (ScheduledFutureTask<?>)e;
440     if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
441     t.cancel(false);
442     }
443 dl 1.1 }
444     entries = null;
445     purge();
446     }
447     }
448    
449     /**
450     * Initiates an orderly shutdown in which previously submitted
451     * tasks are executed, but no new tasks will be accepted. If the
452     * <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
453     * been set <tt>false</tt>, existing delayed tasks whose delays
454     * have not yet elapsed are cancelled. And unless the
455     * <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
456     * been set <tt>true</tt>, future executions of existing periodic
457     * tasks will be cancelled.
458     */
459     public void shutdown() {
460     cancelUnwantedTasks();
461     super.shutdown();
462     }
463    
464     /**
465     * Attempts to stop all actively executing tasks, halts the
466     * processing of waiting tasks, and returns a list of the tasks that were
467     * awaiting execution.
468     *
469     * <p>There are no guarantees beyond best-effort attempts to stop
470     * processing actively executing tasks. This implementations
471     * cancels via {@link Thread#interrupt}, so if any tasks mask or
472     * fail to respond to interrupts, they may never terminate.
473     *
474     * @return list of tasks that never commenced execution. Each
475     * element of this list is a {@link ScheduledFuture},
476     * including those tasks submitted using <tt>execute</tt> which
477     * are for scheduling purposes used as the basis of a zero-delay
478     * <tt>ScheduledFuture</tt>.
479     */
480 tim 1.4 public List<Runnable> shutdownNow() {
481 dl 1.1 return super.shutdownNow();
482     }
483    
484    
485     /**
486     * Returns the task queue used by this executor. Each element of
487     * this queue is a {@link ScheduledFuture}, including those
488     * tasks submitted using <tt>execute</tt> which are for scheduling
489     * purposes used as the basis of a zero-delay
490     * <tt>ScheduledFuture</tt>. Iteration over this queue is
491     * </em>not</em> guaranteed to traverse tasks in the order in
492     * which they will execute.
493     *
494     * @return the task queue
495     */
496     public BlockingQueue<Runnable> getQueue() {
497     return super.getQueue();
498     }
499    
500     }