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