ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.39
Committed: Sat Aug 20 07:41:47 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.38: +1 -2 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 null elements.
26 *
27 * <p>This class and its iterator implement all of the
28 * <em>optional</em> methods of the {@link Collection} and {@link
29 * Iterator} interfaces.
30 *
31 * <p>This class is a member of the
32 * <a href="{@docRoot}/../guide/collections/index.html">
33 * Java Collections Framework</a>.
34 *
35 * @since 1.5
36 * @author Doug Lea
37 * @param <E> the type of elements held in this collection
38 */
39
40 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
41 implements BlockingQueue<E> {
42
43 private transient final ReentrantLock lock = new ReentrantLock();
44 private transient final Condition available = lock.newCondition();
45 private final PriorityQueue<E> q = new PriorityQueue<E>();
46
47 /**
48 * Creates a new <tt>DelayQueue</tt> that is initially empty.
49 */
50 public DelayQueue() {}
51
52 /**
53 * Creates a <tt>DelayQueue</tt> initially containing the elements of the
54 * given collection of {@link Delayed} instances.
55 *
56 * @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 */
60 public DelayQueue(Collection<? extends E> c) {
61 this.addAll(c);
62 }
63
64 /**
65 * Inserts the specified element into this delay queue.
66 *
67 * @param e the element to add
68 * @return <tt>true</tt> (as specified by {@link Collection#add})
69 * @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 * @return <tt>true</tt>
80 * @throws NullPointerException if the specified element is null
81 */
82 public boolean offer(E e) {
83 final ReentrantLock lock = this.lock;
84 lock.lock();
85 try {
86 E first = q.peek();
87 q.offer(e);
88 if (first == null || e.compareTo(first) < 0)
89 available.signalAll();
90 return true;
91 } finally {
92 lock.unlock();
93 }
94 }
95
96 /**
97 * Inserts the specified element into this delay queue. As the queue is
98 * unbounded this method will never block.
99 *
100 * @param e the element to add
101 * @throws NullPointerException {@inheritDoc}
102 */
103 public void put(E e) {
104 offer(e);
105 }
106
107 /**
108 * Inserts the specified element into this delay queue. As the queue is
109 * unbounded this method will never block.
110 *
111 * @param e the element to add
112 * @param timeout This parameter is ignored as the method never blocks
113 * @param unit This parameter is ignored as the method never blocks
114 * @return <tt>true</tt>
115 * @throws NullPointerException {@inheritDoc}
116 */
117 public boolean offer(E e, long timeout, TimeUnit unit) {
118 return offer(e);
119 }
120
121 /**
122 * 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 *
125 * @return the head of this queue, or <tt>null</tt> if this
126 * queue has no elements with an expired delay
127 */
128 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 }
146
147 /**
148 * 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 * @return the head of this queue
152 * @throws InterruptedException {@inheritDoc}
153 */
154 public E take() throws InterruptedException {
155 final ReentrantLock lock = this.lock;
156 lock.lockInterruptibly();
157 try {
158 for (;;) {
159 E first = q.peek();
160 if (first == null) {
161 available.await();
162 } else {
163 long delay = first.getDelay(TimeUnit.NANOSECONDS);
164 if (delay > 0) {
165 long tl = available.awaitNanos(delay);
166 } else {
167 E x = q.poll();
168 assert x != null;
169 if (q.size() != 0)
170 available.signalAll(); // wake up other takers
171 return x;
172
173 }
174 }
175 }
176 } finally {
177 lock.unlock();
178 }
179 }
180
181 /**
182 * 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 * @return the head of this queue, or <tt>null</tt> if the
187 * specified waiting time elapses before an element with
188 * an expired delay becomes available
189 * @throws InterruptedException {@inheritDoc}
190 */
191 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
192 final ReentrantLock lock = this.lock;
193 lock.lockInterruptibly();
194 long nanos = unit.toNanos(timeout);
195 try {
196 for (;;) {
197 E first = q.peek();
198 if (first == null) {
199 if (nanos <= 0)
200 return null;
201 else
202 nanos = available.awaitNanos(nanos);
203 } else {
204 long delay = first.getDelay(TimeUnit.NANOSECONDS);
205 if (delay > 0) {
206 if (delay > nanos)
207 delay = nanos;
208 long timeLeft = available.awaitNanos(delay);
209 nanos -= delay - timeLeft;
210 } else {
211 E x = q.poll();
212 assert x != null;
213 if (q.size() != 0)
214 available.signalAll();
215 return x;
216 }
217 }
218 }
219 } finally {
220 lock.unlock();
221 }
222 }
223
224 /**
225 * 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 *
231 * @return the head of this queue, or <tt>null</tt> if this
232 * queue is empty.
233 */
234 public E peek() {
235 final ReentrantLock lock = this.lock;
236 lock.lock();
237 try {
238 return q.peek();
239 } finally {
240 lock.unlock();
241 }
242 }
243
244 public int size() {
245 final ReentrantLock lock = this.lock;
246 lock.lock();
247 try {
248 return q.size();
249 } finally {
250 lock.unlock();
251 }
252 }
253
254 /**
255 * @throws UnsupportedOperationException {@inheritDoc}
256 * @throws ClassCastException {@inheritDoc}
257 * @throws NullPointerException {@inheritDoc}
258 * @throws IllegalArgumentException {@inheritDoc}
259 */
260 public int drainTo(Collection<? super E> c) {
261 if (c == null)
262 throw new NullPointerException();
263 if (c == this)
264 throw new IllegalArgumentException();
265 final ReentrantLock lock = this.lock;
266 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 /**
285 * @throws UnsupportedOperationException {@inheritDoc}
286 * @throws ClassCastException {@inheritDoc}
287 * @throws NullPointerException {@inheritDoc}
288 * @throws IllegalArgumentException {@inheritDoc}
289 */
290 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 final ReentrantLock lock = this.lock;
298 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 /**
317 * Atomically removes all of the elements from this delay queue.
318 * The queue will be empty after this call returns.
319 * Elements with an unexpired delay are not waited for; they are
320 * simply discarded from the queue.
321 */
322 public void clear() {
323 final ReentrantLock lock = this.lock;
324 lock.lock();
325 try {
326 q.clear();
327 } finally {
328 lock.unlock();
329 }
330 }
331
332 /**
333 * Always returns <tt>Integer.MAX_VALUE</tt> because
334 * a <tt>DelayQueue</tt> is not capacity constrained.
335 *
336 * @return <tt>Integer.MAX_VALUE</tt>
337 */
338 public int remainingCapacity() {
339 return Integer.MAX_VALUE;
340 }
341
342 /**
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 *
350 * <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 public Object[] toArray() {
356 final ReentrantLock lock = this.lock;
357 lock.lock();
358 try {
359 return q.toArray();
360 } finally {
361 lock.unlock();
362 }
363 }
364
365 /**
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 * <p>The following code can be used to dump a delay queue into a newly
384 * allocated array of <tt>Delayed</tt>:
385 *
386 * <pre>
387 * Delayed[] a = q.toArray(new Delayed[0]);</pre>
388 *
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 final ReentrantLock lock = this.lock;
403 lock.lock();
404 try {
405 return q.toArray(a);
406 } finally {
407 lock.unlock();
408 }
409 }
410
411 /**
412 * Removes a single instance of the specified element from this
413 * queue, if it is present, whether or not it has expired.
414 */
415 public boolean remove(Object o) {
416 final ReentrantLock lock = this.lock;
417 lock.lock();
418 try {
419 return q.remove(o);
420 } finally {
421 lock.unlock();
422 }
423 }
424
425 /**
426 * Returns an iterator over all the elements (both expired and
427 * unexpired) in this queue. The iterator does not
428 * return the elements in any particular order. The returned
429 * iterator is a thread-safe "fast-fail" iterator that will throw
430 * {@link ConcurrentModificationException} upon detected
431 * interference.
432 *
433 * @return an iterator over the elements in this queue
434 */
435 public Iterator<E> iterator() {
436 final ReentrantLock lock = this.lock;
437 lock.lock();
438 try {
439 return new Itr<E>(q.iterator());
440 } finally {
441 lock.unlock();
442 }
443 }
444
445 private class Itr<E> implements Iterator<E> {
446 private final Iterator<E> iter;
447 Itr(Iterator<E> i) {
448 iter = i;
449 }
450
451 public boolean hasNext() {
452 return iter.hasNext();
453 }
454
455 public E next() {
456 final ReentrantLock lock = DelayQueue.this.lock;
457 lock.lock();
458 try {
459 return iter.next();
460 } finally {
461 lock.unlock();
462 }
463 }
464
465 public void remove() {
466 final ReentrantLock lock = DelayQueue.this.lock;
467 lock.lock();
468 try {
469 iter.remove();
470 } finally {
471 lock.unlock();
472 }
473 }
474 }
475
476 }