ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.106
Committed: Wed Dec 31 09:37:20 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.105: +0 -2 lines
Log Message:
remove unused/redundant imports

File Contents

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