ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.47
Committed: Wed Aug 8 16:08:40 2007 UTC (16 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.46: +0 -1 lines
Log Message:
whitespace

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