ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.82
Committed: Fri Dec 2 14:37:32 2011 UTC (12 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.81: +1 -0 lines
Log Message:
blanket unchecked warning suppression for comparator-using classes

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