ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.41
Committed: Fri Sep 23 18:08:35 2005 UTC (18 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.40: +2 -2 lines
Log Message:
hold locks only when necessary

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