ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.125
Committed: Mon Dec 26 19:54:46 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.124: +14 -17 lines
Log Message:
rewrite spliterators to address 8172023: Concurrent spliterators fail to handle exhaustion properly

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