ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.5
Committed: Tue Dec 20 22:10:13 2016 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.4: +0 -2 lines
Log Message:
remove confusing comments

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 *
311 * @param k the position to fill
312 * @param x the item to insert
313 * @param array the heap array
314 */
315 private static <T> void siftUpComparable(int k, T x, Object[] array) {
316 Comparable<? super T> key = (Comparable<? super T>) x;
317 while (k > 0) {
318 int parent = (k - 1) >>> 1;
319 Object e = array[parent];
320 if (key.compareTo((T) e) >= 0)
321 break;
322 array[k] = e;
323 k = parent;
324 }
325 array[k] = key;
326 }
327
328 private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
329 Comparator<? super T> cmp) {
330 while (k > 0) {
331 int parent = (k - 1) >>> 1;
332 Object e = array[parent];
333 if (cmp.compare(x, (T) e) >= 0)
334 break;
335 array[k] = e;
336 k = parent;
337 }
338 array[k] = x;
339 }
340
341 /**
342 * Inserts item x at position k, maintaining heap invariant by
343 * demoting x down the tree repeatedly until it is less than or
344 * equal to its children or is a leaf.
345 *
346 * @param k the position to fill
347 * @param x the item to insert
348 * @param array the heap array
349 * @param n heap size
350 */
351 private static <T> void siftDownComparable(int k, T x, Object[] array,
352 int n) {
353 if (n > 0) {
354 Comparable<? super T> key = (Comparable<? super T>)x;
355 int half = n >>> 1; // loop while a non-leaf
356 while (k < half) {
357 int child = (k << 1) + 1; // assume left child is least
358 Object c = array[child];
359 int right = child + 1;
360 if (right < n &&
361 ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
362 c = array[child = right];
363 if (key.compareTo((T) c) <= 0)
364 break;
365 array[k] = c;
366 k = child;
367 }
368 array[k] = key;
369 }
370 }
371
372 private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
373 int n,
374 Comparator<? super T> cmp) {
375 if (n > 0) {
376 int half = n >>> 1;
377 while (k < half) {
378 int child = (k << 1) + 1;
379 Object c = array[child];
380 int right = child + 1;
381 if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
382 c = array[child = right];
383 if (cmp.compare(x, (T) c) <= 0)
384 break;
385 array[k] = c;
386 k = child;
387 }
388 array[k] = x;
389 }
390 }
391
392 /**
393 * Establishes the heap invariant (described above) in the entire tree,
394 * assuming nothing about the order of the elements prior to the call.
395 */
396 private void heapify() {
397 Object[] array = queue;
398 int n = size;
399 int half = (n >>> 1) - 1;
400 Comparator<? super E> cmp = comparator;
401 if (cmp == null) {
402 for (int i = half; i >= 0; i--)
403 siftDownComparable(i, (E) array[i], array, n);
404 }
405 else {
406 for (int i = half; i >= 0; i--)
407 siftDownUsingComparator(i, (E) array[i], array, n, cmp);
408 }
409 }
410
411 /**
412 * Inserts the specified element into this priority queue.
413 *
414 * @param e the element to add
415 * @return {@code true} (as specified by {@link Collection#add})
416 * @throws ClassCastException if the specified element cannot be compared
417 * with elements currently in the priority queue according to the
418 * priority queue's ordering
419 * @throws NullPointerException if the specified element is null
420 */
421 public boolean add(E e) {
422 return offer(e);
423 }
424
425 /**
426 * Inserts the specified element into this priority queue.
427 * As the queue is unbounded, this method will never return {@code false}.
428 *
429 * @param e the element to add
430 * @return {@code true} (as specified by {@link Queue#offer})
431 * @throws ClassCastException if the specified element cannot be compared
432 * with elements currently in the priority queue according to the
433 * priority queue's ordering
434 * @throws NullPointerException if the specified element is null
435 */
436 public boolean offer(E e) {
437 if (e == null)
438 throw new NullPointerException();
439 final ReentrantLock lock = this.lock;
440 lock.lock();
441 int n, cap;
442 Object[] array;
443 while ((n = size) >= (cap = (array = queue).length))
444 tryGrow(array, cap);
445 try {
446 Comparator<? super E> cmp = comparator;
447 if (cmp == null)
448 siftUpComparable(n, e, array);
449 else
450 siftUpUsingComparator(n, e, array, cmp);
451 size = n + 1;
452 notEmpty.signal();
453 } finally {
454 lock.unlock();
455 }
456 return true;
457 }
458
459 /**
460 * Inserts the specified element into this priority queue.
461 * As the queue is unbounded, this method will never block.
462 *
463 * @param e the element to add
464 * @throws ClassCastException if the specified element cannot be compared
465 * with elements currently in the priority queue according to the
466 * priority queue's ordering
467 * @throws NullPointerException if the specified element is null
468 */
469 public void put(E e) {
470 offer(e); // never need to block
471 }
472
473 /**
474 * Inserts the specified element into this priority queue.
475 * As the queue is unbounded, this method will never block or
476 * return {@code false}.
477 *
478 * @param e the element to add
479 * @param timeout This parameter is ignored as the method never blocks
480 * @param unit This parameter is ignored as the method never blocks
481 * @return {@code true} (as specified by
482 * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
483 * @throws ClassCastException if the specified element cannot be compared
484 * with elements currently in the priority queue according to the
485 * priority queue's ordering
486 * @throws NullPointerException if the specified element is null
487 */
488 public boolean offer(E e, long timeout, TimeUnit unit) {
489 return offer(e); // never need to block
490 }
491
492 public E poll() {
493 final ReentrantLock lock = this.lock;
494 lock.lock();
495 try {
496 return dequeue();
497 } finally {
498 lock.unlock();
499 }
500 }
501
502 public E take() throws InterruptedException {
503 final ReentrantLock lock = this.lock;
504 lock.lockInterruptibly();
505 E result;
506 try {
507 while ( (result = dequeue()) == null)
508 notEmpty.await();
509 } finally {
510 lock.unlock();
511 }
512 return result;
513 }
514
515 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
516 long nanos = unit.toNanos(timeout);
517 final ReentrantLock lock = this.lock;
518 lock.lockInterruptibly();
519 E result;
520 try {
521 while ( (result = dequeue()) == null && nanos > 0)
522 nanos = notEmpty.awaitNanos(nanos);
523 } finally {
524 lock.unlock();
525 }
526 return result;
527 }
528
529 public E peek() {
530 final ReentrantLock lock = this.lock;
531 lock.lock();
532 try {
533 return (size == 0) ? null : (E) queue[0];
534 } finally {
535 lock.unlock();
536 }
537 }
538
539 /**
540 * Returns the comparator used to order the elements in this queue,
541 * or {@code null} if this queue uses the {@linkplain Comparable
542 * natural ordering} of its elements.
543 *
544 * @return the comparator used to order the elements in this queue,
545 * or {@code null} if this queue uses the natural
546 * ordering of its elements
547 */
548 public Comparator<? super E> comparator() {
549 return comparator;
550 }
551
552 public int size() {
553 final ReentrantLock lock = this.lock;
554 lock.lock();
555 try {
556 return size;
557 } finally {
558 lock.unlock();
559 }
560 }
561
562 /**
563 * Always returns {@code Integer.MAX_VALUE} because
564 * a {@code PriorityBlockingQueue} is not capacity constrained.
565 * @return {@code Integer.MAX_VALUE} always
566 */
567 public int remainingCapacity() {
568 return Integer.MAX_VALUE;
569 }
570
571 private int indexOf(Object o) {
572 if (o != null) {
573 Object[] array = queue;
574 int n = size;
575 for (int i = 0; i < n; i++)
576 if (o.equals(array[i]))
577 return i;
578 }
579 return -1;
580 }
581
582 /**
583 * Removes the ith element from queue.
584 */
585 private void removeAt(int i) {
586 Object[] array = queue;
587 int n = size - 1;
588 if (n == i) // removed last element
589 array[i] = null;
590 else {
591 E moved = (E) array[n];
592 array[n] = null;
593 Comparator<? super E> cmp = comparator;
594 if (cmp == null)
595 siftDownComparable(i, moved, array, n);
596 else
597 siftDownUsingComparator(i, moved, array, n, cmp);
598 if (array[i] == moved) {
599 if (cmp == null)
600 siftUpComparable(i, moved, array);
601 else
602 siftUpUsingComparator(i, moved, array, cmp);
603 }
604 }
605 size = n;
606 }
607
608 /**
609 * Removes a single instance of the specified element from this queue,
610 * if it is present. More formally, removes an element {@code e} such
611 * that {@code o.equals(e)}, if this queue contains one or more such
612 * elements. Returns {@code true} if and only if this queue contained
613 * the specified element (or equivalently, if this queue changed as a
614 * result of the call).
615 *
616 * @param o element to be removed from this queue, if present
617 * @return {@code true} if this queue changed as a result of the call
618 */
619 public boolean remove(Object o) {
620 final ReentrantLock lock = this.lock;
621 lock.lock();
622 try {
623 int i = indexOf(o);
624 if (i == -1)
625 return false;
626 removeAt(i);
627 return true;
628 } finally {
629 lock.unlock();
630 }
631 }
632
633 /**
634 * Identity-based version for use in Itr.remove
635 */
636 void removeEQ(Object o) {
637 final ReentrantLock lock = this.lock;
638 lock.lock();
639 try {
640 Object[] array = queue;
641 for (int i = 0, n = size; i < n; i++) {
642 if (o == array[i]) {
643 removeAt(i);
644 break;
645 }
646 }
647 } finally {
648 lock.unlock();
649 }
650 }
651
652 /**
653 * Returns {@code true} if this queue contains the specified element.
654 * More formally, returns {@code true} if and only if this queue contains
655 * at least one element {@code e} such that {@code o.equals(e)}.
656 *
657 * @param o object to be checked for containment in this queue
658 * @return {@code true} if this queue contains the specified element
659 */
660 public boolean contains(Object o) {
661 final ReentrantLock lock = this.lock;
662 lock.lock();
663 try {
664 return indexOf(o) != -1;
665 } finally {
666 lock.unlock();
667 }
668 }
669
670 /**
671 * Returns an array containing all of the elements in this queue.
672 * The returned array elements are in no particular order.
673 *
674 * <p>The returned array will be "safe" in that no references to it are
675 * maintained by this queue. (In other words, this method must allocate
676 * a new array). The caller is thus free to modify the returned array.
677 *
678 * <p>This method acts as bridge between array-based and collection-based
679 * APIs.
680 *
681 * @return an array containing all of the elements in this queue
682 */
683 public Object[] toArray() {
684 final ReentrantLock lock = this.lock;
685 lock.lock();
686 try {
687 return Arrays.copyOf(queue, size);
688 } finally {
689 lock.unlock();
690 }
691 }
692
693 public String toString() {
694 final ReentrantLock lock = this.lock;
695 lock.lock();
696 try {
697 int n = size;
698 if (n == 0)
699 return "[]";
700 StringBuilder sb = new StringBuilder();
701 sb.append('[');
702 for (int i = 0; i < n; ++i) {
703 Object e = queue[i];
704 sb.append(e == this ? "(this Collection)" : e);
705 if (i != n - 1)
706 sb.append(',').append(' ');
707 }
708 return sb.append(']').toString();
709 } finally {
710 lock.unlock();
711 }
712 }
713
714 /**
715 * @throws UnsupportedOperationException {@inheritDoc}
716 * @throws ClassCastException {@inheritDoc}
717 * @throws NullPointerException {@inheritDoc}
718 * @throws IllegalArgumentException {@inheritDoc}
719 */
720 public int drainTo(Collection<? super E> c) {
721 return drainTo(c, Integer.MAX_VALUE);
722 }
723
724 /**
725 * @throws UnsupportedOperationException {@inheritDoc}
726 * @throws ClassCastException {@inheritDoc}
727 * @throws NullPointerException {@inheritDoc}
728 * @throws IllegalArgumentException {@inheritDoc}
729 */
730 public int drainTo(Collection<? super E> c, int maxElements) {
731 if (c == null)
732 throw new NullPointerException();
733 if (c == this)
734 throw new IllegalArgumentException();
735 if (maxElements <= 0)
736 return 0;
737 final ReentrantLock lock = this.lock;
738 lock.lock();
739 try {
740 int n = Math.min(size, maxElements);
741 for (int i = 0; i < n; i++) {
742 c.add((E) queue[0]); // In this order, in case add() throws.
743 dequeue();
744 }
745 return n;
746 } finally {
747 lock.unlock();
748 }
749 }
750
751 /**
752 * Atomically removes all of the elements from this queue.
753 * The queue will be empty after this call returns.
754 */
755 public void clear() {
756 final ReentrantLock lock = this.lock;
757 lock.lock();
758 try {
759 Object[] array = queue;
760 int n = size;
761 size = 0;
762 for (int i = 0; i < n; i++)
763 array[i] = null;
764 } finally {
765 lock.unlock();
766 }
767 }
768
769 /**
770 * Returns an array containing all of the elements in this queue; the
771 * runtime type of the returned array is that of the specified array.
772 * The returned array elements are in no particular order.
773 * If the queue fits in the specified array, it is returned therein.
774 * Otherwise, a new array is allocated with the runtime type of the
775 * specified array and the size of this queue.
776 *
777 * <p>If this queue fits in the specified array with room to spare
778 * (i.e., the array has more elements than this queue), the element in
779 * the array immediately following the end of the queue is set to
780 * {@code null}.
781 *
782 * <p>Like the {@link #toArray()} method, this method acts as bridge between
783 * array-based and collection-based APIs. Further, this method allows
784 * precise control over the runtime type of the output array, and may,
785 * under certain circumstances, be used to save allocation costs.
786 *
787 * <p>Suppose {@code x} is a queue known to contain only strings.
788 * The following code can be used to dump the queue into a newly
789 * allocated array of {@code String}:
790 *
791 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
792 *
793 * Note that {@code toArray(new Object[0])} is identical in function to
794 * {@code toArray()}.
795 *
796 * @param a the array into which the elements of the queue are to
797 * be stored, if it is big enough; otherwise, a new array of the
798 * same runtime type is allocated for this purpose
799 * @return an array containing all of the elements in this queue
800 * @throws ArrayStoreException if the runtime type of the specified array
801 * is not a supertype of the runtime type of every element in
802 * this queue
803 * @throws NullPointerException if the specified array is null
804 */
805 public <T> T[] toArray(T[] a) {
806 final ReentrantLock lock = this.lock;
807 lock.lock();
808 try {
809 int n = size;
810 if (a.length < n)
811 // Make a new array of a's runtime type, but my contents:
812 return (T[]) Arrays.copyOf(queue, size, a.getClass());
813 System.arraycopy(queue, 0, a, 0, n);
814 if (a.length > n)
815 a[n] = null;
816 return a;
817 } finally {
818 lock.unlock();
819 }
820 }
821
822 /**
823 * Returns an iterator over the elements in this queue. The
824 * iterator does not return the elements in any particular order.
825 *
826 * <p>The returned iterator is a "weakly consistent" iterator that
827 * will never throw {@link java.util.ConcurrentModificationException
828 * ConcurrentModificationException}, and guarantees to traverse
829 * elements as they existed upon construction of the iterator, and
830 * may (but is not guaranteed to) reflect any modifications
831 * subsequent to construction.
832 *
833 * @return an iterator over the elements in this queue
834 */
835 public Iterator<E> iterator() {
836 return new Itr(toArray());
837 }
838
839 /**
840 * Snapshot iterator that works off copy of underlying q array.
841 */
842 final class Itr implements Iterator<E> {
843 final Object[] array; // Array of all elements
844 int cursor; // index of next element to return
845 int lastRet; // index of last element, or -1 if no such
846
847 Itr(Object[] array) {
848 lastRet = -1;
849 this.array = array;
850 }
851
852 public boolean hasNext() {
853 return cursor < array.length;
854 }
855
856 public E next() {
857 if (cursor >= array.length)
858 throw new NoSuchElementException();
859 lastRet = cursor;
860 return (E)array[cursor++];
861 }
862
863 public void remove() {
864 if (lastRet < 0)
865 throw new IllegalStateException();
866 removeEQ(array[lastRet]);
867 lastRet = -1;
868 }
869 }
870
871 /**
872 * Saves this queue to a stream (that is, serializes it).
873 *
874 * For compatibility with previous version of this class, elements
875 * are first copied to a java.util.PriorityQueue, which is then
876 * serialized.
877 */
878 private void writeObject(java.io.ObjectOutputStream s)
879 throws java.io.IOException {
880 lock.lock();
881 try {
882 // avoid zero capacity argument
883 q = new PriorityQueue<E>(Math.max(size, 1), comparator);
884 q.addAll(this);
885 s.defaultWriteObject();
886 } finally {
887 q = null;
888 lock.unlock();
889 }
890 }
891
892 /**
893 * Reconstitutes this queue from a stream (that is, deserializes it).
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 }