ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.66
Committed: Wed Oct 13 14:01:25 2010 UTC (13 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.65: +197 -167 lines
Log Message:
Ensure consistent state on exceptions; incorporate review suggestions

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