ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.67
Committed: Tue Dec 2 05:48:28 2014 UTC (9 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.66: +1 -1 lines
Log Message:
this collection => this XXX

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.23 * Expert Group and released to the public domain, as explained at
4 jsr166 1.52 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 jsr166 1.56 import static java.util.concurrent.TimeUnit.NANOSECONDS;
9     import java.util.concurrent.locks.Condition;
10     import java.util.concurrent.locks.ReentrantLock;
11 tim 1.1 import java.util.*;
12    
13     /**
14 dl 1.27 * An unbounded {@linkplain BlockingQueue blocking queue} of
15 jsr166 1.61 * {@code Delayed} elements, in which an element can only be taken
16 dl 1.27 * when its delay has expired. The <em>head</em> of the queue is that
17 jsr166 1.61 * {@code Delayed} element whose delay expired furthest in the
18     * past. If no delay has expired there is no head and {@code poll}
19     * will return {@code null}. Expiration occurs when an element's
20     * {@code getDelay(TimeUnit.NANOSECONDS)} method returns a value less
21 dl 1.36 * than or equal to zero. Even though unexpired elements cannot be
22 jsr166 1.61 * removed using {@code take} or {@code poll}, they are otherwise
23     * treated as normal elements. For example, the {@code size} method
24 dl 1.36 * returns the count of both expired and unexpired elements.
25 jsr166 1.39 * This queue does not permit null elements.
26 dl 1.25 *
27 dl 1.26 * <p>This class and its iterator implement all of the
28     * <em>optional</em> methods of the {@link Collection} and {@link
29 dl 1.53 * Iterator} interfaces. The Iterator provided in method {@link
30     * #iterator()} is <em>not</em> guaranteed to traverse the elements of
31     * the DelayQueue in any particular order.
32 dl 1.26 *
33 dl 1.25 * <p>This class is a member of the
34 jsr166 1.46 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
35 dl 1.25 * Java Collections Framework</a>.
36     *
37 dl 1.4 * @since 1.5
38     * @author Doug Lea
39 jsr166 1.67 * @param <E> the type of elements held in this queue
40 dl 1.19 */
41 dl 1.3 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
42     implements BlockingQueue<E> {
43 tim 1.6
44 jsr166 1.62 private final transient ReentrantLock lock = new ReentrantLock();
45 dl 1.3 private final PriorityQueue<E> q = new PriorityQueue<E>();
46 tim 1.1
47 dl 1.4 /**
48 jsr166 1.48 * Thread designated to wait for the element at the head of
49     * the queue. This variant of the Leader-Follower pattern
50     * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
51     * minimize unnecessary timed waiting. When a thread becomes
52     * the leader, it waits only for the next delay to elapse, but
53     * other threads await indefinitely. The leader thread must
54     * signal some other thread before returning from take() or
55     * poll(...), unless some other thread becomes leader in the
56     * interim. Whenever the head of the queue is replaced with
57     * an element with an earlier expiration time, the leader
58     * field is invalidated by being reset to null, and some
59     * waiting thread, but not necessarily the current leader, is
60     * signalled. So waiting threads must be prepared to acquire
61     * and lose leadership while waiting.
62     */
63 jsr166 1.66 private Thread leader;
64 jsr166 1.48
65     /**
66     * Condition signalled when a newer element becomes available
67     * at the head of the queue or a new thread may need to
68     * become leader.
69     */
70     private final Condition available = lock.newCondition();
71    
72     /**
73 jsr166 1.61 * Creates a new {@code DelayQueue} that is initially empty.
74 dl 1.4 */
75 tim 1.1 public DelayQueue() {}
76    
77 tim 1.6 /**
78 jsr166 1.61 * Creates a {@code DelayQueue} initially containing the elements of the
79 dholmes 1.7 * given collection of {@link Delayed} instances.
80     *
81 jsr166 1.32 * @param c the collection of elements to initially contain
82     * @throws NullPointerException if the specified collection or any
83     * of its elements are null
84 tim 1.6 */
85     public DelayQueue(Collection<? extends E> c) {
86     this.addAll(c);
87     }
88    
89 dholmes 1.7 /**
90 dl 1.16 * Inserts the specified element into this delay queue.
91 dholmes 1.7 *
92 jsr166 1.30 * @param e the element to add
93 jsr166 1.61 * @return {@code true} (as specified by {@link Collection#add})
94 jsr166 1.32 * @throws NullPointerException if the specified element is null
95     */
96     public boolean add(E e) {
97     return offer(e);
98     }
99    
100     /**
101     * Inserts the specified element into this delay queue.
102     *
103     * @param e the element to add
104 jsr166 1.61 * @return {@code true}
105 jsr166 1.32 * @throws NullPointerException if the specified element is null
106 dholmes 1.7 */
107 jsr166 1.30 public boolean offer(E e) {
108 dl 1.21 final ReentrantLock lock = this.lock;
109 dl 1.2 lock.lock();
110     try {
111 jsr166 1.30 q.offer(e);
112 jsr166 1.48 if (q.peek() == e) {
113 jsr166 1.49 leader = null;
114 jsr166 1.48 available.signal();
115 jsr166 1.49 }
116 dl 1.2 return true;
117 tim 1.13 } finally {
118 dl 1.2 lock.unlock();
119     }
120     }
121    
122 dholmes 1.7 /**
123 jsr166 1.32 * Inserts the specified element into this delay queue. As the queue is
124 dholmes 1.7 * unbounded this method will never block.
125 jsr166 1.32 *
126 jsr166 1.30 * @param e the element to add
127 jsr166 1.32 * @throws NullPointerException {@inheritDoc}
128 dholmes 1.7 */
129 jsr166 1.30 public void put(E e) {
130     offer(e);
131 dl 1.2 }
132    
133 dholmes 1.7 /**
134 dl 1.16 * Inserts the specified element into this delay queue. As the queue is
135 dholmes 1.7 * unbounded this method will never block.
136 jsr166 1.32 *
137 jsr166 1.30 * @param e the element to add
138 dl 1.14 * @param timeout This parameter is ignored as the method never blocks
139 dholmes 1.7 * @param unit This parameter is ignored as the method never blocks
140 jsr166 1.61 * @return {@code true}
141 jsr166 1.32 * @throws NullPointerException {@inheritDoc}
142 dholmes 1.7 */
143 jsr166 1.30 public boolean offer(E e, long timeout, TimeUnit unit) {
144     return offer(e);
145 dl 1.2 }
146    
147 dholmes 1.7 /**
148 jsr166 1.61 * Retrieves and removes the head of this queue, or returns {@code null}
149 jsr166 1.32 * if this queue has no elements with an expired delay.
150 dholmes 1.7 *
151 jsr166 1.61 * @return the head of this queue, or {@code null} if this
152 jsr166 1.32 * queue has no elements with an expired delay
153 dholmes 1.7 */
154 jsr166 1.32 public E poll() {
155     final ReentrantLock lock = this.lock;
156     lock.lock();
157     try {
158     E first = q.peek();
159 jsr166 1.56 if (first == null || first.getDelay(NANOSECONDS) > 0)
160 jsr166 1.32 return null;
161 jsr166 1.48 else
162     return q.poll();
163 jsr166 1.32 } finally {
164     lock.unlock();
165     }
166 dl 1.2 }
167    
168 dl 1.27 /**
169 jsr166 1.32 * Retrieves and removes the head of this queue, waiting if necessary
170     * until an element with an expired delay is available on this queue.
171     *
172 dl 1.27 * @return the head of this queue
173 jsr166 1.32 * @throws InterruptedException {@inheritDoc}
174 dl 1.27 */
175 dl 1.3 public E take() throws InterruptedException {
176 dl 1.21 final ReentrantLock lock = this.lock;
177 dl 1.2 lock.lockInterruptibly();
178     try {
179     for (;;) {
180 dl 1.3 E first = q.peek();
181 jsr166 1.48 if (first == null)
182 dl 1.4 available.await();
183 jsr166 1.49 else {
184 jsr166 1.56 long delay = first.getDelay(NANOSECONDS);
185 jsr166 1.49 if (delay <= 0)
186     return q.poll();
187 jsr166 1.64 first = null; // don't retain ref while waiting
188     if (leader != null)
189 jsr166 1.49 available.await();
190     else {
191     Thread thisThread = Thread.currentThread();
192     leader = thisThread;
193     try {
194     available.awaitNanos(delay);
195     } finally {
196     if (leader == thisThread)
197     leader = null;
198     }
199 dl 1.2 }
200     }
201     }
202 tim 1.13 } finally {
203 jsr166 1.49 if (leader == null && q.peek() != null)
204     available.signal();
205 dl 1.2 lock.unlock();
206     }
207     }
208    
209 dl 1.27 /**
210 jsr166 1.32 * Retrieves and removes the head of this queue, waiting if necessary
211     * until an element with an expired delay is available on this queue,
212     * or the specified wait time expires.
213     *
214 jsr166 1.61 * @return the head of this queue, or {@code null} if the
215 jsr166 1.32 * specified waiting time elapses before an element with
216     * an expired delay becomes available
217     * @throws InterruptedException {@inheritDoc}
218 dl 1.27 */
219     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
220 jsr166 1.41 long nanos = unit.toNanos(timeout);
221 dl 1.21 final ReentrantLock lock = this.lock;
222 dl 1.2 lock.lockInterruptibly();
223     try {
224     for (;;) {
225 dl 1.3 E first = q.peek();
226 dl 1.2 if (first == null) {
227     if (nanos <= 0)
228     return null;
229     else
230 dl 1.4 nanos = available.awaitNanos(nanos);
231 tim 1.13 } else {
232 jsr166 1.56 long delay = first.getDelay(NANOSECONDS);
233 jsr166 1.49 if (delay <= 0)
234     return q.poll();
235     if (nanos <= 0)
236     return null;
237 jsr166 1.64 first = null; // don't retain ref while waiting
238 jsr166 1.49 if (nanos < delay || leader != null)
239     nanos = available.awaitNanos(nanos);
240     else {
241     Thread thisThread = Thread.currentThread();
242     leader = thisThread;
243     try {
244     long timeLeft = available.awaitNanos(delay);
245     nanos -= delay - timeLeft;
246     } finally {
247     if (leader == thisThread)
248     leader = null;
249     }
250     }
251 dl 1.2 }
252     }
253 tim 1.13 } finally {
254 jsr166 1.49 if (leader == null && q.peek() != null)
255     available.signal();
256 dl 1.2 lock.unlock();
257     }
258     }
259    
260 dl 1.27 /**
261 dl 1.36 * Retrieves, but does not remove, the head of this queue, or
262 jsr166 1.61 * returns {@code null} if this queue is empty. Unlike
263     * {@code poll}, if no expired elements are available in the queue,
264 dl 1.36 * this method returns the element that will expire next,
265     * if one exists.
266 dl 1.27 *
267 jsr166 1.61 * @return the head of this queue, or {@code null} if this
268 jsr166 1.63 * queue is empty
269 dl 1.27 */
270 dl 1.3 public E peek() {
271 dl 1.21 final ReentrantLock lock = this.lock;
272 dl 1.2 lock.lock();
273     try {
274     return q.peek();
275 tim 1.13 } finally {
276 dl 1.2 lock.unlock();
277     }
278 tim 1.1 }
279    
280 dl 1.2 public int size() {
281 dl 1.21 final ReentrantLock lock = this.lock;
282 dl 1.2 lock.lock();
283     try {
284     return q.size();
285 tim 1.13 } finally {
286 dl 1.2 lock.unlock();
287     }
288     }
289    
290 jsr166 1.32 /**
291 jsr166 1.59 * Returns first element only if it is expired.
292 jsr166 1.56 * Used only by drainTo. Call only when holding lock.
293     */
294     private E peekExpired() {
295     // assert lock.isHeldByCurrentThread();
296     E first = q.peek();
297     return (first == null || first.getDelay(NANOSECONDS) > 0) ?
298     null : first;
299     }
300    
301     /**
302 jsr166 1.32 * @throws UnsupportedOperationException {@inheritDoc}
303     * @throws ClassCastException {@inheritDoc}
304     * @throws NullPointerException {@inheritDoc}
305     * @throws IllegalArgumentException {@inheritDoc}
306     */
307 dl 1.17 public int drainTo(Collection<? super E> c) {
308     if (c == null)
309     throw new NullPointerException();
310     if (c == this)
311     throw new IllegalArgumentException();
312 dl 1.21 final ReentrantLock lock = this.lock;
313 dl 1.17 lock.lock();
314     try {
315     int n = 0;
316 jsr166 1.56 for (E e; (e = peekExpired()) != null;) {
317     c.add(e); // In this order, in case add() throws.
318     q.poll();
319 dl 1.17 ++n;
320     }
321     return n;
322     } finally {
323     lock.unlock();
324     }
325     }
326    
327 jsr166 1.32 /**
328     * @throws UnsupportedOperationException {@inheritDoc}
329     * @throws ClassCastException {@inheritDoc}
330     * @throws NullPointerException {@inheritDoc}
331     * @throws IllegalArgumentException {@inheritDoc}
332     */
333 dl 1.17 public int drainTo(Collection<? super E> c, int maxElements) {
334     if (c == null)
335     throw new NullPointerException();
336     if (c == this)
337     throw new IllegalArgumentException();
338     if (maxElements <= 0)
339     return 0;
340 dl 1.21 final ReentrantLock lock = this.lock;
341 dl 1.17 lock.lock();
342     try {
343     int n = 0;
344 jsr166 1.56 for (E e; n < maxElements && (e = peekExpired()) != null;) {
345     c.add(e); // In this order, in case add() throws.
346     q.poll();
347 dl 1.17 ++n;
348     }
349     return n;
350     } finally {
351     lock.unlock();
352     }
353     }
354    
355 dholmes 1.7 /**
356     * Atomically removes all of the elements from this delay queue.
357     * The queue will be empty after this call returns.
358 jsr166 1.32 * Elements with an unexpired delay are not waited for; they are
359     * simply discarded from the queue.
360 dholmes 1.7 */
361 dl 1.2 public void clear() {
362 dl 1.21 final ReentrantLock lock = this.lock;
363 dl 1.2 lock.lock();
364     try {
365     q.clear();
366 tim 1.13 } finally {
367 dl 1.2 lock.unlock();
368     }
369     }
370 tim 1.1
371 dholmes 1.7 /**
372 jsr166 1.61 * Always returns {@code Integer.MAX_VALUE} because
373     * a {@code DelayQueue} is not capacity constrained.
374 jsr166 1.32 *
375 jsr166 1.61 * @return {@code Integer.MAX_VALUE}
376 dholmes 1.7 */
377 dl 1.2 public int remainingCapacity() {
378     return Integer.MAX_VALUE;
379 tim 1.1 }
380 dl 1.2
381 jsr166 1.32 /**
382     * Returns an array containing all of the elements in this queue.
383     * The returned array elements are in no particular order.
384     *
385     * <p>The returned array will be "safe" in that no references to it are
386     * maintained by this queue. (In other words, this method must allocate
387     * a new array). The caller is thus free to modify the returned array.
388 jsr166 1.33 *
389 jsr166 1.32 * <p>This method acts as bridge between array-based and collection-based
390     * APIs.
391     *
392     * @return an array containing all of the elements in this queue
393     */
394 dl 1.2 public Object[] toArray() {
395 dl 1.21 final ReentrantLock lock = this.lock;
396 dl 1.2 lock.lock();
397     try {
398     return q.toArray();
399 tim 1.13 } finally {
400 dl 1.2 lock.unlock();
401     }
402 tim 1.1 }
403 dl 1.2
404 jsr166 1.32 /**
405     * Returns an array containing all of the elements in this queue; the
406     * runtime type of the returned array is that of the specified array.
407     * The returned array elements are in no particular order.
408     * If the queue fits in the specified array, it is returned therein.
409     * Otherwise, a new array is allocated with the runtime type of the
410     * specified array and the size of this queue.
411     *
412     * <p>If this queue fits in the specified array with room to spare
413     * (i.e., the array has more elements than this queue), the element in
414     * the array immediately following the end of the queue is set to
415 jsr166 1.61 * {@code null}.
416 jsr166 1.32 *
417     * <p>Like the {@link #toArray()} method, this method acts as bridge between
418     * array-based and collection-based APIs. Further, this method allows
419     * precise control over the runtime type of the output array, and may,
420     * under certain circumstances, be used to save allocation costs.
421     *
422 jsr166 1.37 * <p>The following code can be used to dump a delay queue into a newly
423 jsr166 1.61 * allocated array of {@code Delayed}:
424 jsr166 1.32 *
425 jsr166 1.55 * <pre> {@code Delayed[] a = q.toArray(new Delayed[0]);}</pre>
426 jsr166 1.32 *
427 jsr166 1.61 * Note that {@code toArray(new Object[0])} is identical in function to
428     * {@code toArray()}.
429 jsr166 1.32 *
430     * @param a the array into which the elements of the queue are to
431     * be stored, if it is big enough; otherwise, a new array of the
432     * same runtime type is allocated for this purpose
433     * @return an array containing all of the elements in this queue
434     * @throws ArrayStoreException if the runtime type of the specified array
435     * is not a supertype of the runtime type of every element in
436     * this queue
437     * @throws NullPointerException if the specified array is null
438     */
439     public <T> T[] toArray(T[] a) {
440 dl 1.21 final ReentrantLock lock = this.lock;
441 dl 1.2 lock.lock();
442     try {
443 jsr166 1.32 return q.toArray(a);
444 tim 1.13 } finally {
445 dl 1.2 lock.unlock();
446     }
447 tim 1.1 }
448    
449 dl 1.26 /**
450     * Removes a single instance of the specified element from this
451 dl 1.36 * queue, if it is present, whether or not it has expired.
452 dl 1.26 */
453 dholmes 1.7 public boolean remove(Object o) {
454 dl 1.21 final ReentrantLock lock = this.lock;
455 dl 1.2 lock.lock();
456     try {
457 dholmes 1.7 return q.remove(o);
458 tim 1.13 } finally {
459 dl 1.2 lock.unlock();
460     }
461     }
462    
463 dholmes 1.7 /**
464 jsr166 1.57 * Identity-based version for use in Itr.remove
465     */
466     void removeEQ(Object o) {
467     final ReentrantLock lock = this.lock;
468     lock.lock();
469     try {
470     for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
471     if (o == it.next()) {
472     it.remove();
473     break;
474     }
475     }
476     } finally {
477     lock.unlock();
478     }
479     }
480    
481     /**
482 dl 1.36 * Returns an iterator over all the elements (both expired and
483 dl 1.44 * unexpired) in this queue. The iterator does not return the
484 jsr166 1.51 * elements in any particular order.
485     *
486 jsr166 1.65 * <p>The returned iterator is
487     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
488 dholmes 1.7 *
489 jsr166 1.32 * @return an iterator over the elements in this queue
490 dholmes 1.7 */
491 dl 1.3 public Iterator<E> iterator() {
492 dl 1.44 return new Itr(toArray());
493 dl 1.2 }
494    
495 dl 1.42 /**
496     * Snapshot iterator that works off copy of underlying q array.
497     */
498 dl 1.44 private class Itr implements Iterator<E> {
499 dl 1.42 final Object[] array; // Array of all elements
500 jsr166 1.57 int cursor; // index of next element to return
501 jsr166 1.49 int lastRet; // index of last element, or -1 if no such
502 jsr166 1.43
503 dl 1.42 Itr(Object[] array) {
504     lastRet = -1;
505     this.array = array;
506 dl 1.2 }
507    
508 tim 1.6 public boolean hasNext() {
509 dl 1.42 return cursor < array.length;
510 tim 1.6 }
511    
512 jsr166 1.49 @SuppressWarnings("unchecked")
513 tim 1.6 public E next() {
514 dl 1.42 if (cursor >= array.length)
515     throw new NoSuchElementException();
516     lastRet = cursor;
517     return (E)array[cursor++];
518 tim 1.6 }
519    
520     public void remove() {
521 jsr166 1.43 if (lastRet < 0)
522 jsr166 1.49 throw new IllegalStateException();
523 jsr166 1.57 removeEQ(array[lastRet]);
524 dl 1.42 lastRet = -1;
525 tim 1.6 }
526 tim 1.1 }
527    
528     }