ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.115
Committed: Thu Jun 2 13:16:27 2016 UTC (8 years ago) by dl
Branch: MAIN
Changes since 1.114: +9 -6 lines
Log Message:
VarHandles conversion; pass 1

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