ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.121
Committed: Sun Dec 18 21:52:10 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.120: +1 -1 lines
Log Message:
typo

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