ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.85
Committed: Sun Jun 17 11:13:21 2012 UTC (11 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.84: +30 -26 lines
Log Message:
Guard siftDown to avoid unnecessary item retention

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/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.util.concurrent.locks.Condition;
10 import java.util.concurrent.locks.ReentrantLock;
11 import java.util.*;
12
13 /**
14 * An unbounded {@linkplain BlockingQueue blocking queue} that uses
15 * the same ordering rules as class {@link PriorityQueue} and supplies
16 * blocking retrieval operations. While this queue is logically
17 * unbounded, attempted additions may fail due to resource exhaustion
18 * (causing {@code OutOfMemoryError}). This class does not permit
19 * {@code null} elements. A priority queue relying on {@linkplain
20 * Comparable natural ordering} also does not permit insertion of
21 * non-comparable objects (doing so results in
22 * {@code ClassCastException}).
23 *
24 * <p>This class and its iterator implement all of the
25 * <em>optional</em> methods of the {@link Collection} and {@link
26 * Iterator} interfaces. The Iterator provided in method {@link
27 * #iterator()} is <em>not</em> guaranteed to traverse the elements of
28 * the PriorityBlockingQueue in any particular order. If you need
29 * ordered traversal, consider using
30 * {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo}
31 * can be used to <em>remove</em> some or all elements in priority
32 * order and place them in another collection.
33 *
34 * <p>Operations on this class make no guarantees about the ordering
35 * of elements with equal priority. If you need to enforce an
36 * ordering, you can define custom classes or comparators that use a
37 * secondary key to break ties in primary priority values. For
38 * example, here is a class that applies first-in-first-out
39 * tie-breaking to comparable elements. To use it, you would insert a
40 * {@code new FIFOEntry(anEntry)} instead of a plain entry object.
41 *
42 * <pre> {@code
43 * class FIFOEntry<E extends Comparable<? super E>>
44 * implements Comparable<FIFOEntry<E>> {
45 * static final AtomicLong seq = new AtomicLong(0);
46 * final long seqNum;
47 * final E entry;
48 * public FIFOEntry(E entry) {
49 * seqNum = seq.getAndIncrement();
50 * this.entry = entry;
51 * }
52 * public E getEntry() { return entry; }
53 * public int compareTo(FIFOEntry<E> other) {
54 * int res = entry.compareTo(other.entry);
55 * if (res == 0 && other.entry != this.entry)
56 * res = (seqNum < other.seqNum ? -1 : 1);
57 * return res;
58 * }
59 * }}</pre>
60 *
61 * <p>This class is a member of the
62 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
63 * Java Collections Framework</a>.
64 *
65 * @since 1.5
66 * @author Doug Lea
67 * @param <E> the type of elements held in this collection
68 */
69 @SuppressWarnings("unchecked")
70 public class PriorityBlockingQueue<E> extends AbstractQueue<E>
71 implements BlockingQueue<E>, java.io.Serializable {
72 private static final long serialVersionUID = 5595510919245408276L;
73
74 /*
75 * The implementation uses an array-based binary heap, with public
76 * operations protected with a single lock. However, allocation
77 * during resizing uses a simple spinlock (used only while not
78 * holding main lock) in order to allow takes to operate
79 * concurrently with allocation. This avoids repeated
80 * postponement of waiting consumers and consequent element
81 * build-up. The need to back away from lock during allocation
82 * makes it impossible to simply wrap delegated
83 * java.util.PriorityQueue operations within a lock, as was done
84 * in a previous version of this class. To maintain
85 * interoperability, a plain PriorityQueue is still used during
86 * serialization, which maintains compatibility at the expense of
87 * transiently doubling overhead.
88 */
89
90 /**
91 * Default array capacity.
92 */
93 private static final int DEFAULT_INITIAL_CAPACITY = 11;
94
95 /**
96 * The maximum size of array to allocate.
97 * Some VMs reserve some header words in an array.
98 * Attempts to allocate larger arrays may result in
99 * OutOfMemoryError: Requested array size exceeds VM limit
100 */
101 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
102
103 /**
104 * Priority queue represented as a balanced binary heap: the two
105 * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
106 * priority queue is ordered by comparator, or by the elements'
107 * natural ordering, if comparator is null: For each node n in the
108 * heap and each descendant d of n, n <= d. The element with the
109 * lowest value is in queue[0], assuming the queue is nonempty.
110 */
111 private transient Object[] queue;
112
113 /**
114 * The number of elements in the priority queue.
115 */
116 private transient int size;
117
118 /**
119 * The comparator, or null if priority queue uses elements'
120 * natural ordering.
121 */
122 private transient Comparator<? super E> comparator;
123
124 /**
125 * Lock used for all public operations
126 */
127 private final ReentrantLock lock;
128
129 /**
130 * Condition for blocking when empty
131 */
132 private final Condition notEmpty;
133
134 /**
135 * Spinlock for allocation, acquired via CAS.
136 */
137 private transient volatile int allocationSpinLock;
138
139 /**
140 * A plain PriorityQueue used only for serialization,
141 * to maintain compatibility with previous versions
142 * of this class. Non-null only during serialization/deserialization.
143 */
144 private PriorityQueue<E> q;
145
146 /**
147 * Creates a {@code PriorityBlockingQueue} with the default
148 * initial capacity (11) that orders its elements according to
149 * their {@linkplain Comparable natural ordering}.
150 */
151 public PriorityBlockingQueue() {
152 this(DEFAULT_INITIAL_CAPACITY, null);
153 }
154
155 /**
156 * Creates a {@code PriorityBlockingQueue} with the specified
157 * initial capacity that orders its elements according to their
158 * {@linkplain Comparable natural ordering}.
159 *
160 * @param initialCapacity the initial capacity for this priority queue
161 * @throws IllegalArgumentException if {@code initialCapacity} is less
162 * than 1
163 */
164 public PriorityBlockingQueue(int initialCapacity) {
165 this(initialCapacity, null);
166 }
167
168 /**
169 * Creates a {@code PriorityBlockingQueue} with the specified initial
170 * capacity that orders its elements according to the specified
171 * comparator.
172 *
173 * @param initialCapacity the initial capacity for this priority queue
174 * @param comparator the comparator that will be used to order this
175 * priority queue. If {@code null}, the {@linkplain Comparable
176 * natural ordering} of the elements will be used.
177 * @throws IllegalArgumentException if {@code initialCapacity} is less
178 * than 1
179 */
180 public PriorityBlockingQueue(int initialCapacity,
181 Comparator<? super E> comparator) {
182 if (initialCapacity < 1)
183 throw new IllegalArgumentException();
184 this.lock = new ReentrantLock();
185 this.notEmpty = lock.newCondition();
186 this.comparator = comparator;
187 this.queue = new Object[initialCapacity];
188 }
189
190 /**
191 * Creates a {@code PriorityBlockingQueue} containing the elements
192 * in the specified collection. If the specified collection is a
193 * {@link SortedSet} or a {@link PriorityQueue}, this
194 * priority queue will be ordered according to the same ordering.
195 * Otherwise, this priority queue will be ordered according to the
196 * {@linkplain Comparable natural ordering} of its elements.
197 *
198 * @param c the collection whose elements are to be placed
199 * into this priority queue
200 * @throws ClassCastException if elements of the specified collection
201 * cannot be compared to one another according to the priority
202 * queue's ordering
203 * @throws NullPointerException if the specified collection or any
204 * of its elements are null
205 */
206 public PriorityBlockingQueue(Collection<? extends E> c) {
207 this.lock = new ReentrantLock();
208 this.notEmpty = lock.newCondition();
209 boolean heapify = true; // true if not known to be in heap order
210 boolean screen = true; // true if must screen for nulls
211 if (c instanceof SortedSet<?>) {
212 SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
213 this.comparator = (Comparator<? super E>) ss.comparator();
214 heapify = false;
215 }
216 else if (c instanceof PriorityBlockingQueue<?>) {
217 PriorityBlockingQueue<? extends E> pq =
218 (PriorityBlockingQueue<? extends E>) c;
219 this.comparator = (Comparator<? super E>) pq.comparator();
220 screen = false;
221 if (pq.getClass() == PriorityBlockingQueue.class) // exact match
222 heapify = false;
223 }
224 Object[] a = c.toArray();
225 int n = a.length;
226 // If c.toArray incorrectly doesn't return Object[], copy it.
227 if (a.getClass() != Object[].class)
228 a = Arrays.copyOf(a, n, Object[].class);
229 if (screen && (n == 1 || this.comparator != null)) {
230 for (int i = 0; i < n; ++i)
231 if (a[i] == null)
232 throw new NullPointerException();
233 }
234 this.queue = a;
235 this.size = n;
236 if (heapify)
237 heapify();
238 }
239
240 /**
241 * Tries to grow array to accommodate at least one more element
242 * (but normally expand by about 50%), giving up (allowing retry)
243 * on contention (which we expect to be rare). Call only while
244 * holding lock.
245 *
246 * @param array the heap array
247 * @param oldCap the length of the array
248 */
249 private void tryGrow(Object[] array, int oldCap) {
250 lock.unlock(); // must release and then re-acquire main lock
251 Object[] newArray = null;
252 if (allocationSpinLock == 0 &&
253 UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
254 0, 1)) {
255 try {
256 int newCap = oldCap + ((oldCap < 64) ?
257 (oldCap + 2) : // grow faster if small
258 (oldCap >> 1));
259 if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
260 int minCap = oldCap + 1;
261 if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
262 throw new OutOfMemoryError();
263 newCap = MAX_ARRAY_SIZE;
264 }
265 if (newCap > oldCap && queue == array)
266 newArray = new Object[newCap];
267 } finally {
268 allocationSpinLock = 0;
269 }
270 }
271 if (newArray == null) // back off if another thread is allocating
272 Thread.yield();
273 lock.lock();
274 if (newArray != null && queue == array) {
275 queue = newArray;
276 System.arraycopy(array, 0, newArray, 0, oldCap);
277 }
278 }
279
280 /**
281 * Mechanics for poll(). Call only while holding lock.
282 */
283 private E dequeue() {
284 int n = size - 1;
285 if (n < 0)
286 return null;
287 else {
288 Object[] array = queue;
289 E result = (E) array[0];
290 E x = (E) array[n];
291 array[n] = null;
292 Comparator<? super E> cmp = comparator;
293 if (cmp == null)
294 siftDownComparable(0, x, array, n);
295 else
296 siftDownUsingComparator(0, x, array, n, cmp);
297 size = n;
298 return result;
299 }
300 }
301
302 /**
303 * Inserts item x at position k, maintaining heap invariant by
304 * promoting x up the tree until it is greater than or equal to
305 * its parent, or is the root.
306 *
307 * To simplify and speed up coercions and comparisons. the
308 * Comparable and Comparator versions are separated into different
309 * methods that are otherwise identical. (Similarly for siftDown.)
310 * These methods are static, with heap state as arguments, to
311 * simplify use in light of possible comparator exceptions.
312 *
313 * @param k the position to fill
314 * @param x the item to insert
315 * @param array the heap array
316 * @param n heap size
317 */
318 private static <T> void siftUpComparable(int k, T x, Object[] array) {
319 Comparable<? super T> key = (Comparable<? super T>) x;
320 while (k > 0) {
321 int parent = (k - 1) >>> 1;
322 Object e = array[parent];
323 if (key.compareTo((T) e) >= 0)
324 break;
325 array[k] = e;
326 k = parent;
327 }
328 array[k] = key;
329 }
330
331 private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
332 Comparator<? super T> cmp) {
333 while (k > 0) {
334 int parent = (k - 1) >>> 1;
335 Object e = array[parent];
336 if (cmp.compare(x, (T) e) >= 0)
337 break;
338 array[k] = e;
339 k = parent;
340 }
341 array[k] = x;
342 }
343
344 /**
345 * Inserts item x at position k, maintaining heap invariant by
346 * demoting x down the tree repeatedly until it is less than or
347 * equal to its children or is a leaf.
348 *
349 * @param k the position to fill
350 * @param x the item to insert
351 * @param array the heap array
352 * @param n heap size
353 */
354 private static <T> void siftDownComparable(int k, T x, Object[] array,
355 int n) {
356 if (n > 0) {
357 Comparable<? super T> key = (Comparable<? super T>)x;
358 int half = n >>> 1; // loop while a non-leaf
359 while (k < half) {
360 int child = (k << 1) + 1; // assume left child is least
361 Object c = array[child];
362 int right = child + 1;
363 if (right < n &&
364 ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
365 c = array[child = right];
366 if (key.compareTo((T) c) <= 0)
367 break;
368 array[k] = c;
369 k = child;
370 }
371 array[k] = key;
372 }
373 }
374
375 private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
376 int n,
377 Comparator<? super T> cmp) {
378 if (n > 0) {
379 int half = n >>> 1;
380 while (k < half) {
381 int child = (k << 1) + 1;
382 Object c = array[child];
383 int right = child + 1;
384 if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
385 c = array[child = right];
386 if (cmp.compare(x, (T) c) <= 0)
387 break;
388 array[k] = c;
389 k = child;
390 }
391 array[k] = x;
392 }
393 }
394
395 /**
396 * Establishes the heap invariant (described above) in the entire tree,
397 * assuming nothing about the order of the elements prior to the call.
398 */
399 private void heapify() {
400 Object[] array = queue;
401 int n = size;
402 int half = (n >>> 1) - 1;
403 Comparator<? super E> cmp = comparator;
404 if (cmp == null) {
405 for (int i = half; i >= 0; i--)
406 siftDownComparable(i, (E) array[i], array, n);
407 }
408 else {
409 for (int i = half; i >= 0; i--)
410 siftDownUsingComparator(i, (E) array[i], array, n, cmp);
411 }
412 }
413
414 /**
415 * Inserts the specified element into this priority queue.
416 *
417 * @param e the element to add
418 * @return {@code true} (as specified by {@link Collection#add})
419 * @throws ClassCastException if the specified element cannot be compared
420 * with elements currently in the priority queue according to the
421 * priority queue's ordering
422 * @throws NullPointerException if the specified element is null
423 */
424 public boolean add(E e) {
425 return offer(e);
426 }
427
428 /**
429 * Inserts the specified element into this priority queue.
430 * As the queue is unbounded, this method will never return {@code false}.
431 *
432 * @param e the element to add
433 * @return {@code true} (as specified by {@link Queue#offer})
434 * @throws ClassCastException if the specified element cannot be compared
435 * with elements currently in the priority queue according to the
436 * priority queue's ordering
437 * @throws NullPointerException if the specified element is null
438 */
439 public boolean offer(E e) {
440 if (e == null)
441 throw new NullPointerException();
442 final ReentrantLock lock = this.lock;
443 lock.lock();
444 int n, cap;
445 Object[] array;
446 while ((n = size) >= (cap = (array = queue).length))
447 tryGrow(array, cap);
448 try {
449 Comparator<? super E> cmp = comparator;
450 if (cmp == null)
451 siftUpComparable(n, e, array);
452 else
453 siftUpUsingComparator(n, e, array, cmp);
454 size = n + 1;
455 notEmpty.signal();
456 } finally {
457 lock.unlock();
458 }
459 return true;
460 }
461
462 /**
463 * Inserts the specified element into this priority queue.
464 * As the queue is unbounded, this method will never block.
465 *
466 * @param e the element to add
467 * @throws ClassCastException if the specified element cannot be compared
468 * with elements currently in the priority queue according to the
469 * priority queue's ordering
470 * @throws NullPointerException if the specified element is null
471 */
472 public void put(E e) {
473 offer(e); // never need to block
474 }
475
476 /**
477 * Inserts the specified element into this priority queue.
478 * As the queue is unbounded, this method will never block or
479 * return {@code false}.
480 *
481 * @param e the element to add
482 * @param timeout This parameter is ignored as the method never blocks
483 * @param unit This parameter is ignored as the method never blocks
484 * @return {@code true} (as specified by
485 * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
486 * @throws ClassCastException if the specified element cannot be compared
487 * with elements currently in the priority queue according to the
488 * priority queue's ordering
489 * @throws NullPointerException if the specified element is null
490 */
491 public boolean offer(E e, long timeout, TimeUnit unit) {
492 return offer(e); // never need to block
493 }
494
495 public E poll() {
496 final ReentrantLock lock = this.lock;
497 lock.lock();
498 try {
499 return dequeue();
500 } finally {
501 lock.unlock();
502 }
503 }
504
505 public E take() throws InterruptedException {
506 final ReentrantLock lock = this.lock;
507 lock.lockInterruptibly();
508 E result;
509 try {
510 while ( (result = dequeue()) == null)
511 notEmpty.await();
512 } finally {
513 lock.unlock();
514 }
515 return result;
516 }
517
518 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
519 long nanos = unit.toNanos(timeout);
520 final ReentrantLock lock = this.lock;
521 lock.lockInterruptibly();
522 E result;
523 try {
524 while ( (result = dequeue()) == null && nanos > 0)
525 nanos = notEmpty.awaitNanos(nanos);
526 } finally {
527 lock.unlock();
528 }
529 return result;
530 }
531
532 public E peek() {
533 final ReentrantLock lock = this.lock;
534 lock.lock();
535 try {
536 return (size == 0) ? null : (E) queue[0];
537 } finally {
538 lock.unlock();
539 }
540 }
541
542 /**
543 * Returns the comparator used to order the elements in this queue,
544 * or {@code null} if this queue uses the {@linkplain Comparable
545 * natural ordering} of its elements.
546 *
547 * @return the comparator used to order the elements in this queue,
548 * or {@code null} if this queue uses the natural
549 * ordering of its elements
550 */
551 public Comparator<? super E> comparator() {
552 return comparator;
553 }
554
555 public int size() {
556 final ReentrantLock lock = this.lock;
557 lock.lock();
558 try {
559 return size;
560 } finally {
561 lock.unlock();
562 }
563 }
564
565 /**
566 * Always returns {@code Integer.MAX_VALUE} because
567 * a {@code PriorityBlockingQueue} is not capacity constrained.
568 * @return {@code Integer.MAX_VALUE} always
569 */
570 public int remainingCapacity() {
571 return Integer.MAX_VALUE;
572 }
573
574 private int indexOf(Object o) {
575 if (o != null) {
576 Object[] array = queue;
577 int n = size;
578 for (int i = 0; i < n; i++)
579 if (o.equals(array[i]))
580 return i;
581 }
582 return -1;
583 }
584
585 /**
586 * Removes the ith element from queue.
587 */
588 private void removeAt(int i) {
589 Object[] array = queue;
590 int n = size - 1;
591 if (n == i) // removed last element
592 array[i] = null;
593 else {
594 E moved = (E) array[n];
595 array[n] = null;
596 Comparator<? super E> cmp = comparator;
597 if (cmp == null)
598 siftDownComparable(i, moved, array, n);
599 else
600 siftDownUsingComparator(i, moved, array, n, cmp);
601 if (array[i] == moved) {
602 if (cmp == null)
603 siftUpComparable(i, moved, array);
604 else
605 siftUpUsingComparator(i, moved, array, cmp);
606 }
607 }
608 size = n;
609 }
610
611 /**
612 * Removes a single instance of the specified element from this queue,
613 * if it is present. More formally, removes an element {@code e} such
614 * that {@code o.equals(e)}, if this queue contains one or more such
615 * elements. Returns {@code true} if and only if this queue contained
616 * the specified element (or equivalently, if this queue changed as a
617 * result of the call).
618 *
619 * @param o element to be removed from this queue, if present
620 * @return {@code true} if this queue changed as a result of the call
621 */
622 public boolean remove(Object o) {
623 final ReentrantLock lock = this.lock;
624 lock.lock();
625 try {
626 int i = indexOf(o);
627 if (i == -1)
628 return false;
629 removeAt(i);
630 return true;
631 } finally {
632 lock.unlock();
633 }
634 }
635
636 /**
637 * Identity-based version for use in Itr.remove
638 */
639 void removeEQ(Object o) {
640 final ReentrantLock lock = this.lock;
641 lock.lock();
642 try {
643 Object[] array = queue;
644 for (int i = 0, n = size; i < n; i++) {
645 if (o == array[i]) {
646 removeAt(i);
647 break;
648 }
649 }
650 } finally {
651 lock.unlock();
652 }
653 }
654
655 /**
656 * Returns {@code true} if this queue contains the specified element.
657 * More formally, returns {@code true} if and only if this queue contains
658 * at least one element {@code e} such that {@code o.equals(e)}.
659 *
660 * @param o object to be checked for containment in this queue
661 * @return {@code true} if this queue contains the specified element
662 */
663 public boolean contains(Object o) {
664 final ReentrantLock lock = this.lock;
665 lock.lock();
666 try {
667 return indexOf(o) != -1;
668 } finally {
669 lock.unlock();
670 }
671 }
672
673 /**
674 * Returns an array containing all of the elements in this queue.
675 * The returned array elements are in no particular order.
676 *
677 * <p>The returned array will be "safe" in that no references to it are
678 * maintained by this queue. (In other words, this method must allocate
679 * a new array). The caller is thus free to modify the returned array.
680 *
681 * <p>This method acts as bridge between array-based and collection-based
682 * APIs.
683 *
684 * @return an array containing all of the elements in this queue
685 */
686 public Object[] toArray() {
687 final ReentrantLock lock = this.lock;
688 lock.lock();
689 try {
690 return Arrays.copyOf(queue, size);
691 } finally {
692 lock.unlock();
693 }
694 }
695
696 public String toString() {
697 final ReentrantLock lock = this.lock;
698 lock.lock();
699 try {
700 int n = size;
701 if (n == 0)
702 return "[]";
703 StringBuilder sb = new StringBuilder();
704 sb.append('[');
705 for (int i = 0; i < n; ++i) {
706 Object e = queue[i];
707 sb.append(e == this ? "(this Collection)" : e);
708 if (i != n - 1)
709 sb.append(',').append(' ');
710 }
711 return sb.append(']').toString();
712 } finally {
713 lock.unlock();
714 }
715 }
716
717 /**
718 * @throws UnsupportedOperationException {@inheritDoc}
719 * @throws ClassCastException {@inheritDoc}
720 * @throws NullPointerException {@inheritDoc}
721 * @throws IllegalArgumentException {@inheritDoc}
722 */
723 public int drainTo(Collection<? super E> c) {
724 return drainTo(c, Integer.MAX_VALUE);
725 }
726
727 /**
728 * @throws UnsupportedOperationException {@inheritDoc}
729 * @throws ClassCastException {@inheritDoc}
730 * @throws NullPointerException {@inheritDoc}
731 * @throws IllegalArgumentException {@inheritDoc}
732 */
733 public int drainTo(Collection<? super E> c, int maxElements) {
734 if (c == null)
735 throw new NullPointerException();
736 if (c == this)
737 throw new IllegalArgumentException();
738 if (maxElements <= 0)
739 return 0;
740 final ReentrantLock lock = this.lock;
741 lock.lock();
742 try {
743 int n = Math.min(size, maxElements);
744 for (int i = 0; i < n; i++) {
745 c.add((E) queue[0]); // In this order, in case add() throws.
746 dequeue();
747 }
748 return n;
749 } finally {
750 lock.unlock();
751 }
752 }
753
754 /**
755 * Atomically removes all of the elements from this queue.
756 * The queue will be empty after this call returns.
757 */
758 public void clear() {
759 final ReentrantLock lock = this.lock;
760 lock.lock();
761 try {
762 Object[] array = queue;
763 int n = size;
764 size = 0;
765 for (int i = 0; i < n; i++)
766 array[i] = null;
767 } finally {
768 lock.unlock();
769 }
770 }
771
772 /**
773 * Returns an array containing all of the elements in this queue; the
774 * runtime type of the returned array is that of the specified array.
775 * The returned array elements are in no particular order.
776 * If the queue fits in the specified array, it is returned therein.
777 * Otherwise, a new array is allocated with the runtime type of the
778 * specified array and the size of this queue.
779 *
780 * <p>If this queue fits in the specified array with room to spare
781 * (i.e., the array has more elements than this queue), the element in
782 * the array immediately following the end of the queue is set to
783 * {@code null}.
784 *
785 * <p>Like the {@link #toArray()} method, this method acts as bridge between
786 * array-based and collection-based APIs. Further, this method allows
787 * precise control over the runtime type of the output array, and may,
788 * under certain circumstances, be used to save allocation costs.
789 *
790 * <p>Suppose {@code x} is a queue known to contain only strings.
791 * The following code can be used to dump the queue into a newly
792 * allocated array of {@code String}:
793 *
794 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
795 *
796 * Note that {@code toArray(new Object[0])} is identical in function to
797 * {@code toArray()}.
798 *
799 * @param a the array into which the elements of the queue are to
800 * be stored, if it is big enough; otherwise, a new array of the
801 * same runtime type is allocated for this purpose
802 * @return an array containing all of the elements in this queue
803 * @throws ArrayStoreException if the runtime type of the specified array
804 * is not a supertype of the runtime type of every element in
805 * this queue
806 * @throws NullPointerException if the specified array is null
807 */
808 public <T> T[] toArray(T[] a) {
809 final ReentrantLock lock = this.lock;
810 lock.lock();
811 try {
812 int n = size;
813 if (a.length < n)
814 // Make a new array of a's runtime type, but my contents:
815 return (T[]) Arrays.copyOf(queue, size, a.getClass());
816 System.arraycopy(queue, 0, a, 0, n);
817 if (a.length > n)
818 a[n] = null;
819 return a;
820 } finally {
821 lock.unlock();
822 }
823 }
824
825 /**
826 * Returns an iterator over the elements in this queue. The
827 * iterator does not return the elements in any particular order.
828 *
829 * <p>The returned iterator is a "weakly consistent" iterator that
830 * will never throw {@link java.util.ConcurrentModificationException
831 * ConcurrentModificationException}, and guarantees to traverse
832 * elements as they existed upon construction of the iterator, and
833 * may (but is not guaranteed to) reflect any modifications
834 * subsequent to construction.
835 *
836 * @return an iterator over the elements in this queue
837 */
838 public Iterator<E> iterator() {
839 return new Itr(toArray());
840 }
841
842 /**
843 * Snapshot iterator that works off copy of underlying q array.
844 */
845 final class Itr implements Iterator<E> {
846 final Object[] array; // Array of all elements
847 int cursor; // index of next element to return
848 int lastRet; // index of last element, or -1 if no such
849
850 Itr(Object[] array) {
851 lastRet = -1;
852 this.array = array;
853 }
854
855 public boolean hasNext() {
856 return cursor < array.length;
857 }
858
859 public E next() {
860 if (cursor >= array.length)
861 throw new NoSuchElementException();
862 lastRet = cursor;
863 return (E)array[cursor++];
864 }
865
866 public void remove() {
867 if (lastRet < 0)
868 throw new IllegalStateException();
869 removeEQ(array[lastRet]);
870 lastRet = -1;
871 }
872 }
873
874 /**
875 * Saves this queue to a stream (that is, serializes it).
876 *
877 * For compatibility with previous version of this class, elements
878 * are first copied to a java.util.PriorityQueue, which is then
879 * serialized.
880 */
881 private void writeObject(java.io.ObjectOutputStream s)
882 throws java.io.IOException {
883 lock.lock();
884 try {
885 // avoid zero capacity argument
886 q = new PriorityQueue<E>(Math.max(size, 1), comparator);
887 q.addAll(this);
888 s.defaultWriteObject();
889 } finally {
890 q = null;
891 lock.unlock();
892 }
893 }
894
895 /**
896 * Reconstitutes this queue from a stream (that is, deserializes it).
897 */
898 private void readObject(java.io.ObjectInputStream s)
899 throws java.io.IOException, ClassNotFoundException {
900 try {
901 s.defaultReadObject();
902 this.queue = new Object[q.size()];
903 comparator = q.comparator();
904 addAll(q);
905 } finally {
906 q = null;
907 }
908 }
909
910 // Unsafe mechanics
911 private static final sun.misc.Unsafe UNSAFE;
912 private static final long allocationSpinLockOffset;
913 static {
914 try {
915 UNSAFE = sun.misc.Unsafe.getUnsafe();
916 Class<?> k = PriorityBlockingQueue.class;
917 allocationSpinLockOffset = UNSAFE.objectFieldOffset
918 (k.getDeclaredField("allocationSpinLock"));
919 } catch (Exception e) {
920 throw new Error(e);
921 }
922 }
923 }