ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ScheduledThreadPoolExecutor.java
Revision: 1.100
Committed: Fri Nov 20 20:49:49 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.99: +3 -0 lines
Log Message:
document benign racy read in ScheduledFutureTask.cancel

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 jsr166 1.58 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.1 */
6    
7     package java.util.concurrent;
8 jsr166 1.82
9 jsr166 1.83 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 jsr166 1.62 import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 jsr166 1.83
12 jsr166 1.82 import java.util.AbstractQueue;
13     import java.util.Arrays;
14     import java.util.Collection;
15     import java.util.Iterator;
16     import java.util.List;
17     import java.util.NoSuchElementException;
18 jsr166 1.83 import java.util.concurrent.atomic.AtomicLong;
19     import java.util.concurrent.locks.Condition;
20     import java.util.concurrent.locks.ReentrantLock;
21 dl 1.1
22     /**
23 dl 1.7 * A {@link ThreadPoolExecutor} that can additionally schedule
24 jsr166 1.75 * commands to run after a given delay, or to execute periodically.
25     * This class is preferable to {@link java.util.Timer} when multiple
26     * worker threads are needed, or when the additional flexibility or
27     * capabilities of {@link ThreadPoolExecutor} (which this class
28     * extends) are required.
29 dl 1.1 *
30 jsr166 1.46 * <p>Delayed tasks execute no sooner than they are enabled, but
31 dl 1.18 * without any real-time guarantees about when, after they are
32     * enabled, they will commence. Tasks scheduled for exactly the same
33     * execution time are enabled in first-in-first-out (FIFO) order of
34 jsr166 1.46 * submission.
35     *
36     * <p>When a submitted task is cancelled before it is run, execution
37 jsr166 1.75 * is suppressed. By default, such a cancelled task is not
38     * automatically removed from the work queue until its delay elapses.
39     * While this enables further inspection and monitoring, it may also
40     * cause unbounded retention of cancelled tasks. To avoid this, use
41     * {@link #setRemoveOnCancelPolicy} to cause tasks to be immediately
42     * removed from the work queue at time of cancellation.
43 dl 1.1 *
44 jsr166 1.75 * <p>Successive executions of a periodic task scheduled via
45 jsr166 1.84 * {@link #scheduleAtFixedRate scheduleAtFixedRate} or
46     * {@link #scheduleWithFixedDelay scheduleWithFixedDelay}
47     * do not overlap. While different executions may be performed by
48     * different threads, the effects of prior executions
49     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
50 dl 1.51 * those of subsequent ones.
51     *
52 dl 1.1 * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
53 dl 1.8 * of the inherited tuning methods are not useful for it. In
54 jsr166 1.53 * particular, because it acts as a fixed-sized pool using
55     * {@code corePoolSize} threads and an unbounded queue, adjustments
56     * to {@code maximumPoolSize} have no useful effect. Additionally, it
57     * is almost never a good idea to set {@code corePoolSize} to zero or
58     * use {@code allowCoreThreadTimeOut} because this may leave the pool
59     * without threads to handle tasks once they become eligible to run.
60 dl 1.1 *
61 jsr166 1.39 * <p><b>Extension notes:</b> This class overrides the
62 jsr166 1.69 * {@link ThreadPoolExecutor#execute(Runnable) execute} and
63 jsr166 1.39 * {@link AbstractExecutorService#submit(Runnable) submit}
64     * methods to generate internal {@link ScheduledFuture} objects to
65     * control per-task delays and scheduling. To preserve
66     * functionality, any further overrides of these methods in
67 dl 1.32 * subclasses must invoke superclass versions, which effectively
68 jsr166 1.39 * disables additional task customization. However, this class
69 dl 1.32 * provides alternative protected extension method
70 jsr166 1.39 * {@code decorateTask} (one version each for {@code Runnable} and
71     * {@code Callable}) that can be used to customize the concrete task
72     * types used to execute commands entered via {@code execute},
73     * {@code submit}, {@code schedule}, {@code scheduleAtFixedRate},
74     * and {@code scheduleWithFixedDelay}. By default, a
75     * {@code ScheduledThreadPoolExecutor} uses a task type extending
76 dl 1.32 * {@link FutureTask}. However, this may be modified or replaced using
77     * subclasses of the form:
78     *
79 jsr166 1.85 * <pre> {@code
80 dl 1.23 * public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {
81     *
82 jsr166 1.39 * static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }
83 dl 1.23 *
84 jsr166 1.39 * protected <V> RunnableScheduledFuture<V> decorateTask(
85     * Runnable r, RunnableScheduledFuture<V> task) {
86     * return new CustomTask<V>(r, task);
87 jsr166 1.29 * }
88 dl 1.23 *
89 jsr166 1.39 * protected <V> RunnableScheduledFuture<V> decorateTask(
90     * Callable<V> c, RunnableScheduledFuture<V> task) {
91     * return new CustomTask<V>(c, task);
92 jsr166 1.29 * }
93     * // ... add constructors, etc.
94 jsr166 1.39 * }}</pre>
95     *
96 dl 1.1 * @since 1.5
97     * @author Doug Lea
98     */
99 jsr166 1.21 public class ScheduledThreadPoolExecutor
100     extends ThreadPoolExecutor
101 tim 1.3 implements ScheduledExecutorService {
102 dl 1.1
103 dl 1.37 /*
104     * This class specializes ThreadPoolExecutor implementation by
105     *
106 jsr166 1.99 * 1. Using a custom task type ScheduledFutureTask, even for tasks
107     * that don't require scheduling because they are submitted
108     * using ExecutorService rather than ScheduledExecutorService
109     * methods, which are treated as tasks with a delay of zero.
110 dl 1.37 *
111 jsr166 1.46 * 2. Using a custom queue (DelayedWorkQueue), a variant of
112 dl 1.37 * unbounded DelayQueue. The lack of capacity constraint and
113     * the fact that corePoolSize and maximumPoolSize are
114     * effectively identical simplifies some execution mechanics
115 jsr166 1.46 * (see delayedExecute) compared to ThreadPoolExecutor.
116 dl 1.37 *
117     * 3. Supporting optional run-after-shutdown parameters, which
118     * leads to overrides of shutdown methods to remove and cancel
119     * tasks that should NOT be run after shutdown, as well as
120     * different recheck logic when task (re)submission overlaps
121     * with a shutdown.
122     *
123     * 4. Task decoration methods to allow interception and
124     * instrumentation, which are needed because subclasses cannot
125     * otherwise override submit methods to get this effect. These
126     * don't have any impact on pool control logic though.
127     */
128    
129 dl 1.1 /**
130     * False if should cancel/suppress periodic tasks on shutdown.
131     */
132     private volatile boolean continueExistingPeriodicTasksAfterShutdown;
133    
134     /**
135     * False if should cancel non-periodic tasks on shutdown.
136     */
137     private volatile boolean executeExistingDelayedTasksAfterShutdown = true;
138    
139     /**
140 jsr166 1.75 * True if ScheduledFutureTask.cancel should remove from queue.
141 dl 1.41 */
142 jsr166 1.90 volatile boolean removeOnCancel;
143 dl 1.41
144     /**
145 dl 1.1 * Sequence number to break scheduling ties, and in turn to
146     * guarantee FIFO order among tied entries.
147     */
148 jsr166 1.60 private static final AtomicLong sequencer = new AtomicLong();
149 dl 1.14
150 jsr166 1.21 private class ScheduledFutureTask<V>
151 peierls 1.22 extends FutureTask<V> implements RunnableScheduledFuture<V> {
152 jsr166 1.21
153 dl 1.1 /** Sequence number to break ties FIFO */
154     private final long sequenceNumber;
155 jsr166 1.44
156 jsr166 1.99 /** The nanoTime-based time when the task is enabled to execute. */
157 dl 1.88 private volatile long time;
158 jsr166 1.44
159 dl 1.16 /**
160 jsr166 1.99 * Period for repeating tasks, in nanoseconds.
161 jsr166 1.75 * A positive value indicates fixed-rate execution.
162     * A negative value indicates fixed-delay execution.
163     * A value of 0 indicates a non-repeating (one-shot) task.
164 dl 1.16 */
165 dl 1.1 private final long period;
166    
167 jsr166 1.48 /** The actual task to be re-enqueued by reExecutePeriodic */
168     RunnableScheduledFuture<V> outerTask = this;
169 jsr166 1.44
170 dl 1.1 /**
171 dl 1.40 * Index into delay queue, to support faster cancellation.
172     */
173     int heapIndex;
174    
175     /**
176 jsr166 1.30 * Creates a one-shot action with given nanoTime-based trigger time.
177 dl 1.1 */
178 jsr166 1.89 ScheduledFutureTask(Runnable r, V result, long triggerTime,
179     long sequenceNumber) {
180 dl 1.1 super(r, result);
181 jsr166 1.75 this.time = triggerTime;
182 dl 1.1 this.period = 0;
183 jsr166 1.89 this.sequenceNumber = sequenceNumber;
184 dl 1.1 }
185    
186     /**
187 jsr166 1.75 * Creates a periodic action with given nanoTime-based initial
188     * trigger time and period.
189 dl 1.1 */
190 jsr166 1.75 ScheduledFutureTask(Runnable r, V result, long triggerTime,
191 jsr166 1.89 long period, long sequenceNumber) {
192 dl 1.1 super(r, result);
193 jsr166 1.75 this.time = triggerTime;
194 dl 1.1 this.period = period;
195 jsr166 1.89 this.sequenceNumber = sequenceNumber;
196 dl 1.1 }
197    
198     /**
199 jsr166 1.65 * Creates a one-shot action with given nanoTime-based trigger time.
200 dl 1.1 */
201 jsr166 1.89 ScheduledFutureTask(Callable<V> callable, long triggerTime,
202     long sequenceNumber) {
203 dl 1.1 super(callable);
204 jsr166 1.75 this.time = triggerTime;
205 dl 1.1 this.period = 0;
206 jsr166 1.89 this.sequenceNumber = sequenceNumber;
207 dl 1.1 }
208    
209     public long getDelay(TimeUnit unit) {
210 jsr166 1.98 return unit.convert(time - System.nanoTime(), NANOSECONDS);
211 dl 1.1 }
212    
213 dl 1.20 public int compareTo(Delayed other) {
214 dl 1.59 if (other == this) // compare zero if same object
215 dl 1.1 return 0;
216 dl 1.34 if (other instanceof ScheduledFutureTask) {
217     ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
218     long diff = time - x.time;
219     if (diff < 0)
220     return -1;
221     else if (diff > 0)
222     return 1;
223     else if (sequenceNumber < x.sequenceNumber)
224     return -1;
225     else
226     return 1;
227     }
228 jsr166 1.64 long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS);
229 jsr166 1.61 return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
230 dl 1.1 }
231    
232     /**
233 jsr166 1.70 * Returns {@code true} if this is a periodic (not a one-shot) action.
234 jsr166 1.30 *
235 jsr166 1.70 * @return {@code true} if periodic
236 dl 1.1 */
237 dl 1.23 public boolean isPeriodic() {
238 dl 1.16 return period != 0;
239 dl 1.1 }
240    
241     /**
242 jsr166 1.39 * Sets the next time to run for a periodic task.
243 dl 1.13 */
244 dl 1.37 private void setNextRunTime() {
245     long p = period;
246     if (p > 0)
247     time += p;
248     else
249 jsr166 1.54 time = triggerTime(-p);
250 dl 1.13 }
251    
252 dl 1.40 public boolean cancel(boolean mayInterruptIfRunning) {
253 jsr166 1.100 // The racy read of heapIndex below is benign:
254     // if heapIndex < 0, then OOTA guarantees that we have surely
255     // been removed; else we recheck under lock in remove()
256 dl 1.41 boolean cancelled = super.cancel(mayInterruptIfRunning);
257     if (cancelled && removeOnCancel && heapIndex >= 0)
258 jsr166 1.42 remove(this);
259 dl 1.41 return cancelled;
260 dl 1.40 }
261    
262 dl 1.13 /**
263 dl 1.5 * Overrides FutureTask version so as to reset/requeue if periodic.
264 jsr166 1.21 */
265 dl 1.1 public void run() {
266 dl 1.37 boolean periodic = isPeriodic();
267     if (!canRunInCurrentRunState(periodic))
268     cancel(false);
269     else if (!periodic)
270 jsr166 1.91 super.run();
271     else if (super.runAndReset()) {
272 dl 1.37 setNextRunTime();
273 jsr166 1.44 reExecutePeriodic(outerTask);
274 dl 1.37 }
275 dl 1.1 }
276     }
277    
278     /**
279 dl 1.37 * Returns true if can run a task given current run state
280 jsr166 1.39 * and run-after-shutdown parameters.
281     *
282 dl 1.37 * @param periodic true if this task periodic, false if delayed
283     */
284     boolean canRunInCurrentRunState(boolean periodic) {
285 jsr166 1.38 return isRunningOrShutdown(periodic ?
286 dl 1.37 continueExistingPeriodicTasksAfterShutdown :
287     executeExistingDelayedTasksAfterShutdown);
288     }
289    
290     /**
291     * Main execution method for delayed or periodic tasks. If pool
292     * is shut down, rejects the task. Otherwise adds task to queue
293     * and starts a thread, if necessary, to run it. (We cannot
294     * prestart the thread to run the task because the task (probably)
295 jsr166 1.67 * shouldn't be run yet.) If the pool is shut down while the task
296 dl 1.37 * is being added, cancel and remove it if required by state and
297 jsr166 1.39 * run-after-shutdown parameters.
298     *
299 dl 1.37 * @param task the task
300     */
301     private void delayedExecute(RunnableScheduledFuture<?> task) {
302     if (isShutdown())
303     reject(task);
304     else {
305     super.getQueue().add(task);
306     if (isShutdown() &&
307     !canRunInCurrentRunState(task.isPeriodic()) &&
308     remove(task))
309     task.cancel(false);
310 jsr166 1.48 else
311 dl 1.63 ensurePrestart();
312 dl 1.37 }
313     }
314 jsr166 1.21
315 dl 1.37 /**
316 jsr166 1.39 * Requeues a periodic task unless current run state precludes it.
317     * Same idea as delayedExecute except drops task rather than rejecting.
318     *
319 dl 1.37 * @param task the task
320     */
321     void reExecutePeriodic(RunnableScheduledFuture<?> task) {
322     if (canRunInCurrentRunState(true)) {
323     super.getQueue().add(task);
324     if (!canRunInCurrentRunState(true) && remove(task))
325     task.cancel(false);
326 jsr166 1.48 else
327 dl 1.63 ensurePrestart();
328 dl 1.37 }
329 dl 1.13 }
330 dl 1.1
331 dl 1.13 /**
332 jsr166 1.21 * Cancels and clears the queue of all tasks that should not be run
333 jsr166 1.39 * due to shutdown policy. Invoked within super.shutdown.
334 dl 1.13 */
335 dl 1.37 @Override void onShutdown() {
336     BlockingQueue<Runnable> q = super.getQueue();
337     boolean keepDelayed =
338     getExecuteExistingDelayedTasksAfterShutdownPolicy();
339     boolean keepPeriodic =
340     getContinueExistingPeriodicTasksAfterShutdownPolicy();
341 jsr166 1.57 if (!keepDelayed && !keepPeriodic) {
342     for (Object e : q.toArray())
343     if (e instanceof RunnableScheduledFuture<?>)
344     ((RunnableScheduledFuture<?>) e).cancel(false);
345 dl 1.37 q.clear();
346 jsr166 1.57 }
347 dl 1.37 else {
348     // Traverse snapshot to avoid iterator exceptions
349 jsr166 1.39 for (Object e : q.toArray()) {
350 dl 1.23 if (e instanceof RunnableScheduledFuture) {
351 dl 1.37 RunnableScheduledFuture<?> t =
352     (RunnableScheduledFuture<?>)e;
353 dl 1.41 if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) ||
354     t.isCancelled()) { // also remove if already cancelled
355     if (q.remove(t))
356     t.cancel(false);
357     }
358 dl 1.13 }
359     }
360 dl 1.1 }
361 jsr166 1.48 tryTerminate();
362 dl 1.1 }
363    
364 dl 1.23 /**
365 jsr166 1.30 * Modifies or replaces the task used to execute a runnable.
366 jsr166 1.28 * This method can be used to override the concrete
367 dl 1.23 * class used for managing internal tasks.
368 jsr166 1.30 * The default implementation simply returns the given task.
369 jsr166 1.28 *
370 dl 1.23 * @param runnable the submitted Runnable
371     * @param task the task created to execute the runnable
372 jsr166 1.72 * @param <V> the type of the task's result
373 dl 1.23 * @return a task that can execute the runnable
374     * @since 1.6
375     */
376 peierls 1.22 protected <V> RunnableScheduledFuture<V> decorateTask(
377 dl 1.23 Runnable runnable, RunnableScheduledFuture<V> task) {
378     return task;
379 peierls 1.22 }
380    
381 dl 1.23 /**
382 jsr166 1.30 * Modifies or replaces the task used to execute a callable.
383 jsr166 1.28 * This method can be used to override the concrete
384 dl 1.23 * class used for managing internal tasks.
385 jsr166 1.30 * The default implementation simply returns the given task.
386 jsr166 1.28 *
387 dl 1.23 * @param callable the submitted Callable
388     * @param task the task created to execute the callable
389 jsr166 1.72 * @param <V> the type of the task's result
390 dl 1.23 * @return a task that can execute the callable
391     * @since 1.6
392     */
393 peierls 1.22 protected <V> RunnableScheduledFuture<V> decorateTask(
394 dl 1.23 Callable<V> callable, RunnableScheduledFuture<V> task) {
395     return task;
396 dl 1.19 }
397    
398 dl 1.1 /**
399 jsr166 1.78 * The default keep-alive time for pool threads.
400     *
401     * Normally, this value is unused because all pool threads will be
402     * core threads, but if a user creates a pool with a corePoolSize
403     * of zero (against our advice), we keep a thread alive as long as
404     * there are queued tasks. If the keep alive time is zero (the
405     * historic value), we end up hot-spinning in getTask, wasting a
406     * CPU. But on the other hand, if we set the value too high, and
407     * users create a one-shot pool which they don't cleanly shutdown,
408     * the pool's non-daemon threads will prevent JVM termination. A
409     * small but non-zero value (relative to a JVM's lifetime) seems
410     * best.
411     */
412     private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
413    
414     /**
415 jsr166 1.39 * Creates a new {@code ScheduledThreadPoolExecutor} with the
416     * given core pool size.
417 jsr166 1.21 *
418 jsr166 1.39 * @param corePoolSize the number of threads to keep in the pool, even
419     * if they are idle, unless {@code allowCoreThreadTimeOut} is set
420     * @throws IllegalArgumentException if {@code corePoolSize < 0}
421 dl 1.1 */
422     public ScheduledThreadPoolExecutor(int corePoolSize) {
423 jsr166 1.78 super(corePoolSize, Integer.MAX_VALUE,
424     DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
425 dl 1.1 new DelayedWorkQueue());
426     }
427    
428     /**
429 jsr166 1.39 * Creates a new {@code ScheduledThreadPoolExecutor} with the
430     * given initial parameters.
431 jsr166 1.21 *
432 jsr166 1.39 * @param corePoolSize the number of threads to keep in the pool, even
433     * if they are idle, unless {@code allowCoreThreadTimeOut} is set
434 dl 1.1 * @param threadFactory the factory to use when the executor
435 jsr166 1.39 * creates a new thread
436     * @throws IllegalArgumentException if {@code corePoolSize < 0}
437     * @throws NullPointerException if {@code threadFactory} is null
438 dl 1.1 */
439     public ScheduledThreadPoolExecutor(int corePoolSize,
440 jsr166 1.56 ThreadFactory threadFactory) {
441 jsr166 1.78 super(corePoolSize, Integer.MAX_VALUE,
442     DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
443 dl 1.1 new DelayedWorkQueue(), threadFactory);
444     }
445    
446     /**
447 jsr166 1.79 * Creates a new {@code ScheduledThreadPoolExecutor} with the
448     * given initial parameters.
449 jsr166 1.21 *
450 jsr166 1.39 * @param corePoolSize the number of threads to keep in the pool, even
451     * if they are idle, unless {@code allowCoreThreadTimeOut} is set
452 dl 1.1 * @param handler the handler to use when execution is blocked
453 jsr166 1.39 * because the thread bounds and queue capacities are reached
454     * @throws IllegalArgumentException if {@code corePoolSize < 0}
455     * @throws NullPointerException if {@code handler} is null
456 dl 1.1 */
457     public ScheduledThreadPoolExecutor(int corePoolSize,
458 jsr166 1.56 RejectedExecutionHandler handler) {
459 jsr166 1.78 super(corePoolSize, Integer.MAX_VALUE,
460     DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
461 dl 1.1 new DelayedWorkQueue(), handler);
462     }
463    
464     /**
465 jsr166 1.79 * Creates a new {@code ScheduledThreadPoolExecutor} with the
466     * given initial parameters.
467 jsr166 1.21 *
468 jsr166 1.39 * @param corePoolSize the number of threads to keep in the pool, even
469     * if they are idle, unless {@code allowCoreThreadTimeOut} is set
470 dl 1.1 * @param threadFactory the factory to use when the executor
471 jsr166 1.39 * creates a new thread
472 dl 1.1 * @param handler the handler to use when execution is blocked
473 jsr166 1.39 * because the thread bounds and queue capacities are reached
474     * @throws IllegalArgumentException if {@code corePoolSize < 0}
475     * @throws NullPointerException if {@code threadFactory} or
476     * {@code handler} is null
477 dl 1.1 */
478     public ScheduledThreadPoolExecutor(int corePoolSize,
479 jsr166 1.56 ThreadFactory threadFactory,
480     RejectedExecutionHandler handler) {
481 jsr166 1.78 super(corePoolSize, Integer.MAX_VALUE,
482     DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
483 dl 1.1 new DelayedWorkQueue(), threadFactory, handler);
484     }
485    
486 dl 1.37 /**
487 jsr166 1.73 * Returns the nanoTime-based trigger time of a delayed action.
488 jsr166 1.54 */
489     private long triggerTime(long delay, TimeUnit unit) {
490     return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
491     }
492    
493     /**
494 jsr166 1.73 * Returns the nanoTime-based trigger time of a delayed action.
495 dl 1.50 */
496 jsr166 1.54 long triggerTime(long delay) {
497 jsr166 1.98 return System.nanoTime() +
498 jsr166 1.54 ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));
499     }
500    
501     /**
502     * Constrains the values of all delays in the queue to be within
503     * Long.MAX_VALUE of each other, to avoid overflow in compareTo.
504     * This may occur if a task is eligible to be dequeued, but has
505     * not yet been, while some other task is added with a delay of
506     * Long.MAX_VALUE.
507     */
508     private long overflowFree(long delay) {
509     Delayed head = (Delayed) super.getQueue().peek();
510     if (head != null) {
511 jsr166 1.62 long headDelay = head.getDelay(NANOSECONDS);
512 jsr166 1.54 if (headDelay < 0 && (delay - headDelay < 0))
513     delay = Long.MAX_VALUE + headDelay;
514     }
515     return delay;
516 dl 1.50 }
517    
518     /**
519 dl 1.37 * @throws RejectedExecutionException {@inheritDoc}
520     * @throws NullPointerException {@inheritDoc}
521     */
522 jsr166 1.21 public ScheduledFuture<?> schedule(Runnable command,
523     long delay,
524 dl 1.13 TimeUnit unit) {
525 dl 1.9 if (command == null || unit == null)
526 dl 1.1 throw new NullPointerException();
527 jsr166 1.76 RunnableScheduledFuture<Void> t = decorateTask(command,
528 jsr166 1.54 new ScheduledFutureTask<Void>(command, null,
529 jsr166 1.89 triggerTime(delay, unit),
530     sequencer.getAndIncrement()));
531 dl 1.1 delayedExecute(t);
532     return t;
533     }
534 jsr166 1.52
535 dl 1.37 /**
536     * @throws RejectedExecutionException {@inheritDoc}
537     * @throws NullPointerException {@inheritDoc}
538     */
539 jsr166 1.21 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
540     long delay,
541 dl 1.13 TimeUnit unit) {
542 dl 1.9 if (callable == null || unit == null)
543 dl 1.1 throw new NullPointerException();
544 peierls 1.22 RunnableScheduledFuture<V> t = decorateTask(callable,
545 jsr166 1.54 new ScheduledFutureTask<V>(callable,
546 jsr166 1.89 triggerTime(delay, unit),
547     sequencer.getAndIncrement()));
548 dl 1.1 delayedExecute(t);
549     return t;
550     }
551    
552 dl 1.37 /**
553     * @throws RejectedExecutionException {@inheritDoc}
554     * @throws NullPointerException {@inheritDoc}
555     * @throws IllegalArgumentException {@inheritDoc}
556     */
557 jsr166 1.21 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
558     long initialDelay,
559     long period,
560 dl 1.13 TimeUnit unit) {
561 dl 1.9 if (command == null || unit == null)
562 dl 1.1 throw new NullPointerException();
563 jsr166 1.96 if (period <= 0L)
564 dl 1.1 throw new IllegalArgumentException();
565 jsr166 1.48 ScheduledFutureTask<Void> sft =
566     new ScheduledFutureTask<Void>(command,
567     null,
568 jsr166 1.54 triggerTime(initialDelay, unit),
569 jsr166 1.89 unit.toNanos(period),
570     sequencer.getAndIncrement());
571 jsr166 1.44 RunnableScheduledFuture<Void> t = decorateTask(command, sft);
572 jsr166 1.48 sft.outerTask = t;
573 dl 1.1 delayedExecute(t);
574     return t;
575     }
576 jsr166 1.21
577 dl 1.37 /**
578     * @throws RejectedExecutionException {@inheritDoc}
579     * @throws NullPointerException {@inheritDoc}
580     * @throws IllegalArgumentException {@inheritDoc}
581     */
582 jsr166 1.21 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
583     long initialDelay,
584     long delay,
585 dl 1.13 TimeUnit unit) {
586 dl 1.9 if (command == null || unit == null)
587 dl 1.1 throw new NullPointerException();
588 jsr166 1.96 if (delay <= 0L)
589 dl 1.1 throw new IllegalArgumentException();
590 jsr166 1.48 ScheduledFutureTask<Void> sft =
591     new ScheduledFutureTask<Void>(command,
592     null,
593 jsr166 1.54 triggerTime(initialDelay, unit),
594 jsr166 1.97 -unit.toNanos(delay),
595 jsr166 1.89 sequencer.getAndIncrement());
596 jsr166 1.44 RunnableScheduledFuture<Void> t = decorateTask(command, sft);
597 jsr166 1.48 sft.outerTask = t;
598 dl 1.1 delayedExecute(t);
599     return t;
600     }
601 jsr166 1.21
602 dl 1.1 /**
603 jsr166 1.39 * Executes {@code command} with zero required delay.
604     * This has effect equivalent to
605     * {@link #schedule(Runnable,long,TimeUnit) schedule(command, 0, anyUnit)}.
606     * Note that inspections of the queue and of the list returned by
607     * {@code shutdownNow} will access the zero-delayed
608     * {@link ScheduledFuture}, not the {@code command} itself.
609     *
610     * <p>A consequence of the use of {@code ScheduledFuture} objects is
611     * that {@link ThreadPoolExecutor#afterExecute afterExecute} is always
612     * called with a null second {@code Throwable} argument, even if the
613     * {@code command} terminated abruptly. Instead, the {@code Throwable}
614     * thrown by such a task can be obtained via {@link Future#get}.
615 dl 1.1 *
616     * @throws RejectedExecutionException at discretion of
617 jsr166 1.39 * {@code RejectedExecutionHandler}, if the task
618     * cannot be accepted for execution because the
619     * executor has been shut down
620     * @throws NullPointerException {@inheritDoc}
621 dl 1.1 */
622     public void execute(Runnable command) {
623 jsr166 1.62 schedule(command, 0, NANOSECONDS);
624 dl 1.1 }
625    
626 dl 1.13 // Override AbstractExecutorService methods
627    
628 dl 1.37 /**
629     * @throws RejectedExecutionException {@inheritDoc}
630     * @throws NullPointerException {@inheritDoc}
631     */
632 dl 1.7 public Future<?> submit(Runnable task) {
633 jsr166 1.62 return schedule(task, 0, NANOSECONDS);
634 dl 1.7 }
635    
636 dl 1.37 /**
637     * @throws RejectedExecutionException {@inheritDoc}
638     * @throws NullPointerException {@inheritDoc}
639     */
640 dl 1.7 public <T> Future<T> submit(Runnable task, T result) {
641 jsr166 1.62 return schedule(Executors.callable(task, result), 0, NANOSECONDS);
642 dl 1.7 }
643    
644 dl 1.37 /**
645     * @throws RejectedExecutionException {@inheritDoc}
646     * @throws NullPointerException {@inheritDoc}
647     */
648 dl 1.7 public <T> Future<T> submit(Callable<T> task) {
649 jsr166 1.62 return schedule(task, 0, NANOSECONDS);
650 dl 1.7 }
651 dl 1.1
652     /**
653 dl 1.37 * Sets the policy on whether to continue executing existing
654 jsr166 1.39 * periodic tasks even when this executor has been {@code shutdown}.
655     * In this case, these tasks will only terminate upon
656     * {@code shutdownNow} or after setting the policy to
657     * {@code false} when already shutdown.
658     * This value is by default {@code false}.
659 jsr166 1.30 *
660 jsr166 1.68 * @param value if {@code true}, continue after shutdown, else don't
661 jsr166 1.25 * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy
662 dl 1.1 */
663     public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
664     continueExistingPeriodicTasksAfterShutdown = value;
665 jsr166 1.39 if (!value && isShutdown())
666 dl 1.37 onShutdown();
667 dl 1.1 }
668    
669     /**
670 jsr166 1.21 * Gets the policy on whether to continue executing existing
671 jsr166 1.39 * periodic tasks even when this executor has been {@code shutdown}.
672     * In this case, these tasks will only terminate upon
673     * {@code shutdownNow} or after setting the policy to
674     * {@code false} when already shutdown.
675     * This value is by default {@code false}.
676 jsr166 1.30 *
677 jsr166 1.39 * @return {@code true} if will continue after shutdown
678 dl 1.16 * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy
679 dl 1.1 */
680     public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
681     return continueExistingPeriodicTasksAfterShutdown;
682     }
683    
684     /**
685 jsr166 1.21 * Sets the policy on whether to execute existing delayed
686 jsr166 1.39 * tasks even when this executor has been {@code shutdown}.
687     * In this case, these tasks will only terminate upon
688     * {@code shutdownNow}, or after setting the policy to
689     * {@code false} when already shutdown.
690     * This value is by default {@code true}.
691 jsr166 1.30 *
692 jsr166 1.68 * @param value if {@code true}, execute after shutdown, else don't
693 dl 1.16 * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
694 dl 1.1 */
695     public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
696     executeExistingDelayedTasksAfterShutdown = value;
697 jsr166 1.39 if (!value && isShutdown())
698 dl 1.37 onShutdown();
699 dl 1.1 }
700    
701     /**
702 jsr166 1.21 * Gets the policy on whether to execute existing delayed
703 jsr166 1.39 * tasks even when this executor has been {@code shutdown}.
704     * In this case, these tasks will only terminate upon
705     * {@code shutdownNow}, or after setting the policy to
706     * {@code false} when already shutdown.
707     * This value is by default {@code true}.
708 jsr166 1.30 *
709 jsr166 1.39 * @return {@code true} if will execute after shutdown
710 dl 1.16 * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy
711 dl 1.1 */
712     public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
713     return executeExistingDelayedTasksAfterShutdown;
714     }
715    
716     /**
717 jsr166 1.46 * Sets the policy on whether cancelled tasks should be immediately
718     * removed from the work queue at time of cancellation. This value is
719     * by default {@code false}.
720 dl 1.41 *
721 jsr166 1.42 * @param value if {@code true}, remove on cancellation, else don't
722 dl 1.41 * @see #getRemoveOnCancelPolicy
723 jsr166 1.43 * @since 1.7
724 dl 1.41 */
725     public void setRemoveOnCancelPolicy(boolean value) {
726     removeOnCancel = value;
727     }
728    
729     /**
730 jsr166 1.46 * Gets the policy on whether cancelled tasks should be immediately
731     * removed from the work queue at time of cancellation. This value is
732     * by default {@code false}.
733 dl 1.41 *
734 jsr166 1.46 * @return {@code true} if cancelled tasks are immediately removed
735     * from the queue
736 dl 1.41 * @see #setRemoveOnCancelPolicy
737 jsr166 1.43 * @since 1.7
738 dl 1.41 */
739     public boolean getRemoveOnCancelPolicy() {
740     return removeOnCancel;
741     }
742    
743     /**
744 dl 1.1 * Initiates an orderly shutdown in which previously submitted
745 jsr166 1.49 * tasks are executed, but no new tasks will be accepted.
746     * Invocation has no additional effect if already shut down.
747     *
748     * <p>This method does not wait for previously submitted tasks to
749     * complete execution. Use {@link #awaitTermination awaitTermination}
750     * to do that.
751     *
752     * <p>If the {@code ExecuteExistingDelayedTasksAfterShutdownPolicy}
753     * has been set {@code false}, existing delayed tasks whose delays
754     * have not yet elapsed are cancelled. And unless the {@code
755     * ContinueExistingPeriodicTasksAfterShutdownPolicy} has been set
756     * {@code true}, future executions of existing periodic tasks will
757     * be cancelled.
758 jsr166 1.39 *
759     * @throws SecurityException {@inheritDoc}
760 dl 1.1 */
761     public void shutdown() {
762     super.shutdown();
763     }
764    
765     /**
766     * Attempts to stop all actively executing tasks, halts the
767 jsr166 1.30 * processing of waiting tasks, and returns a list of the tasks
768 jsr166 1.92 * that were awaiting execution. These tasks are drained (removed)
769     * from the task queue upon return from this method.
770 jsr166 1.21 *
771 jsr166 1.49 * <p>This method does not wait for actively executing tasks to
772     * terminate. Use {@link #awaitTermination awaitTermination} to
773     * do that.
774     *
775 dl 1.1 * <p>There are no guarantees beyond best-effort attempts to stop
776 dl 1.18 * processing actively executing tasks. This implementation
777 jsr166 1.93 * interrupts tasks via {@link Thread#interrupt}; any task that
778 jsr166 1.31 * fails to respond to interrupts may never terminate.
779 dl 1.1 *
780 jsr166 1.39 * @return list of tasks that never commenced execution.
781 jsr166 1.77 * Each element of this list is a {@link ScheduledFuture}.
782     * For tasks submitted via one of the {@code schedule}
783     * methods, the element will be identical to the returned
784     * {@code ScheduledFuture}. For tasks submitted using
785 jsr166 1.84 * {@link #execute execute}, the element will be a
786     * zero-delay {@code ScheduledFuture}.
787 jsr166 1.31 * @throws SecurityException {@inheritDoc}
788 dl 1.1 */
789 tim 1.4 public List<Runnable> shutdownNow() {
790 dl 1.1 return super.shutdownNow();
791     }
792    
793     /**
794 jsr166 1.95 * Returns the task queue used by this executor. Access to the
795     * task queue is intended primarily for debugging and monitoring.
796     * This queue may be in active use. Retrieving the task queue
797     * does not prevent queued tasks from executing.
798     *
799     * <p>Each element of this queue is a {@link ScheduledFuture}.
800 jsr166 1.77 * For tasks submitted via one of the {@code schedule} methods, the
801     * element will be identical to the returned {@code ScheduledFuture}.
802 jsr166 1.84 * For tasks submitted using {@link #execute execute}, the element
803     * will be a zero-delay {@code ScheduledFuture}.
804 jsr166 1.77 *
805     * <p>Iteration over this queue is <em>not</em> guaranteed to traverse
806     * tasks in the order in which they will execute.
807 dl 1.1 *
808     * @return the task queue
809     */
810     public BlockingQueue<Runnable> getQueue() {
811     return super.getQueue();
812     }
813    
814 dl 1.13 /**
815 dl 1.40 * Specialized delay queue. To mesh with TPE declarations, this
816     * class must be declared as a BlockingQueue<Runnable> even though
817 jsr166 1.42 * it can only hold RunnableScheduledFutures.
818 jsr166 1.21 */
819 dl 1.40 static class DelayedWorkQueue extends AbstractQueue<Runnable>
820 dl 1.13 implements BlockingQueue<Runnable> {
821 jsr166 1.21
822 dl 1.40 /*
823     * A DelayedWorkQueue is based on a heap-based data structure
824     * like those in DelayQueue and PriorityQueue, except that
825     * every ScheduledFutureTask also records its index into the
826     * heap array. This eliminates the need to find a task upon
827     * cancellation, greatly speeding up removal (down from O(n)
828     * to O(log n)), and reducing garbage retention that would
829     * otherwise occur by waiting for the element to rise to top
830     * before clearing. But because the queue may also hold
831     * RunnableScheduledFutures that are not ScheduledFutureTasks,
832     * we are not guaranteed to have such indices available, in
833     * which case we fall back to linear search. (We expect that
834     * most tasks will not be decorated, and that the faster cases
835     * will be much more common.)
836     *
837     * All heap operations must record index changes -- mainly
838     * within siftUp and siftDown. Upon removal, a task's
839     * heapIndex is set to -1. Note that ScheduledFutureTasks can
840     * appear at most once in the queue (this need not be true for
841     * other kinds of tasks or work queues), so are uniquely
842     * identified by heapIndex.
843     */
844    
845 jsr166 1.46 private static final int INITIAL_CAPACITY = 16;
846 jsr166 1.61 private RunnableScheduledFuture<?>[] queue =
847     new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
848 jsr166 1.46 private final ReentrantLock lock = new ReentrantLock();
849 jsr166 1.80 private int size;
850 dl 1.40
851 jsr166 1.48 /**
852     * Thread designated to wait for the task at the head of the
853     * queue. This variant of the Leader-Follower pattern
854     * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
855     * minimize unnecessary timed waiting. When a thread becomes
856     * the leader, it waits only for the next delay to elapse, but
857     * other threads await indefinitely. The leader thread must
858     * signal some other thread before returning from take() or
859     * poll(...), unless some other thread becomes leader in the
860     * interim. Whenever the head of the queue is replaced with a
861     * task with an earlier expiration time, the leader field is
862     * invalidated by being reset to null, and some waiting
863     * thread, but not necessarily the current leader, is
864     * signalled. So waiting threads must be prepared to acquire
865     * and lose leadership while waiting.
866     */
867 jsr166 1.80 private Thread leader;
868 jsr166 1.48
869     /**
870     * Condition signalled when a newer task becomes available at the
871     * head of the queue or a new thread may need to become leader.
872     */
873     private final Condition available = lock.newCondition();
874 dl 1.40
875     /**
876 jsr166 1.66 * Sets f's heapIndex if it is a ScheduledFutureTask.
877 dl 1.40 */
878 jsr166 1.61 private void setIndex(RunnableScheduledFuture<?> f, int idx) {
879 dl 1.40 if (f instanceof ScheduledFutureTask)
880     ((ScheduledFutureTask)f).heapIndex = idx;
881     }
882    
883     /**
884 jsr166 1.66 * Sifts element added at bottom up to its heap-ordered spot.
885 dl 1.40 * Call only when holding lock.
886     */
887 jsr166 1.61 private void siftUp(int k, RunnableScheduledFuture<?> key) {
888 dl 1.40 while (k > 0) {
889     int parent = (k - 1) >>> 1;
890 jsr166 1.61 RunnableScheduledFuture<?> e = queue[parent];
891 dl 1.40 if (key.compareTo(e) >= 0)
892     break;
893     queue[k] = e;
894     setIndex(e, k);
895     k = parent;
896     }
897     queue[k] = key;
898     setIndex(key, k);
899     }
900    
901     /**
902 jsr166 1.66 * Sifts element added at top down to its heap-ordered spot.
903 dl 1.40 * Call only when holding lock.
904     */
905 jsr166 1.61 private void siftDown(int k, RunnableScheduledFuture<?> key) {
906 jsr166 1.42 int half = size >>> 1;
907 dl 1.40 while (k < half) {
908 jsr166 1.42 int child = (k << 1) + 1;
909 jsr166 1.61 RunnableScheduledFuture<?> c = queue[child];
910 dl 1.40 int right = child + 1;
911     if (right < size && c.compareTo(queue[right]) > 0)
912     c = queue[child = right];
913     if (key.compareTo(c) <= 0)
914     break;
915     queue[k] = c;
916     setIndex(c, k);
917     k = child;
918     }
919     queue[k] = key;
920     setIndex(key, k);
921     }
922    
923     /**
924 jsr166 1.66 * Resizes the heap array. Call only when holding lock.
925 dl 1.40 */
926     private void grow() {
927     int oldCapacity = queue.length;
928     int newCapacity = oldCapacity + (oldCapacity >> 1); // grow 50%
929     if (newCapacity < 0) // overflow
930     newCapacity = Integer.MAX_VALUE;
931     queue = Arrays.copyOf(queue, newCapacity);
932     }
933    
934     /**
935 jsr166 1.66 * Finds index of given object, or -1 if absent.
936 dl 1.40 */
937     private int indexOf(Object x) {
938     if (x != null) {
939 jsr166 1.48 if (x instanceof ScheduledFutureTask) {
940     int i = ((ScheduledFutureTask) x).heapIndex;
941     // Sanity check; x could conceivably be a
942     // ScheduledFutureTask from some other pool.
943     if (i >= 0 && i < size && queue[i] == x)
944     return i;
945     } else {
946     for (int i = 0; i < size; i++)
947     if (x.equals(queue[i]))
948     return i;
949     }
950 dl 1.40 }
951     return -1;
952     }
953    
954 jsr166 1.48 public boolean contains(Object x) {
955     final ReentrantLock lock = this.lock;
956 jsr166 1.45 lock.lock();
957     try {
958 jsr166 1.48 return indexOf(x) != -1;
959 jsr166 1.45 } finally {
960     lock.unlock();
961     }
962 jsr166 1.48 }
963 jsr166 1.45
964 dl 1.40 public boolean remove(Object x) {
965     final ReentrantLock lock = this.lock;
966     lock.lock();
967     try {
968 jsr166 1.45 int i = indexOf(x);
969 jsr166 1.48 if (i < 0)
970     return false;
971 jsr166 1.45
972 jsr166 1.48 setIndex(queue[i], -1);
973     int s = --size;
974 jsr166 1.61 RunnableScheduledFuture<?> replacement = queue[s];
975 jsr166 1.48 queue[s] = null;
976     if (s != i) {
977     siftDown(i, replacement);
978     if (queue[i] == replacement)
979     siftUp(i, replacement);
980     }
981     return true;
982 dl 1.40 } finally {
983     lock.unlock();
984     }
985     }
986    
987     public int size() {
988     final ReentrantLock lock = this.lock;
989     lock.lock();
990     try {
991 jsr166 1.45 return size;
992 dl 1.40 } finally {
993     lock.unlock();
994     }
995     }
996    
997 jsr166 1.42 public boolean isEmpty() {
998     return size() == 0;
999 dl 1.40 }
1000    
1001     public int remainingCapacity() {
1002     return Integer.MAX_VALUE;
1003     }
1004    
1005 jsr166 1.61 public RunnableScheduledFuture<?> peek() {
1006 dl 1.40 final ReentrantLock lock = this.lock;
1007     lock.lock();
1008     try {
1009     return queue[0];
1010     } finally {
1011     lock.unlock();
1012     }
1013 dl 1.13 }
1014    
1015 dl 1.40 public boolean offer(Runnable x) {
1016     if (x == null)
1017     throw new NullPointerException();
1018 jsr166 1.61 RunnableScheduledFuture<?> e = (RunnableScheduledFuture<?>)x;
1019 dl 1.40 final ReentrantLock lock = this.lock;
1020     lock.lock();
1021     try {
1022     int i = size;
1023     if (i >= queue.length)
1024     grow();
1025     size = i + 1;
1026     if (i == 0) {
1027     queue[0] = e;
1028     setIndex(e, 0);
1029 jsr166 1.45 } else {
1030 dl 1.40 siftUp(i, e);
1031     }
1032 jsr166 1.46 if (queue[0] == e) {
1033 jsr166 1.48 leader = null;
1034 jsr166 1.46 available.signal();
1035 jsr166 1.48 }
1036 dl 1.40 } finally {
1037     lock.unlock();
1038     }
1039     return true;
1040 jsr166 1.48 }
1041 dl 1.40
1042     public void put(Runnable e) {
1043     offer(e);
1044     }
1045    
1046     public boolean add(Runnable e) {
1047 jsr166 1.48 return offer(e);
1048     }
1049 dl 1.40
1050     public boolean offer(Runnable e, long timeout, TimeUnit unit) {
1051     return offer(e);
1052     }
1053 jsr166 1.42
1054 jsr166 1.46 /**
1055     * Performs common bookkeeping for poll and take: Replaces
1056 jsr166 1.47 * first element with last and sifts it down. Call only when
1057     * holding lock.
1058 jsr166 1.46 * @param f the task to remove and return
1059     */
1060 jsr166 1.61 private RunnableScheduledFuture<?> finishPoll(RunnableScheduledFuture<?> f) {
1061 jsr166 1.46 int s = --size;
1062 jsr166 1.61 RunnableScheduledFuture<?> x = queue[s];
1063 jsr166 1.46 queue[s] = null;
1064     if (s != 0)
1065     siftDown(0, x);
1066     setIndex(f, -1);
1067     return f;
1068     }
1069    
1070 jsr166 1.61 public RunnableScheduledFuture<?> poll() {
1071 dl 1.40 final ReentrantLock lock = this.lock;
1072     lock.lock();
1073     try {
1074 jsr166 1.61 RunnableScheduledFuture<?> first = queue[0];
1075 jsr166 1.87 return (first == null || first.getDelay(NANOSECONDS) > 0)
1076     ? null
1077     : finishPoll(first);
1078 dl 1.40 } finally {
1079     lock.unlock();
1080     }
1081     }
1082    
1083 jsr166 1.61 public RunnableScheduledFuture<?> take() throws InterruptedException {
1084 dl 1.40 final ReentrantLock lock = this.lock;
1085     lock.lockInterruptibly();
1086     try {
1087     for (;;) {
1088 jsr166 1.61 RunnableScheduledFuture<?> first = queue[0];
1089 jsr166 1.42 if (first == null)
1090 dl 1.40 available.await();
1091     else {
1092 jsr166 1.62 long delay = first.getDelay(NANOSECONDS);
1093 jsr166 1.96 if (delay <= 0L)
1094 jsr166 1.48 return finishPoll(first);
1095 jsr166 1.71 first = null; // don't retain ref while waiting
1096     if (leader != null)
1097 jsr166 1.48 available.await();
1098     else {
1099     Thread thisThread = Thread.currentThread();
1100     leader = thisThread;
1101     try {
1102     available.awaitNanos(delay);
1103     } finally {
1104     if (leader == thisThread)
1105     leader = null;
1106     }
1107     }
1108 dl 1.40 }
1109     }
1110     } finally {
1111 jsr166 1.48 if (leader == null && queue[0] != null)
1112     available.signal();
1113 dl 1.40 lock.unlock();
1114     }
1115     }
1116    
1117 jsr166 1.61 public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
1118 dl 1.40 throws InterruptedException {
1119     long nanos = unit.toNanos(timeout);
1120     final ReentrantLock lock = this.lock;
1121     lock.lockInterruptibly();
1122     try {
1123     for (;;) {
1124 jsr166 1.61 RunnableScheduledFuture<?> first = queue[0];
1125 dl 1.40 if (first == null) {
1126 jsr166 1.96 if (nanos <= 0L)
1127 dl 1.40 return null;
1128     else
1129     nanos = available.awaitNanos(nanos);
1130     } else {
1131 jsr166 1.62 long delay = first.getDelay(NANOSECONDS);
1132 jsr166 1.96 if (delay <= 0L)
1133 dl 1.40 return finishPoll(first);
1134 jsr166 1.96 if (nanos <= 0L)
1135 jsr166 1.48 return null;
1136 jsr166 1.71 first = null; // don't retain ref while waiting
1137 jsr166 1.48 if (nanos < delay || leader != null)
1138     nanos = available.awaitNanos(nanos);
1139     else {
1140     Thread thisThread = Thread.currentThread();
1141     leader = thisThread;
1142     try {
1143     long timeLeft = available.awaitNanos(delay);
1144     nanos -= delay - timeLeft;
1145     } finally {
1146     if (leader == thisThread)
1147     leader = null;
1148     }
1149     }
1150     }
1151     }
1152 dl 1.40 } finally {
1153 jsr166 1.48 if (leader == null && queue[0] != null)
1154     available.signal();
1155 dl 1.40 lock.unlock();
1156     }
1157     }
1158    
1159     public void clear() {
1160     final ReentrantLock lock = this.lock;
1161     lock.lock();
1162     try {
1163     for (int i = 0; i < size; i++) {
1164 jsr166 1.61 RunnableScheduledFuture<?> t = queue[i];
1165 dl 1.40 if (t != null) {
1166     queue[i] = null;
1167     setIndex(t, -1);
1168     }
1169     }
1170     size = 0;
1171     } finally {
1172     lock.unlock();
1173     }
1174 dl 1.13 }
1175 dl 1.40
1176     /**
1177 jsr166 1.66 * Returns first element only if it is expired.
1178 dl 1.40 * Used only by drainTo. Call only when holding lock.
1179     */
1180 jsr166 1.62 private RunnableScheduledFuture<?> peekExpired() {
1181     // assert lock.isHeldByCurrentThread();
1182 jsr166 1.61 RunnableScheduledFuture<?> first = queue[0];
1183 jsr166 1.62 return (first == null || first.getDelay(NANOSECONDS) > 0) ?
1184     null : first;
1185 dl 1.40 }
1186    
1187     public int drainTo(Collection<? super Runnable> c) {
1188     if (c == null)
1189     throw new NullPointerException();
1190     if (c == this)
1191     throw new IllegalArgumentException();
1192     final ReentrantLock lock = this.lock;
1193     lock.lock();
1194     try {
1195 jsr166 1.61 RunnableScheduledFuture<?> first;
1196 dl 1.40 int n = 0;
1197 jsr166 1.62 while ((first = peekExpired()) != null) {
1198     c.add(first); // In this order, in case add() throws.
1199     finishPoll(first);
1200 jsr166 1.48 ++n;
1201     }
1202 dl 1.40 return n;
1203     } finally {
1204     lock.unlock();
1205     }
1206 dl 1.13 }
1207    
1208 jsr166 1.21 public int drainTo(Collection<? super Runnable> c, int maxElements) {
1209 dl 1.40 if (c == null)
1210     throw new NullPointerException();
1211     if (c == this)
1212     throw new IllegalArgumentException();
1213     if (maxElements <= 0)
1214     return 0;
1215     final ReentrantLock lock = this.lock;
1216     lock.lock();
1217     try {
1218 jsr166 1.61 RunnableScheduledFuture<?> first;
1219 dl 1.40 int n = 0;
1220 jsr166 1.62 while (n < maxElements && (first = peekExpired()) != null) {
1221     c.add(first); // In this order, in case add() throws.
1222     finishPoll(first);
1223 jsr166 1.48 ++n;
1224     }
1225 dl 1.40 return n;
1226     } finally {
1227     lock.unlock();
1228     }
1229     }
1230    
1231     public Object[] toArray() {
1232     final ReentrantLock lock = this.lock;
1233     lock.lock();
1234     try {
1235 jsr166 1.45 return Arrays.copyOf(queue, size, Object[].class);
1236 dl 1.40 } finally {
1237     lock.unlock();
1238     }
1239     }
1240    
1241 jsr166 1.48 @SuppressWarnings("unchecked")
1242 dl 1.40 public <T> T[] toArray(T[] a) {
1243     final ReentrantLock lock = this.lock;
1244     lock.lock();
1245     try {
1246     if (a.length < size)
1247     return (T[]) Arrays.copyOf(queue, size, a.getClass());
1248     System.arraycopy(queue, 0, a, 0, size);
1249     if (a.length > size)
1250     a[size] = null;
1251     return a;
1252     } finally {
1253     lock.unlock();
1254     }
1255 dl 1.13 }
1256    
1257 jsr166 1.21 public Iterator<Runnable> iterator() {
1258 jsr166 1.45 return new Itr(Arrays.copyOf(queue, size));
1259 dl 1.40 }
1260 jsr166 1.42
1261 dl 1.40 /**
1262     * Snapshot iterator that works off copy of underlying q array.
1263     */
1264     private class Itr implements Iterator<Runnable> {
1265 jsr166 1.74 final RunnableScheduledFuture<?>[] array;
1266 jsr166 1.86 int cursor; // index of next element to return; initially 0
1267     int lastRet = -1; // index of last element returned; -1 if no such
1268 jsr166 1.42
1269 jsr166 1.74 Itr(RunnableScheduledFuture<?>[] array) {
1270 dl 1.40 this.array = array;
1271     }
1272 jsr166 1.42
1273 dl 1.40 public boolean hasNext() {
1274     return cursor < array.length;
1275     }
1276 jsr166 1.42
1277 dl 1.40 public Runnable next() {
1278     if (cursor >= array.length)
1279     throw new NoSuchElementException();
1280     lastRet = cursor;
1281 jsr166 1.45 return array[cursor++];
1282 dl 1.40 }
1283 jsr166 1.42
1284 dl 1.40 public void remove() {
1285     if (lastRet < 0)
1286     throw new IllegalStateException();
1287     DelayedWorkQueue.this.remove(array[lastRet]);
1288     lastRet = -1;
1289     }
1290 dl 1.13 }
1291     }
1292 dl 1.1 }