ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.69
Committed: Fri Nov 19 08:02:10 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.68: +3 -2 lines
Log Message:
make iterator weakly consistent specs more consistent

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 final ReentrantLock lock = this.lock;
556 lock.lock();
557 try {
558 return size;
559 } finally {
560 lock.unlock();
561 }
562 }
563
564 /**
565 * Always returns {@code Integer.MAX_VALUE} because
566 * a {@code PriorityBlockingQueue} is not capacity constrained.
567 * @return {@code Integer.MAX_VALUE} always
568 */
569 public int remainingCapacity() {
570 return Integer.MAX_VALUE;
571 }
572
573 private int indexOf(Object o) {
574 if (o != null) {
575 Object[] array = queue;
576 int n = size;
577 for (int i = 0; i < n; i++)
578 if (o.equals(array[i]))
579 return i;
580 }
581 return -1;
582 }
583
584 /**
585 * Removes the ith element from queue.
586 */
587 private void removeAt(int i) {
588 Object[] array = queue;
589 int n = size - 1;
590 if (n == i) // removed last element
591 array[i] = null;
592 else {
593 E moved = (E) array[n];
594 array[n] = null;
595 Comparator<? super E> cmp = comparator;
596 if (cmp == null)
597 siftDownComparable(i, moved, array, n);
598 else
599 siftDownUsingComparator(i, moved, array, n, cmp);
600 if (array[i] == moved) {
601 if (cmp == null)
602 siftUpComparable(i, moved, array);
603 else
604 siftUpUsingComparator(i, moved, array, cmp);
605 }
606 }
607 size = n;
608 }
609
610 /**
611 * Removes a single instance of the specified element from this queue,
612 * if it is present. More formally, removes an element {@code e} such
613 * that {@code o.equals(e)}, if this queue contains one or more such
614 * elements. Returns {@code true} if and only if this queue contained
615 * the specified element (or equivalently, if this queue changed as a
616 * result of the call).
617 *
618 * @param o element to be removed from this queue, if present
619 * @return {@code true} if this queue changed as a result of the call
620 */
621 public boolean remove(Object o) {
622 boolean removed = false;
623 final ReentrantLock lock = this.lock;
624 lock.lock();
625 try {
626 int i = indexOf(o);
627 if (i != -1) {
628 removeAt(i);
629 removed = true;
630 }
631 } finally {
632 lock.unlock();
633 }
634 return removed;
635 }
636
637
638 /**
639 * Identity-based version for use in Itr.remove
640 */
641 private void removeEQ(Object o) {
642 final ReentrantLock lock = this.lock;
643 lock.lock();
644 try {
645 Object[] array = queue;
646 int n = size;
647 for (int i = 0; i < n; i++) {
648 if (o == array[i]) {
649 removeAt(i);
650 break;
651 }
652 }
653 } finally {
654 lock.unlock();
655 }
656 }
657
658 /**
659 * Returns {@code true} if this queue contains the specified element.
660 * More formally, returns {@code true} if and only if this queue contains
661 * at least one element {@code e} such that {@code o.equals(e)}.
662 *
663 * @param o object to be checked for containment in this queue
664 * @return {@code true} if this queue contains the specified element
665 */
666 public boolean contains(Object o) {
667 int index;
668 final ReentrantLock lock = this.lock;
669 lock.lock();
670 try {
671 index = indexOf(o);
672 } finally {
673 lock.unlock();
674 }
675 return index != -1;
676 }
677
678 /**
679 * Returns an array containing all of the elements in this queue.
680 * The returned array elements are in no particular order.
681 *
682 * <p>The returned array will be "safe" in that no references to it are
683 * maintained by this queue. (In other words, this method must allocate
684 * a new array). The caller is thus free to modify the returned array.
685 *
686 * <p>This method acts as bridge between array-based and collection-based
687 * APIs.
688 *
689 * @return an array containing all of the elements in this queue
690 */
691 public Object[] toArray() {
692 final ReentrantLock lock = this.lock;
693 lock.lock();
694 try {
695 return Arrays.copyOf(queue, size);
696 } finally {
697 lock.unlock();
698 }
699 }
700
701
702 public String toString() {
703 final ReentrantLock lock = this.lock;
704 lock.lock();
705 try {
706 int n = size;
707 if (n == 0)
708 return "[]";
709 StringBuilder sb = new StringBuilder();
710 sb.append('[');
711 for (int i = 0; i < n; ++i) {
712 E e = (E)queue[i];
713 sb.append(e == this ? "(this Collection)" : e);
714 if (i != n - 1)
715 sb.append(',').append(' ');
716 }
717 return sb.append(']').toString();
718 } finally {
719 lock.unlock();
720 }
721 }
722
723 /**
724 * @throws UnsupportedOperationException {@inheritDoc}
725 * @throws ClassCastException {@inheritDoc}
726 * @throws NullPointerException {@inheritDoc}
727 * @throws IllegalArgumentException {@inheritDoc}
728 */
729 public int drainTo(Collection<? super E> c) {
730 if (c == null)
731 throw new NullPointerException();
732 if (c == this)
733 throw new IllegalArgumentException();
734 final ReentrantLock lock = this.lock;
735 lock.lock();
736 try {
737 int n = 0;
738 E e;
739 while ( (e = extract()) != null) {
740 c.add(e);
741 ++n;
742 }
743 return n;
744 } finally {
745 lock.unlock();
746 }
747 }
748
749 /**
750 * @throws UnsupportedOperationException {@inheritDoc}
751 * @throws ClassCastException {@inheritDoc}
752 * @throws NullPointerException {@inheritDoc}
753 * @throws IllegalArgumentException {@inheritDoc}
754 */
755 public int drainTo(Collection<? super E> c, int maxElements) {
756 if (c == null)
757 throw new NullPointerException();
758 if (c == this)
759 throw new IllegalArgumentException();
760 if (maxElements <= 0)
761 return 0;
762 final ReentrantLock lock = this.lock;
763 lock.lock();
764 try {
765 int n = 0;
766 E e;
767 while (n < maxElements && (e = extract()) != null) {
768 c.add(e);
769 ++n;
770 }
771 return n;
772 } finally {
773 lock.unlock();
774 }
775 }
776
777 /**
778 * Atomically removes all of the elements from this queue.
779 * The queue will be empty after this call returns.
780 */
781 public void clear() {
782 final ReentrantLock lock = this.lock;
783 lock.lock();
784 try {
785 Object[] array = queue;
786 int n = size;
787 size = 0;
788 for (int i = 0; i < n; i++)
789 array[i] = null;
790 } finally {
791 lock.unlock();
792 }
793 }
794
795 /**
796 * Returns an array containing all of the elements in this queue; the
797 * runtime type of the returned array is that of the specified array.
798 * The returned array elements are in no particular order.
799 * If the queue fits in the specified array, it is returned therein.
800 * Otherwise, a new array is allocated with the runtime type of the
801 * specified array and the size of this queue.
802 *
803 * <p>If this queue fits in the specified array with room to spare
804 * (i.e., the array has more elements than this queue), the element in
805 * the array immediately following the end of the queue is set to
806 * {@code null}.
807 *
808 * <p>Like the {@link #toArray()} method, this method acts as bridge between
809 * array-based and collection-based APIs. Further, this method allows
810 * precise control over the runtime type of the output array, and may,
811 * under certain circumstances, be used to save allocation costs.
812 *
813 * <p>Suppose {@code x} is a queue known to contain only strings.
814 * The following code can be used to dump the queue into a newly
815 * allocated array of {@code String}:
816 *
817 * <pre>
818 * String[] y = x.toArray(new String[0]);</pre>
819 *
820 * Note that {@code toArray(new Object[0])} is identical in function to
821 * {@code toArray()}.
822 *
823 * @param a the array into which the elements of the queue are to
824 * be stored, if it is big enough; otherwise, a new array of the
825 * same runtime type is allocated for this purpose
826 * @return an array containing all of the elements in this queue
827 * @throws ArrayStoreException if the runtime type of the specified array
828 * is not a supertype of the runtime type of every element in
829 * this queue
830 * @throws NullPointerException if the specified array is null
831 */
832 public <T> T[] toArray(T[] a) {
833 final ReentrantLock lock = this.lock;
834 lock.lock();
835 try {
836 int n = size;
837 if (a.length < n)
838 // Make a new array of a's runtime type, but my contents:
839 return (T[]) Arrays.copyOf(queue, size, a.getClass());
840 System.arraycopy(queue, 0, a, 0, n);
841 if (a.length > n)
842 a[n] = null;
843 return a;
844 } finally {
845 lock.unlock();
846 }
847 }
848
849 /**
850 * Returns an iterator over the elements in this queue. The
851 * iterator does not return the elements in any particular order.
852 *
853 * <p>The returned iterator is a "weakly consistent" iterator that
854 * will never throw {@link java.util.ConcurrentModificationException
855 * ConcurrentModificationException}, and guarantees to traverse
856 * elements as they existed upon construction of the iterator, and
857 * may (but is not guaranteed to) reflect any modifications
858 * subsequent to construction.
859 *
860 * @return an iterator over the elements in this queue
861 */
862 public Iterator<E> iterator() {
863 return new Itr(toArray());
864 }
865
866 /**
867 * Snapshot iterator that works off copy of underlying q array.
868 */
869 final class Itr implements Iterator<E> {
870 final Object[] array; // Array of all elements
871 int cursor; // index of next element to return;
872 int lastRet; // index of last element, or -1 if no such
873
874 Itr(Object[] array) {
875 lastRet = -1;
876 this.array = array;
877 }
878
879 public boolean hasNext() {
880 return cursor < array.length;
881 }
882
883 public E next() {
884 if (cursor >= array.length)
885 throw new NoSuchElementException();
886 lastRet = cursor;
887 return (E)array[cursor++];
888 }
889
890 public void remove() {
891 if (lastRet < 0)
892 throw new IllegalStateException();
893 removeEQ(array[lastRet]);
894 lastRet = -1;
895 }
896 }
897
898 /**
899 * Saves the state to a stream (that is, serializes it). For
900 * compatibility with previous version of this class,
901 * elements are first copied to a java.util.PriorityQueue,
902 * which is then serialized.
903 */
904 private void writeObject(java.io.ObjectOutputStream s)
905 throws java.io.IOException {
906 lock.lock();
907 try {
908 int n = size; // avoid zero capacity argument
909 q = new PriorityQueue<E>(n == 0 ? 1 : n, comparator);
910 q.addAll(this);
911 s.defaultWriteObject();
912 } finally {
913 q = null;
914 lock.unlock();
915 }
916 }
917
918 /**
919 * Reconstitutes the {@code PriorityBlockingQueue} instance from a stream
920 * (that is, deserializes it).
921 *
922 * @param s the stream
923 */
924 private void readObject(java.io.ObjectInputStream s)
925 throws java.io.IOException, ClassNotFoundException {
926 try {
927 s.defaultReadObject();
928 this.queue = new Object[q.size()];
929 comparator = q.comparator();
930 addAll(q);
931 } finally {
932 q = null;
933 }
934 }
935
936 // Unsafe mechanics
937 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
938 private static final long allocationSpinLockOffset =
939 objectFieldOffset(UNSAFE, "allocationSpinLock",
940 PriorityBlockingQueue.class);
941
942 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
943 String field, Class<?> klazz) {
944 try {
945 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
946 } catch (NoSuchFieldException e) {
947 // Convert Exception to corresponding Error
948 NoSuchFieldError error = new NoSuchFieldError(field);
949 error.initCause(e);
950 throw error;
951 }
952 }
953
954 }