ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/DelayQueue.java
Revision: 1.50
Committed: Mon May 19 01:14:25 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.49: +1 -0 lines
Log Message:
Sync with OpenJDK; whitespace

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.locks.*;
10 import java.util.*;
11
12 /**
13 * 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 * past. If no delay has expired there is no head and <tt>poll</tt>
18 * will return <tt>null</tt>. Expiration occurs when an element's
19 * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less
20 * 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 * This queue does not permit null elements.
25 *
26 * <p>This class and its iterator implement all of the
27 * <em>optional</em> methods of the {@link Collection} and {@link
28 * Iterator} interfaces.
29 *
30 * <p>This class is a member of the
31 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
32 * Java Collections Framework</a>.
33 *
34 * @since 1.5
35 * @author Doug Lea
36 * @param <E> the type of elements held in this collection
37 */
38
39 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
40 implements BlockingQueue<E> {
41
42 private transient final ReentrantLock lock = new ReentrantLock();
43 private final PriorityQueue<E> q = new PriorityQueue<E>();
44
45 /**
46 * 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 * Creates a new <tt>DelayQueue</tt> that is initially empty.
72 */
73 public DelayQueue() {}
74
75 /**
76 * Creates a <tt>DelayQueue</tt> initially containing the elements of the
77 * given collection of {@link Delayed} instances.
78 *
79 * @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 */
83 public DelayQueue(Collection<? extends E> c) {
84 this.addAll(c);
85 }
86
87 /**
88 * Inserts the specified element into this delay queue.
89 *
90 * @param e the element to add
91 * @return <tt>true</tt> (as specified by {@link Collection#add})
92 * @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 * @return <tt>true</tt>
103 * @throws NullPointerException if the specified element is null
104 */
105 public boolean offer(E e) {
106 final ReentrantLock lock = this.lock;
107 lock.lock();
108 try {
109 q.offer(e);
110 if (q.peek() == e) {
111 leader = null;
112 available.signal();
113 }
114 return true;
115 } finally {
116 lock.unlock();
117 }
118 }
119
120 /**
121 * Inserts the specified element into this delay queue. As the queue is
122 * unbounded this method will never block.
123 *
124 * @param e the element to add
125 * @throws NullPointerException {@inheritDoc}
126 */
127 public void put(E e) {
128 offer(e);
129 }
130
131 /**
132 * Inserts the specified element into this delay queue. As the queue is
133 * unbounded this method will never block.
134 *
135 * @param e the element to add
136 * @param timeout This parameter is ignored as the method never blocks
137 * @param unit This parameter is ignored as the method never blocks
138 * @return <tt>true</tt>
139 * @throws NullPointerException {@inheritDoc}
140 */
141 public boolean offer(E e, long timeout, TimeUnit unit) {
142 return offer(e);
143 }
144
145 /**
146 * 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 *
149 * @return the head of this queue, or <tt>null</tt> if this
150 * queue has no elements with an expired delay
151 */
152 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 else
160 return q.poll();
161 } finally {
162 lock.unlock();
163 }
164 }
165
166 /**
167 * 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 * @return the head of this queue
171 * @throws InterruptedException {@inheritDoc}
172 */
173 public E take() throws InterruptedException {
174 final ReentrantLock lock = this.lock;
175 lock.lockInterruptibly();
176 try {
177 for (;;) {
178 E first = q.peek();
179 if (first == null)
180 available.await();
181 else {
182 long delay = first.getDelay(TimeUnit.NANOSECONDS);
183 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 }
197 }
198 }
199 } finally {
200 if (leader == null && q.peek() != null)
201 available.signal();
202 lock.unlock();
203 }
204 }
205
206 /**
207 * 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 * @return the head of this queue, or <tt>null</tt> if the
212 * specified waiting time elapses before an element with
213 * an expired delay becomes available
214 * @throws InterruptedException {@inheritDoc}
215 */
216 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
217 long nanos = unit.toNanos(timeout);
218 final ReentrantLock lock = this.lock;
219 lock.lockInterruptibly();
220 try {
221 for (;;) {
222 E first = q.peek();
223 if (first == null) {
224 if (nanos <= 0)
225 return null;
226 else
227 nanos = available.awaitNanos(nanos);
228 } else {
229 long delay = first.getDelay(TimeUnit.NANOSECONDS);
230 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 }
248 }
249 } finally {
250 if (leader == null && q.peek() != null)
251 available.signal();
252 lock.unlock();
253 }
254 }
255
256 /**
257 * 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 *
263 * @return the head of this queue, or <tt>null</tt> if this
264 * queue is empty.
265 */
266 public E peek() {
267 final ReentrantLock lock = this.lock;
268 lock.lock();
269 try {
270 return q.peek();
271 } finally {
272 lock.unlock();
273 }
274 }
275
276 public int size() {
277 final ReentrantLock lock = this.lock;
278 lock.lock();
279 try {
280 return q.size();
281 } finally {
282 lock.unlock();
283 }
284 }
285
286 /**
287 * @throws UnsupportedOperationException {@inheritDoc}
288 * @throws ClassCastException {@inheritDoc}
289 * @throws NullPointerException {@inheritDoc}
290 * @throws IllegalArgumentException {@inheritDoc}
291 */
292 public int drainTo(Collection<? super E> c) {
293 if (c == null)
294 throw new NullPointerException();
295 if (c == this)
296 throw new IllegalArgumentException();
297 final ReentrantLock lock = this.lock;
298 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 /**
315 * @throws UnsupportedOperationException {@inheritDoc}
316 * @throws ClassCastException {@inheritDoc}
317 * @throws NullPointerException {@inheritDoc}
318 * @throws IllegalArgumentException {@inheritDoc}
319 */
320 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 final ReentrantLock lock = this.lock;
328 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 /**
345 * Atomically removes all of the elements from this delay queue.
346 * The queue will be empty after this call returns.
347 * Elements with an unexpired delay are not waited for; they are
348 * simply discarded from the queue.
349 */
350 public void clear() {
351 final ReentrantLock lock = this.lock;
352 lock.lock();
353 try {
354 q.clear();
355 } finally {
356 lock.unlock();
357 }
358 }
359
360 /**
361 * Always returns <tt>Integer.MAX_VALUE</tt> because
362 * a <tt>DelayQueue</tt> is not capacity constrained.
363 *
364 * @return <tt>Integer.MAX_VALUE</tt>
365 */
366 public int remainingCapacity() {
367 return Integer.MAX_VALUE;
368 }
369
370 /**
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 *
378 * <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 public Object[] toArray() {
384 final ReentrantLock lock = this.lock;
385 lock.lock();
386 try {
387 return q.toArray();
388 } finally {
389 lock.unlock();
390 }
391 }
392
393 /**
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 * <p>The following code can be used to dump a delay queue into a newly
412 * allocated array of <tt>Delayed</tt>:
413 *
414 * <pre>
415 * Delayed[] a = q.toArray(new Delayed[0]);</pre>
416 *
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 final ReentrantLock lock = this.lock;
431 lock.lock();
432 try {
433 return q.toArray(a);
434 } finally {
435 lock.unlock();
436 }
437 }
438
439 /**
440 * Removes a single instance of the specified element from this
441 * queue, if it is present, whether or not it has expired.
442 */
443 public boolean remove(Object o) {
444 final ReentrantLock lock = this.lock;
445 lock.lock();
446 try {
447 return q.remove(o);
448 } finally {
449 lock.unlock();
450 }
451 }
452
453 /**
454 * Returns an iterator over all the elements (both expired and
455 * unexpired) in this queue. The iterator does not return the
456 * elements in any particular order. The returned
457 * <tt>Iterator</tt> is a "weakly consistent" iterator that will
458 * never throw {@link ConcurrentModificationException}, and
459 * guarantees to traverse elements as they existed upon
460 * construction of the iterator, and may (but is not guaranteed
461 * to) reflect any modifications subsequent to construction.
462 *
463 * @return an iterator over the elements in this queue
464 */
465 public Iterator<E> iterator() {
466 return new Itr(toArray());
467 }
468
469 /**
470 * Snapshot iterator that works off copy of underlying q array.
471 */
472 private class Itr implements Iterator<E> {
473 final Object[] array; // Array of all elements
474 int cursor; // index of next element to return;
475 int lastRet; // index of last element, or -1 if no such
476
477 Itr(Object[] array) {
478 lastRet = -1;
479 this.array = array;
480 }
481
482 public boolean hasNext() {
483 return cursor < array.length;
484 }
485
486 @SuppressWarnings("unchecked")
487 public E next() {
488 if (cursor >= array.length)
489 throw new NoSuchElementException();
490 lastRet = cursor;
491 return (E)array[cursor++];
492 }
493
494 public void remove() {
495 if (lastRet < 0)
496 throw new IllegalStateException();
497 Object x = array[lastRet];
498 lastRet = -1;
499 // Traverse underlying queue to find == element,
500 // not just a .equals element.
501 lock.lock();
502 try {
503 for (Iterator it = q.iterator(); it.hasNext(); ) {
504 if (it.next() == x) {
505 it.remove();
506 return;
507 }
508 }
509 } finally {
510 lock.unlock();
511 }
512 }
513 }
514
515 }