ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.37
Committed: Mon Jul 18 00:25:25 2005 UTC (18 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.36: +4 -4 lines
Log Message:
doc fixes

File Contents

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