ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.51
Committed: Fri Nov 19 08:02:09 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.50: +8 -6 lines
Log Message:
make iterator weakly consistent specs more consistent

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