ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.100
Committed: Wed Aug 7 12:52:23 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.99: +14 -0 lines
Log Message:
Mesh with PriorityQueue update

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.concurrent.locks.Condition;
10 import java.util.concurrent.locks.ReentrantLock;
11 import java.util.AbstractQueue;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Comparator;
16 import java.util.Iterator;
17 import java.util.NoSuchElementException;
18 import java.util.PriorityQueue;
19 import java.util.Queue;
20 import java.util.SortedSet;
21 import java.util.Spliterator;
22 import java.util.stream.Stream;
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 collection
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} with the default
204 * initial capacity that orders its elements according to the
205 * specified comparator.
206 *
207 * @param comparator the comparator that will be used to order this
208 * priority queue. If {@code null}, the {@linkplain Comparable
209 * natural ordering} of the elements will be used.
210 * @since 1.8
211 */
212 public PriorityBlockingQueue(Comparator<? super E> comparator) {
213 this(DEFAULT_INITIAL_CAPACITY, comparator);
214 }
215
216 /**
217 * Creates a {@code PriorityBlockingQueue} containing the elements
218 * in the specified collection. If the specified collection is a
219 * {@link SortedSet} or a {@link PriorityQueue}, this
220 * priority queue will be ordered according to the same ordering.
221 * Otherwise, this priority queue will be ordered according to the
222 * {@linkplain Comparable natural ordering} of its elements.
223 *
224 * @param c the collection whose elements are to be placed
225 * into this priority queue
226 * @throws ClassCastException if elements of the specified collection
227 * cannot be compared to one another according to the priority
228 * queue's ordering
229 * @throws NullPointerException if the specified collection or any
230 * of its elements are null
231 */
232 public PriorityBlockingQueue(Collection<? extends E> c) {
233 this.lock = new ReentrantLock();
234 this.notEmpty = lock.newCondition();
235 boolean heapify = true; // true if not known to be in heap order
236 boolean screen = true; // true if must screen for nulls
237 if (c instanceof SortedSet<?>) {
238 SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
239 this.comparator = (Comparator<? super E>) ss.comparator();
240 heapify = false;
241 }
242 else if (c instanceof PriorityBlockingQueue<?>) {
243 PriorityBlockingQueue<? extends E> pq =
244 (PriorityBlockingQueue<? extends E>) c;
245 this.comparator = (Comparator<? super E>) pq.comparator();
246 screen = false;
247 if (pq.getClass() == PriorityBlockingQueue.class) // exact match
248 heapify = false;
249 }
250 Object[] a = c.toArray();
251 int n = a.length;
252 // If c.toArray incorrectly doesn't return Object[], copy it.
253 if (a.getClass() != Object[].class)
254 a = Arrays.copyOf(a, n, Object[].class);
255 if (screen && (n == 1 || this.comparator != null)) {
256 for (int i = 0; i < n; ++i)
257 if (a[i] == null)
258 throw new NullPointerException();
259 }
260 this.queue = a;
261 this.size = n;
262 if (heapify)
263 heapify();
264 }
265
266 /**
267 * Tries to grow array to accommodate at least one more element
268 * (but normally expand by about 50%), giving up (allowing retry)
269 * on contention (which we expect to be rare). Call only while
270 * holding lock.
271 *
272 * @param array the heap array
273 * @param oldCap the length of the array
274 */
275 private void tryGrow(Object[] array, int oldCap) {
276 lock.unlock(); // must release and then re-acquire main lock
277 Object[] newArray = null;
278 if (allocationSpinLock == 0 &&
279 UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
280 0, 1)) {
281 try {
282 int newCap = oldCap + ((oldCap < 64) ?
283 (oldCap + 2) : // grow faster if small
284 (oldCap >> 1));
285 if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
286 int minCap = oldCap + 1;
287 if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
288 throw new OutOfMemoryError();
289 newCap = MAX_ARRAY_SIZE;
290 }
291 if (newCap > oldCap && queue == array)
292 newArray = new Object[newCap];
293 } finally {
294 allocationSpinLock = 0;
295 }
296 }
297 if (newArray == null) // back off if another thread is allocating
298 Thread.yield();
299 lock.lock();
300 if (newArray != null && queue == array) {
301 queue = newArray;
302 System.arraycopy(array, 0, newArray, 0, oldCap);
303 }
304 }
305
306 /**
307 * Mechanics for poll(). Call only while holding lock.
308 */
309 private E dequeue() {
310 int n = size - 1;
311 if (n < 0)
312 return null;
313 else {
314 Object[] array = queue;
315 E result = (E) array[0];
316 E x = (E) array[n];
317 array[n] = null;
318 Comparator<? super E> cmp = comparator;
319 if (cmp == null)
320 siftDownComparable(0, x, array, n);
321 else
322 siftDownUsingComparator(0, x, array, n, cmp);
323 size = n;
324 return result;
325 }
326 }
327
328 /**
329 * Inserts item x at position k, maintaining heap invariant by
330 * promoting x up the tree until it is greater than or equal to
331 * its parent, or is the root.
332 *
333 * To simplify and speed up coercions and comparisons. the
334 * Comparable and Comparator versions are separated into different
335 * methods that are otherwise identical. (Similarly for siftDown.)
336 * These methods are static, with heap state as arguments, to
337 * simplify use in light of possible comparator exceptions.
338 *
339 * @param k the position to fill
340 * @param x the item to insert
341 * @param array the heap array
342 */
343 private static <T> void siftUpComparable(int k, T x, Object[] array) {
344 Comparable<? super T> key = (Comparable<? super T>) x;
345 while (k > 0) {
346 int parent = (k - 1) >>> 1;
347 Object e = array[parent];
348 if (key.compareTo((T) e) >= 0)
349 break;
350 array[k] = e;
351 k = parent;
352 }
353 array[k] = key;
354 }
355
356 private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
357 Comparator<? super T> cmp) {
358 while (k > 0) {
359 int parent = (k - 1) >>> 1;
360 Object e = array[parent];
361 if (cmp.compare(x, (T) e) >= 0)
362 break;
363 array[k] = e;
364 k = parent;
365 }
366 array[k] = x;
367 }
368
369 /**
370 * Inserts item x at position k, maintaining heap invariant by
371 * demoting x down the tree repeatedly until it is less than or
372 * equal to its children or is a leaf.
373 *
374 * @param k the position to fill
375 * @param x the item to insert
376 * @param array the heap array
377 * @param n heap size
378 */
379 private static <T> void siftDownComparable(int k, T x, Object[] array,
380 int n) {
381 if (n > 0) {
382 Comparable<? super T> key = (Comparable<? super T>)x;
383 int half = n >>> 1; // loop while a non-leaf
384 while (k < half) {
385 int child = (k << 1) + 1; // assume left child is least
386 Object c = array[child];
387 int right = child + 1;
388 if (right < n &&
389 ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
390 c = array[child = right];
391 if (key.compareTo((T) c) <= 0)
392 break;
393 array[k] = c;
394 k = child;
395 }
396 array[k] = key;
397 }
398 }
399
400 private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
401 int n,
402 Comparator<? super T> cmp) {
403 if (n > 0) {
404 int half = n >>> 1;
405 while (k < half) {
406 int child = (k << 1) + 1;
407 Object c = array[child];
408 int right = child + 1;
409 if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
410 c = array[child = right];
411 if (cmp.compare(x, (T) c) <= 0)
412 break;
413 array[k] = c;
414 k = child;
415 }
416 array[k] = x;
417 }
418 }
419
420 /**
421 * Establishes the heap invariant (described above) in the entire tree,
422 * assuming nothing about the order of the elements prior to the call.
423 */
424 private void heapify() {
425 Object[] array = queue;
426 int n = size;
427 int half = (n >>> 1) - 1;
428 Comparator<? super E> cmp = comparator;
429 if (cmp == null) {
430 for (int i = half; i >= 0; i--)
431 siftDownComparable(i, (E) array[i], array, n);
432 }
433 else {
434 for (int i = half; i >= 0; i--)
435 siftDownUsingComparator(i, (E) array[i], array, n, cmp);
436 }
437 }
438
439 /**
440 * Inserts the specified element into this priority queue.
441 *
442 * @param e the element to add
443 * @return {@code true} (as specified by {@link Collection#add})
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 add(E e) {
450 return offer(e);
451 }
452
453 /**
454 * Inserts the specified element into this priority queue.
455 * As the queue is unbounded, this method will never return {@code false}.
456 *
457 * @param e the element to add
458 * @return {@code true} (as specified by {@link Queue#offer})
459 * @throws ClassCastException if the specified element cannot be compared
460 * with elements currently in the priority queue according to the
461 * priority queue's ordering
462 * @throws NullPointerException if the specified element is null
463 */
464 public boolean offer(E e) {
465 if (e == null)
466 throw new NullPointerException();
467 final ReentrantLock lock = this.lock;
468 lock.lock();
469 int n, cap;
470 Object[] array;
471 while ((n = size) >= (cap = (array = queue).length))
472 tryGrow(array, cap);
473 try {
474 Comparator<? super E> cmp = comparator;
475 if (cmp == null)
476 siftUpComparable(n, e, array);
477 else
478 siftUpUsingComparator(n, e, array, cmp);
479 size = n + 1;
480 notEmpty.signal();
481 } finally {
482 lock.unlock();
483 }
484 return true;
485 }
486
487 /**
488 * Inserts the specified element into this priority queue.
489 * As the queue is unbounded, this method will never block.
490 *
491 * @param e the element to add
492 * @throws ClassCastException if the specified element cannot be compared
493 * with elements currently in the priority queue according to the
494 * priority queue's ordering
495 * @throws NullPointerException if the specified element is null
496 */
497 public void put(E e) {
498 offer(e); // never need to block
499 }
500
501 /**
502 * Inserts the specified element into this priority queue.
503 * As the queue is unbounded, this method will never block or
504 * return {@code false}.
505 *
506 * @param e the element to add
507 * @param timeout This parameter is ignored as the method never blocks
508 * @param unit This parameter is ignored as the method never blocks
509 * @return {@code true} (as specified by
510 * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
511 * @throws ClassCastException if the specified element cannot be compared
512 * with elements currently in the priority queue according to the
513 * priority queue's ordering
514 * @throws NullPointerException if the specified element is null
515 */
516 public boolean offer(E e, long timeout, TimeUnit unit) {
517 return offer(e); // never need to block
518 }
519
520 public E poll() {
521 final ReentrantLock lock = this.lock;
522 lock.lock();
523 try {
524 return dequeue();
525 } finally {
526 lock.unlock();
527 }
528 }
529
530 public E take() throws InterruptedException {
531 final ReentrantLock lock = this.lock;
532 lock.lockInterruptibly();
533 E result;
534 try {
535 while ( (result = dequeue()) == null)
536 notEmpty.await();
537 } finally {
538 lock.unlock();
539 }
540 return result;
541 }
542
543 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
544 long nanos = unit.toNanos(timeout);
545 final ReentrantLock lock = this.lock;
546 lock.lockInterruptibly();
547 E result;
548 try {
549 while ( (result = dequeue()) == null && nanos > 0)
550 nanos = notEmpty.awaitNanos(nanos);
551 } finally {
552 lock.unlock();
553 }
554 return result;
555 }
556
557 public E peek() {
558 final ReentrantLock lock = this.lock;
559 lock.lock();
560 try {
561 return (size == 0) ? null : (E) queue[0];
562 } finally {
563 lock.unlock();
564 }
565 }
566
567 /**
568 * Returns the comparator used to order the elements in this queue,
569 * or {@code null} if this queue uses the {@linkplain Comparable
570 * natural ordering} of its elements.
571 *
572 * @return the comparator used to order the elements in this queue,
573 * or {@code null} if this queue uses the natural
574 * ordering of its elements
575 */
576 public Comparator<? super E> comparator() {
577 return comparator;
578 }
579
580 public int size() {
581 final ReentrantLock lock = this.lock;
582 lock.lock();
583 try {
584 return size;
585 } finally {
586 lock.unlock();
587 }
588 }
589
590 /**
591 * Always returns {@code Integer.MAX_VALUE} because
592 * a {@code PriorityBlockingQueue} is not capacity constrained.
593 * @return {@code Integer.MAX_VALUE} always
594 */
595 public int remainingCapacity() {
596 return Integer.MAX_VALUE;
597 }
598
599 private int indexOf(Object o) {
600 if (o != null) {
601 Object[] array = queue;
602 int n = size;
603 for (int i = 0; i < n; i++)
604 if (o.equals(array[i]))
605 return i;
606 }
607 return -1;
608 }
609
610 /**
611 * Removes the ith element from queue.
612 */
613 private void removeAt(int i) {
614 Object[] array = queue;
615 int n = size - 1;
616 if (n == i) // removed last element
617 array[i] = null;
618 else {
619 E moved = (E) array[n];
620 array[n] = null;
621 Comparator<? super E> cmp = comparator;
622 if (cmp == null)
623 siftDownComparable(i, moved, array, n);
624 else
625 siftDownUsingComparator(i, moved, array, n, cmp);
626 if (array[i] == moved) {
627 if (cmp == null)
628 siftUpComparable(i, moved, array);
629 else
630 siftUpUsingComparator(i, moved, array, cmp);
631 }
632 }
633 size = n;
634 }
635
636 /**
637 * Removes a single instance of the specified element from this queue,
638 * if it is present. More formally, removes an element {@code e} such
639 * that {@code o.equals(e)}, if this queue contains one or more such
640 * elements. Returns {@code true} if and only if this queue contained
641 * the specified element (or equivalently, if this queue changed as a
642 * result of the call).
643 *
644 * @param o element to be removed from this queue, if present
645 * @return {@code true} if this queue changed as a result of the call
646 */
647 public boolean remove(Object o) {
648 final ReentrantLock lock = this.lock;
649 lock.lock();
650 try {
651 int i = indexOf(o);
652 if (i == -1)
653 return false;
654 removeAt(i);
655 return true;
656 } finally {
657 lock.unlock();
658 }
659 }
660
661 /**
662 * Identity-based version for use in Itr.remove
663 */
664 void removeEQ(Object o) {
665 final ReentrantLock lock = this.lock;
666 lock.lock();
667 try {
668 Object[] array = queue;
669 for (int i = 0, n = size; i < n; i++) {
670 if (o == array[i]) {
671 removeAt(i);
672 break;
673 }
674 }
675 } finally {
676 lock.unlock();
677 }
678 }
679
680 /**
681 * Returns {@code true} if this queue contains the specified element.
682 * More formally, returns {@code true} if and only if this queue contains
683 * at least one element {@code e} such that {@code o.equals(e)}.
684 *
685 * @param o object to be checked for containment in this queue
686 * @return {@code true} if this queue contains the specified element
687 */
688 public boolean contains(Object o) {
689 final ReentrantLock lock = this.lock;
690 lock.lock();
691 try {
692 return indexOf(o) != -1;
693 } finally {
694 lock.unlock();
695 }
696 }
697
698 /**
699 * Returns an array containing all of the elements in this queue.
700 * The returned array elements are in no particular order.
701 *
702 * <p>The returned array will be "safe" in that no references to it are
703 * maintained by this queue. (In other words, this method must allocate
704 * a new array). The caller is thus free to modify the returned array.
705 *
706 * <p>This method acts as bridge between array-based and collection-based
707 * APIs.
708 *
709 * @return an array containing all of the elements in this queue
710 */
711 public Object[] toArray() {
712 final ReentrantLock lock = this.lock;
713 lock.lock();
714 try {
715 return Arrays.copyOf(queue, size);
716 } finally {
717 lock.unlock();
718 }
719 }
720
721 public String toString() {
722 final ReentrantLock lock = this.lock;
723 lock.lock();
724 try {
725 int n = size;
726 if (n == 0)
727 return "[]";
728 StringBuilder sb = new StringBuilder();
729 sb.append('[');
730 for (int i = 0; i < n; ++i) {
731 Object e = queue[i];
732 sb.append(e == this ? "(this Collection)" : e);
733 if (i != n - 1)
734 sb.append(',').append(' ');
735 }
736 return sb.append(']').toString();
737 } finally {
738 lock.unlock();
739 }
740 }
741
742 /**
743 * @throws UnsupportedOperationException {@inheritDoc}
744 * @throws ClassCastException {@inheritDoc}
745 * @throws NullPointerException {@inheritDoc}
746 * @throws IllegalArgumentException {@inheritDoc}
747 */
748 public int drainTo(Collection<? super E> c) {
749 return drainTo(c, Integer.MAX_VALUE);
750 }
751
752 /**
753 * @throws UnsupportedOperationException {@inheritDoc}
754 * @throws ClassCastException {@inheritDoc}
755 * @throws NullPointerException {@inheritDoc}
756 * @throws IllegalArgumentException {@inheritDoc}
757 */
758 public int drainTo(Collection<? super E> c, int maxElements) {
759 if (c == null)
760 throw new NullPointerException();
761 if (c == this)
762 throw new IllegalArgumentException();
763 if (maxElements <= 0)
764 return 0;
765 final ReentrantLock lock = this.lock;
766 lock.lock();
767 try {
768 int n = Math.min(size, maxElements);
769 for (int i = 0; i < n; i++) {
770 c.add((E) queue[0]); // In this order, in case add() throws.
771 dequeue();
772 }
773 return n;
774 } finally {
775 lock.unlock();
776 }
777 }
778
779 /**
780 * Atomically removes all of the elements from this queue.
781 * The queue will be empty after this call returns.
782 */
783 public void clear() {
784 final ReentrantLock lock = this.lock;
785 lock.lock();
786 try {
787 Object[] array = queue;
788 int n = size;
789 size = 0;
790 for (int i = 0; i < n; i++)
791 array[i] = null;
792 } finally {
793 lock.unlock();
794 }
795 }
796
797 /**
798 * Returns an array containing all of the elements in this queue; the
799 * runtime type of the returned array is that of the specified array.
800 * The returned array elements are in no particular order.
801 * If the queue fits in the specified array, it is returned therein.
802 * Otherwise, a new array is allocated with the runtime type of the
803 * specified array and the size of this queue.
804 *
805 * <p>If this queue fits in the specified array with room to spare
806 * (i.e., the array has more elements than this queue), the element in
807 * the array immediately following the end of the queue is set to
808 * {@code null}.
809 *
810 * <p>Like the {@link #toArray()} method, this method acts as bridge between
811 * array-based and collection-based APIs. Further, this method allows
812 * precise control over the runtime type of the output array, and may,
813 * under certain circumstances, be used to save allocation costs.
814 *
815 * <p>Suppose {@code x} is a queue known to contain only strings.
816 * The following code can be used to dump the queue into a newly
817 * allocated array of {@code String}:
818 *
819 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
820 *
821 * Note that {@code toArray(new Object[0])} is identical in function to
822 * {@code toArray()}.
823 *
824 * @param a the array into which the elements of the queue are to
825 * be stored, if it is big enough; otherwise, a new array of the
826 * same runtime type is allocated for this purpose
827 * @return an array containing all of the elements in this queue
828 * @throws ArrayStoreException if the runtime type of the specified array
829 * is not a supertype of the runtime type of every element in
830 * this queue
831 * @throws NullPointerException if the specified array is null
832 */
833 public <T> T[] toArray(T[] a) {
834 final ReentrantLock lock = this.lock;
835 lock.lock();
836 try {
837 int n = size;
838 if (a.length < n)
839 // Make a new array of a's runtime type, but my contents:
840 return (T[]) Arrays.copyOf(queue, size, a.getClass());
841 System.arraycopy(queue, 0, a, 0, n);
842 if (a.length > n)
843 a[n] = null;
844 return a;
845 } finally {
846 lock.unlock();
847 }
848 }
849
850 /**
851 * Returns an iterator over the elements in this queue. The
852 * iterator does not return the elements in any particular order.
853 *
854 * <p>The returned iterator is a "weakly consistent" iterator that
855 * will never throw {@link java.util.ConcurrentModificationException
856 * ConcurrentModificationException}, and guarantees to traverse
857 * elements as they existed upon construction of the iterator, and
858 * may (but is not guaranteed to) reflect any modifications
859 * subsequent to construction.
860 *
861 * @return an iterator over the elements in this queue
862 */
863 public Iterator<E> iterator() {
864 return new Itr(toArray());
865 }
866
867 /**
868 * Snapshot iterator that works off copy of underlying q array.
869 */
870 final class Itr implements Iterator<E> {
871 final Object[] array; // Array of all elements
872 int cursor; // index of next element to return
873 int lastRet; // index of last element, or -1 if no such
874
875 Itr(Object[] array) {
876 lastRet = -1;
877 this.array = array;
878 }
879
880 public boolean hasNext() {
881 return cursor < array.length;
882 }
883
884 public E next() {
885 if (cursor >= array.length)
886 throw new NoSuchElementException();
887 lastRet = cursor;
888 return (E)array[cursor++];
889 }
890
891 public void remove() {
892 if (lastRet < 0)
893 throw new IllegalStateException();
894 removeEQ(array[lastRet]);
895 lastRet = -1;
896 }
897 }
898
899 /**
900 * Saves this queue to a stream (that is, serializes it).
901 *
902 * For compatibility with previous version of this class, elements
903 * are first copied to a java.util.PriorityQueue, which is then
904 * serialized.
905 *
906 * @param s the stream
907 * @throws java.io.IOException if an I/O error occurs
908 */
909 private void writeObject(java.io.ObjectOutputStream s)
910 throws java.io.IOException {
911 lock.lock();
912 try {
913 // avoid zero capacity argument
914 q = new PriorityQueue<E>(Math.max(size, 1), comparator);
915 q.addAll(this);
916 s.defaultWriteObject();
917 } finally {
918 q = null;
919 lock.unlock();
920 }
921 }
922
923 /**
924 * Reconstitutes this queue from a stream (that is, deserializes it).
925 * @param s the stream
926 * @throws ClassNotFoundException if the class of a serialized object
927 * could not be found
928 * @throws java.io.IOException if an I/O error occurs
929 */
930 private void readObject(java.io.ObjectInputStream s)
931 throws java.io.IOException, ClassNotFoundException {
932 try {
933 s.defaultReadObject();
934 this.queue = new Object[q.size()];
935 comparator = q.comparator();
936 addAll(q);
937 } finally {
938 q = null;
939 }
940 }
941
942 // Similar to Collections.ArraySnapshotSpliterator but avoids
943 // commitment to toArray until needed
944 static final class PBQSpliterator<E> implements Spliterator<E> {
945 final PriorityBlockingQueue<E> queue;
946 Object[] array;
947 int index;
948 int fence;
949
950 PBQSpliterator(PriorityBlockingQueue<E> queue, Object[] array,
951 int index, int fence) {
952 this.queue = queue;
953 this.array = array;
954 this.index = index;
955 this.fence = fence;
956 }
957
958 final int getFence() {
959 int hi;
960 if ((hi = fence) < 0)
961 hi = fence = (array = queue.toArray()).length;
962 return hi;
963 }
964
965 public Spliterator<E> trySplit() {
966 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
967 return (lo >= mid) ? null :
968 new PBQSpliterator<E>(queue, array, lo, index = mid);
969 }
970
971 @SuppressWarnings("unchecked")
972 public void forEachRemaining(Consumer<? super E> action) {
973 Object[] a; int i, hi; // hoist accesses and checks from loop
974 if (action == null)
975 throw new NullPointerException();
976 if ((a = array) == null)
977 fence = (a = queue.toArray()).length;
978 if ((hi = fence) <= a.length &&
979 (i = index) >= 0 && i < (index = hi)) {
980 do { action.accept((E)a[i]); } while (++i < hi);
981 }
982 }
983
984 public boolean tryAdvance(Consumer<? super E> action) {
985 if (action == null)
986 throw new NullPointerException();
987 if (getFence() > index && index >= 0) {
988 @SuppressWarnings("unchecked") E e = (E) array[index++];
989 action.accept(e);
990 return true;
991 }
992 return false;
993 }
994
995 public long estimateSize() { return (long)(getFence() - index); }
996
997 public int characteristics() {
998 return Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED;
999 }
1000 }
1001
1002 public Spliterator<E> spliterator() {
1003 return new PBQSpliterator<E>(this, null, 0, -1);
1004 }
1005
1006 // Unsafe mechanics
1007 private static final sun.misc.Unsafe UNSAFE;
1008 private static final long allocationSpinLockOffset;
1009 static {
1010 try {
1011 UNSAFE = sun.misc.Unsafe.getUnsafe();
1012 Class<?> k = PriorityBlockingQueue.class;
1013 allocationSpinLockOffset = UNSAFE.objectFieldOffset
1014 (k.getDeclaredField("allocationSpinLock"));
1015 } catch (Exception e) {
1016 throw new Error(e);
1017 }
1018 }
1019 }