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, 10 months ago) by dl
Branch: MAIN
Changes since 1.99: +14 -0 lines
Log Message:
Mesh with PriorityQueue update

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.33 * Expert Group and released to the public domain, as explained at
4 jsr166 1.71 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 tim 1.13
9 jsr166 1.84 import java.util.concurrent.locks.Condition;
10     import java.util.concurrent.locks.ReentrantLock;
11 dl 1.86 import java.util.AbstractQueue;
12     import java.util.Arrays;
13     import java.util.Collection;
14 dl 1.92 import java.util.Collections;
15 dl 1.86 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 dl 1.91 import java.util.function.Consumer;
24 tim 1.1
25     /**
26 dl 1.25 * 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 dl 1.24 * unbounded, attempted additions may fail due to resource exhaustion
30 jsr166 1.63 * (causing {@code OutOfMemoryError}). This class does not permit
31     * {@code null} elements. A priority queue relying on {@linkplain
32 jsr166 1.42 * Comparable natural ordering} also does not permit insertion of
33     * non-comparable objects (doing so results in
34 jsr166 1.63 * {@code ClassCastException}).
35 dl 1.20 *
36 dl 1.38 * <p>This class and its iterator implement all of the
37     * <em>optional</em> methods of the {@link Collection} and {@link
38 dl 1.41 * 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 jsr166 1.63 * {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo}
43 dl 1.41 * 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 jsr166 1.63 * {@code new FIFOEntry(anEntry)} instead of a plain entry object.
53 dl 1.41 *
54 jsr166 1.56 * <pre> {@code
55     * class FIFOEntry<E extends Comparable<? super E>>
56     * implements Comparable<FIFOEntry<E>> {
57 jsr166 1.58 * static final AtomicLong seq = new AtomicLong(0);
58 dl 1.41 * 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 jsr166 1.56 * public int compareTo(FIFOEntry<E> other) {
66 dl 1.41 * int res = entry.compareTo(other.entry);
67 jsr166 1.56 * if (res == 0 && other.entry != this.entry)
68     * res = (seqNum < other.seqNum ? -1 : 1);
69 dl 1.41 * return res;
70     * }
71 jsr166 1.56 * }}</pre>
72 dl 1.20 *
73 dl 1.35 * <p>This class is a member of the
74 jsr166 1.53 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
75 dl 1.35 * Java Collections Framework</a>.
76     *
77 dl 1.6 * @since 1.5
78     * @author Doug Lea
79 dl 1.29 * @param <E> the type of elements held in this collection
80 dl 1.28 */
81 jsr166 1.82 @SuppressWarnings("unchecked")
82 dl 1.5 public class PriorityBlockingQueue<E> extends AbstractQueue<E>
83 dl 1.15 implements BlockingQueue<E>, java.io.Serializable {
84 dl 1.21 private static final long serialVersionUID = 5595510919245408276L;
85 tim 1.1
86 dl 1.59 /*
87 dl 1.66 * 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 jsr166 1.77 * serialization, which maintains compatibility at the expense of
99 dl 1.66 * transiently doubling overhead.
100 dl 1.59 */
101    
102     /**
103     * Default array capacity.
104     */
105     private static final int DEFAULT_INITIAL_CAPACITY = 11;
106    
107     /**
108 dl 1.66 * 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 dl 1.59 * 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 dl 1.66 private transient int size;
129 dl 1.59
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 dl 1.66 * Lock used for all public operations
138 dl 1.59 */
139 dl 1.66 private final ReentrantLock lock;
140 dl 1.59
141     /**
142 dl 1.66 * Condition for blocking when empty
143 dl 1.59 */
144 dl 1.66 private final Condition notEmpty;
145 dl 1.5
146 dl 1.2 /**
147 dl 1.59 * Spinlock for allocation, acquired via CAS.
148     */
149     private transient volatile int allocationSpinLock;
150    
151     /**
152 dl 1.66 * 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 jsr166 1.72 private PriorityQueue<E> q;
157 dl 1.66
158     /**
159 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the default
160 jsr166 1.42 * initial capacity (11) that orders its elements according to
161     * their {@linkplain Comparable natural ordering}.
162 dl 1.2 */
163     public PriorityBlockingQueue() {
164 dl 1.59 this(DEFAULT_INITIAL_CAPACITY, null);
165 dl 1.2 }
166    
167     /**
168 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the specified
169 jsr166 1.42 * initial capacity that orders its elements according to their
170     * {@linkplain Comparable natural ordering}.
171 dl 1.2 *
172 jsr166 1.42 * @param initialCapacity the initial capacity for this priority queue
173 jsr166 1.63 * @throws IllegalArgumentException if {@code initialCapacity} is less
174 jsr166 1.52 * than 1
175 dl 1.2 */
176     public PriorityBlockingQueue(int initialCapacity) {
177 dl 1.59 this(initialCapacity, null);
178 dl 1.2 }
179    
180     /**
181 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the specified initial
182 jsr166 1.39 * capacity that orders its elements according to the specified
183     * comparator.
184 dl 1.2 *
185 jsr166 1.42 * @param initialCapacity the initial capacity for this priority queue
186 jsr166 1.52 * @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 jsr166 1.63 * @throws IllegalArgumentException if {@code initialCapacity} is less
190 jsr166 1.52 * than 1
191 dl 1.2 */
192 tim 1.13 public PriorityBlockingQueue(int initialCapacity,
193 dholmes 1.14 Comparator<? super E> comparator) {
194 dl 1.59 if (initialCapacity < 1)
195     throw new IllegalArgumentException();
196 dl 1.66 this.lock = new ReentrantLock();
197     this.notEmpty = lock.newCondition();
198     this.comparator = comparator;
199 dl 1.59 this.queue = new Object[initialCapacity];
200 dl 1.2 }
201    
202     /**
203 dl 1.100 * 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 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} containing the elements
218 jsr166 1.52 * in the specified collection. If the specified collection is a
219 jsr166 1.99 * {@link SortedSet} or a {@link PriorityQueue}, this
220 jsr166 1.52 * 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 dl 1.2 *
224 jsr166 1.52 * @param c the collection whose elements are to be placed
225     * into this priority queue
226 dl 1.2 * @throws ClassCastException if elements of the specified collection
227     * cannot be compared to one another according to the priority
228 jsr166 1.52 * queue's ordering
229 jsr166 1.42 * @throws NullPointerException if the specified collection or any
230     * of its elements are null
231 dl 1.2 */
232 dholmes 1.14 public PriorityBlockingQueue(Collection<? extends E> c) {
233 dl 1.66 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 dl 1.59 if (c instanceof SortedSet<?>) {
238     SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
239     this.comparator = (Comparator<? super E>) ss.comparator();
240 dl 1.66 heapify = false;
241 dl 1.59 }
242     else if (c instanceof PriorityBlockingQueue<?>) {
243 jsr166 1.61 PriorityBlockingQueue<? extends E> pq =
244 dl 1.59 (PriorityBlockingQueue<? extends E>) c;
245     this.comparator = (Comparator<? super E>) pq.comparator();
246 jsr166 1.67 screen = false;
247 dl 1.66 if (pq.getClass() == PriorityBlockingQueue.class) // exact match
248     heapify = false;
249 dl 1.59 }
250     Object[] a = c.toArray();
251 dl 1.66 int n = a.length;
252 dl 1.59 // If c.toArray incorrectly doesn't return Object[], copy it.
253     if (a.getClass() != Object[].class)
254 dl 1.66 a = Arrays.copyOf(a, n, Object[].class);
255     if (screen && (n == 1 || this.comparator != null)) {
256     for (int i = 0; i < n; ++i)
257 dl 1.59 if (a[i] == null)
258     throw new NullPointerException();
259 dl 1.66 }
260 dl 1.59 this.queue = a;
261 dl 1.66 this.size = n;
262     if (heapify)
263     heapify();
264 dl 1.59 }
265    
266     /**
267 dl 1.66 * 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 jsr166 1.67 *
272 dl 1.66 * @param array the heap array
273     * @param oldCap the length of the array
274 dl 1.59 */
275 dl 1.66 private void tryGrow(Object[] array, int oldCap) {
276 dl 1.59 lock.unlock(); // must release and then re-acquire main lock
277     Object[] newArray = null;
278     if (allocationSpinLock == 0 &&
279 jsr166 1.61 UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
280 dl 1.59 0, 1)) {
281     try {
282     int newCap = oldCap + ((oldCap < 64) ?
283 dl 1.66 (oldCap + 2) : // grow faster if small
284 dl 1.59 (oldCap >> 1));
285 dl 1.66 if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
286     int minCap = oldCap + 1;
287 dl 1.59 if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
288     throw new OutOfMemoryError();
289     newCap = MAX_ARRAY_SIZE;
290     }
291 dl 1.66 if (newCap > oldCap && queue == array)
292 dl 1.59 newArray = new Object[newCap];
293     } finally {
294     allocationSpinLock = 0;
295     }
296     }
297 dl 1.66 if (newArray == null) // back off if another thread is allocating
298 dl 1.59 Thread.yield();
299     lock.lock();
300     if (newArray != null && queue == array) {
301     queue = newArray;
302 dl 1.66 System.arraycopy(array, 0, newArray, 0, oldCap);
303 dl 1.59 }
304     }
305    
306     /**
307 jsr166 1.62 * Mechanics for poll(). Call only while holding lock.
308 dl 1.59 */
309 jsr166 1.79 private E dequeue() {
310 dl 1.66 int n = size - 1;
311     if (n < 0)
312 jsr166 1.74 return null;
313 dl 1.66 else {
314     Object[] array = queue;
315 jsr166 1.74 E result = (E) array[0];
316 dl 1.66 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 jsr166 1.67 else
322 dl 1.66 siftDownUsingComparator(0, x, array, n, cmp);
323     size = n;
324 jsr166 1.74 return result;
325 dl 1.59 }
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 dl 1.66 * These methods are static, with heap state as arguments, to
337     * simplify use in light of possible comparator exceptions.
338 dl 1.59 *
339     * @param k the position to fill
340     * @param x the item to insert
341 dl 1.66 * @param array the heap array
342 dl 1.59 */
343 dl 1.66 private static <T> void siftUpComparable(int k, T x, Object[] array) {
344     Comparable<? super T> key = (Comparable<? super T>) x;
345 dl 1.59 while (k > 0) {
346     int parent = (k - 1) >>> 1;
347 dl 1.66 Object e = array[parent];
348     if (key.compareTo((T) e) >= 0)
349 dl 1.59 break;
350 dl 1.66 array[k] = e;
351 dl 1.59 k = parent;
352     }
353 dl 1.66 array[k] = key;
354 dl 1.59 }
355    
356 dl 1.66 private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
357     Comparator<? super T> cmp) {
358 dl 1.59 while (k > 0) {
359     int parent = (k - 1) >>> 1;
360 dl 1.66 Object e = array[parent];
361     if (cmp.compare(x, (T) e) >= 0)
362 dl 1.59 break;
363 dl 1.66 array[k] = e;
364 dl 1.59 k = parent;
365     }
366 dl 1.66 array[k] = x;
367 dl 1.59 }
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 dl 1.66 * @param array the heap array
377     * @param n heap size
378 dl 1.59 */
379 jsr166 1.67 private static <T> void siftDownComparable(int k, T x, Object[] array,
380 dl 1.66 int n) {
381 dl 1.85 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 dl 1.59 }
398     }
399    
400 dl 1.66 private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
401     int n,
402     Comparator<? super T> cmp) {
403 dl 1.85 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 dl 1.59 }
418 dl 1.7 }
419    
420 dholmes 1.10 /**
421 dl 1.59 * 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 dl 1.66 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 dl 1.59 }
438    
439     /**
440 jsr166 1.42 * Inserts the specified element into this priority queue.
441     *
442 jsr166 1.40 * @param e the element to add
443 jsr166 1.63 * @return {@code true} (as specified by {@link Collection#add})
444 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
445 jsr166 1.42 * 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 dholmes 1.10 */
449 jsr166 1.40 public boolean add(E e) {
450 jsr166 1.42 return offer(e);
451 dl 1.5 }
452    
453 dholmes 1.16 /**
454 dl 1.24 * Inserts the specified element into this priority queue.
455 jsr166 1.64 * As the queue is unbounded, this method will never return {@code false}.
456 dholmes 1.16 *
457 jsr166 1.40 * @param e the element to add
458 jsr166 1.63 * @return {@code true} (as specified by {@link Queue#offer})
459 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
460 jsr166 1.42 * 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 dholmes 1.16 */
464 jsr166 1.40 public boolean offer(E e) {
465 dl 1.59 if (e == null)
466     throw new NullPointerException();
467 dl 1.31 final ReentrantLock lock = this.lock;
468 dl 1.5 lock.lock();
469 dl 1.66 int n, cap;
470 dl 1.59 Object[] array;
471 dl 1.66 while ((n = size) >= (cap = (array = queue).length))
472     tryGrow(array, cap);
473 dl 1.59 try {
474 dl 1.66 Comparator<? super E> cmp = comparator;
475     if (cmp == null)
476     siftUpComparable(n, e, array);
477 dl 1.59 else
478 dl 1.66 siftUpUsingComparator(n, e, array, cmp);
479     size = n + 1;
480 dl 1.5 notEmpty.signal();
481 tim 1.19 } finally {
482 tim 1.13 lock.unlock();
483 dl 1.5 }
484 dl 1.59 return true;
485 dl 1.5 }
486    
487 dholmes 1.16 /**
488 jsr166 1.64 * Inserts the specified element into this priority queue.
489     * As the queue is unbounded, this method will never block.
490 jsr166 1.42 *
491 jsr166 1.40 * @param e the element to add
492 jsr166 1.42 * @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 dholmes 1.16 */
497 jsr166 1.40 public void put(E e) {
498     offer(e); // never need to block
499 dl 1.5 }
500    
501 dholmes 1.16 /**
502 jsr166 1.64 * 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 jsr166 1.42 *
506 jsr166 1.40 * @param e the element to add
507 dholmes 1.16 * @param timeout This parameter is ignored as the method never blocks
508     * @param unit This parameter is ignored as the method never blocks
509 jsr166 1.65 * @return {@code true} (as specified by
510     * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
511 jsr166 1.42 * @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 dholmes 1.16 */
516 jsr166 1.40 public boolean offer(E e, long timeout, TimeUnit unit) {
517     return offer(e); // never need to block
518 dl 1.5 }
519    
520 jsr166 1.42 public E poll() {
521     final ReentrantLock lock = this.lock;
522     lock.lock();
523     try {
524 jsr166 1.79 return dequeue();
525 jsr166 1.42 } finally {
526     lock.unlock();
527     }
528     }
529    
530 dl 1.5 public E take() throws InterruptedException {
531 dl 1.31 final ReentrantLock lock = this.lock;
532 dl 1.5 lock.lockInterruptibly();
533 dl 1.66 E result;
534 dl 1.5 try {
535 jsr166 1.79 while ( (result = dequeue()) == null)
536 jsr166 1.55 notEmpty.await();
537 tim 1.19 } finally {
538 dl 1.5 lock.unlock();
539     }
540 dl 1.59 return result;
541 dl 1.5 }
542    
543     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
544 dholmes 1.10 long nanos = unit.toNanos(timeout);
545 dl 1.31 final ReentrantLock lock = this.lock;
546 dl 1.5 lock.lockInterruptibly();
547 dl 1.66 E result;
548 dl 1.5 try {
549 jsr166 1.79 while ( (result = dequeue()) == null && nanos > 0)
550 jsr166 1.55 nanos = notEmpty.awaitNanos(nanos);
551 tim 1.19 } finally {
552 dl 1.5 lock.unlock();
553     }
554 dl 1.59 return result;
555 dl 1.5 }
556    
557     public E peek() {
558 dl 1.31 final ReentrantLock lock = this.lock;
559 dl 1.5 lock.lock();
560     try {
561 jsr166 1.74 return (size == 0) ? null : (E) queue[0];
562 tim 1.19 } finally {
563 tim 1.13 lock.unlock();
564 dl 1.5 }
565     }
566 jsr166 1.61
567 jsr166 1.42 /**
568     * Returns the comparator used to order the elements in this queue,
569 jsr166 1.63 * or {@code null} if this queue uses the {@linkplain Comparable
570 jsr166 1.42 * natural ordering} of its elements.
571     *
572     * @return the comparator used to order the elements in this queue,
573 jsr166 1.63 * or {@code null} if this queue uses the natural
574 jsr166 1.52 * ordering of its elements
575 jsr166 1.42 */
576     public Comparator<? super E> comparator() {
577 dl 1.59 return comparator;
578 jsr166 1.42 }
579    
580 dl 1.5 public int size() {
581 dl 1.31 final ReentrantLock lock = this.lock;
582 dl 1.5 lock.lock();
583     try {
584 jsr166 1.68 return size;
585 tim 1.19 } finally {
586 dl 1.5 lock.unlock();
587     }
588     }
589    
590     /**
591 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
592     * a {@code PriorityBlockingQueue} is not capacity constrained.
593     * @return {@code Integer.MAX_VALUE} always
594 dl 1.5 */
595     public int remainingCapacity() {
596     return Integer.MAX_VALUE;
597     }
598    
599 dl 1.59 private int indexOf(Object o) {
600     if (o != null) {
601 dl 1.66 Object[] array = queue;
602     int n = size;
603     for (int i = 0; i < n; i++)
604     if (o.equals(array[i]))
605 dl 1.59 return i;
606     }
607     return -1;
608     }
609    
610     /**
611     * Removes the ith element from queue.
612     */
613     private void removeAt(int i) {
614 dl 1.66 Object[] array = queue;
615     int n = size - 1;
616     if (n == i) // removed last element
617     array[i] = null;
618 dl 1.59 else {
619 dl 1.66 E moved = (E) array[n];
620     array[n] = null;
621     Comparator<? super E> cmp = comparator;
622 jsr166 1.67 if (cmp == null)
623 dl 1.66 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 dl 1.59 }
633 dl 1.66 size = n;
634 dl 1.59 }
635    
636 dl 1.37 /**
637 jsr166 1.42 * Removes a single instance of the specified element from this queue,
638 jsr166 1.52 * 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 jsr166 1.42 *
644     * @param o element to be removed from this queue, if present
645 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
646 dl 1.37 */
647 dholmes 1.14 public boolean remove(Object o) {
648 dl 1.31 final ReentrantLock lock = this.lock;
649 dl 1.5 lock.lock();
650     try {
651 dl 1.59 int i = indexOf(o);
652 jsr166 1.78 if (i == -1)
653     return false;
654     removeAt(i);
655     return true;
656 dl 1.59 } finally {
657     lock.unlock();
658     }
659     }
660    
661     /**
662     * Identity-based version for use in Itr.remove
663     */
664 jsr166 1.80 void removeEQ(Object o) {
665 dl 1.59 final ReentrantLock lock = this.lock;
666     lock.lock();
667     try {
668 dl 1.66 Object[] array = queue;
669 jsr166 1.78 for (int i = 0, n = size; i < n; i++) {
670 dl 1.66 if (o == array[i]) {
671 dl 1.59 removeAt(i);
672     break;
673     }
674     }
675 tim 1.19 } finally {
676 dl 1.5 lock.unlock();
677     }
678     }
679    
680 jsr166 1.42 /**
681 jsr166 1.52 * 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 jsr166 1.42 *
685     * @param o object to be checked for containment in this queue
686 jsr166 1.63 * @return {@code true} if this queue contains the specified element
687 jsr166 1.42 */
688 dholmes 1.14 public boolean contains(Object o) {
689 dl 1.31 final ReentrantLock lock = this.lock;
690 dl 1.5 lock.lock();
691     try {
692 jsr166 1.78 return indexOf(o) != -1;
693 tim 1.19 } finally {
694 dl 1.5 lock.unlock();
695     }
696     }
697    
698 jsr166 1.42 /**
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 jsr166 1.43 *
706 jsr166 1.42 * <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 dl 1.5 public Object[] toArray() {
712 dl 1.31 final ReentrantLock lock = this.lock;
713 dl 1.5 lock.lock();
714     try {
715 dl 1.59 return Arrays.copyOf(queue, size);
716 tim 1.19 } finally {
717 dl 1.5 lock.unlock();
718     }
719     }
720    
721     public String toString() {
722 dl 1.31 final ReentrantLock lock = this.lock;
723 dl 1.5 lock.lock();
724     try {
725 dl 1.59 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 jsr166 1.74 Object e = queue[i];
732 dl 1.59 sb.append(e == this ? "(this Collection)" : e);
733     if (i != n - 1)
734     sb.append(',').append(' ');
735     }
736     return sb.append(']').toString();
737 tim 1.19 } finally {
738 dl 1.5 lock.unlock();
739     }
740     }
741    
742 jsr166 1.42 /**
743     * @throws UnsupportedOperationException {@inheritDoc}
744     * @throws ClassCastException {@inheritDoc}
745     * @throws NullPointerException {@inheritDoc}
746     * @throws IllegalArgumentException {@inheritDoc}
747     */
748 dl 1.26 public int drainTo(Collection<? super E> c) {
749 jsr166 1.76 return drainTo(c, Integer.MAX_VALUE);
750 dl 1.26 }
751    
752 jsr166 1.42 /**
753     * @throws UnsupportedOperationException {@inheritDoc}
754     * @throws ClassCastException {@inheritDoc}
755     * @throws NullPointerException {@inheritDoc}
756     * @throws IllegalArgumentException {@inheritDoc}
757     */
758 dl 1.26 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 dl 1.31 final ReentrantLock lock = this.lock;
766 dl 1.26 lock.lock();
767     try {
768 jsr166 1.76 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 jsr166 1.79 dequeue();
772 dl 1.26 }
773     return n;
774     } finally {
775     lock.unlock();
776     }
777     }
778    
779 dl 1.17 /**
780 dl 1.37 * Atomically removes all of the elements from this queue.
781 dl 1.17 * The queue will be empty after this call returns.
782     */
783     public void clear() {
784 dl 1.31 final ReentrantLock lock = this.lock;
785 dl 1.17 lock.lock();
786     try {
787 dl 1.66 Object[] array = queue;
788     int n = size;
789 dl 1.59 size = 0;
790 dl 1.66 for (int i = 0; i < n; i++)
791     array[i] = null;
792 tim 1.19 } finally {
793 dl 1.17 lock.unlock();
794     }
795     }
796    
797 jsr166 1.42 /**
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 jsr166 1.63 * {@code null}.
809 jsr166 1.42 *
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 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
816 jsr166 1.42 * The following code can be used to dump the queue into a newly
817 jsr166 1.63 * allocated array of {@code String}:
818 jsr166 1.42 *
819 jsr166 1.73 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
820 jsr166 1.42 *
821 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
822     * {@code toArray()}.
823 jsr166 1.42 *
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 dl 1.5 public <T> T[] toArray(T[] a) {
834 dl 1.31 final ReentrantLock lock = this.lock;
835 dl 1.5 lock.lock();
836     try {
837 dl 1.66 int n = size;
838     if (a.length < n)
839 dl 1.59 // Make a new array of a's runtime type, but my contents:
840     return (T[]) Arrays.copyOf(queue, size, a.getClass());
841 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
842     if (a.length > n)
843     a[n] = null;
844 dl 1.59 return a;
845 tim 1.19 } finally {
846 dl 1.5 lock.unlock();
847     }
848     }
849    
850 dholmes 1.16 /**
851 dl 1.23 * Returns an iterator over the elements in this queue. The
852     * iterator does not return the elements in any particular order.
853 jsr166 1.69 *
854     * <p>The returned iterator is a "weakly consistent" iterator that
855     * will never throw {@link java.util.ConcurrentModificationException
856 dl 1.51 * 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 dholmes 1.16 *
861 jsr166 1.42 * @return an iterator over the elements in this queue
862 dholmes 1.16 */
863 dl 1.5 public Iterator<E> iterator() {
864 dl 1.51 return new Itr(toArray());
865 dl 1.5 }
866    
867 dl 1.49 /**
868     * Snapshot iterator that works off copy of underlying q array.
869     */
870 dl 1.59 final class Itr implements Iterator<E> {
871 dl 1.49 final Object[] array; // Array of all elements
872 jsr166 1.81 int cursor; // index of next element to return
873 jsr166 1.54 int lastRet; // index of last element, or -1 if no such
874 jsr166 1.50
875 dl 1.49 Itr(Object[] array) {
876     lastRet = -1;
877     this.array = array;
878 dl 1.5 }
879    
880 tim 1.13 public boolean hasNext() {
881 dl 1.49 return cursor < array.length;
882 tim 1.13 }
883    
884     public E next() {
885 dl 1.49 if (cursor >= array.length)
886     throw new NoSuchElementException();
887     lastRet = cursor;
888     return (E)array[cursor++];
889 tim 1.13 }
890    
891     public void remove() {
892 jsr166 1.50 if (lastRet < 0)
893 jsr166 1.54 throw new IllegalStateException();
894 dl 1.59 removeEQ(array[lastRet]);
895 dl 1.49 lastRet = -1;
896 tim 1.13 }
897 dl 1.5 }
898    
899     /**
900 jsr166 1.83 * 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 jsr166 1.97 *
906     * @param s the stream
907 jsr166 1.98 * @throws java.io.IOException if an I/O error occurs
908 dl 1.5 */
909     private void writeObject(java.io.ObjectOutputStream s)
910     throws java.io.IOException {
911     lock.lock();
912     try {
913 jsr166 1.78 // avoid zero capacity argument
914     q = new PriorityQueue<E>(Math.max(size, 1), comparator);
915 dl 1.59 q.addAll(this);
916 dl 1.5 s.defaultWriteObject();
917 dl 1.66 } finally {
918 dl 1.59 q = null;
919 dl 1.5 lock.unlock();
920     }
921 tim 1.1 }
922    
923 dl 1.59 /**
924 jsr166 1.83 * Reconstitutes this queue from a stream (that is, deserializes it).
925 jsr166 1.97 * @param s the stream
926 jsr166 1.98 * @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 dl 1.59 */
930     private void readObject(java.io.ObjectInputStream s)
931     throws java.io.IOException, ClassNotFoundException {
932 jsr166 1.67 try {
933 dl 1.66 s.defaultReadObject();
934     this.queue = new Object[q.size()];
935     comparator = q.comparator();
936     addAll(q);
937 jsr166 1.67 } finally {
938 dl 1.66 q = null;
939     }
940 dl 1.59 }
941    
942 dl 1.93 // 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 dl 1.95 public void forEachRemaining(Consumer<? super E> action) {
973 dl 1.93 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 dl 1.94 public Spliterator<E> spliterator() {
1003 dl 1.93 return new PBQSpliterator<E>(this, null, 0, -1);
1004 dl 1.86 }
1005    
1006 dl 1.59 // Unsafe mechanics
1007 dl 1.70 private static final sun.misc.Unsafe UNSAFE;
1008     private static final long allocationSpinLockOffset;
1009     static {
1010 dl 1.59 try {
1011 dl 1.70 UNSAFE = sun.misc.Unsafe.getUnsafe();
1012 jsr166 1.72 Class<?> k = PriorityBlockingQueue.class;
1013 dl 1.70 allocationSpinLockOffset = UNSAFE.objectFieldOffset
1014     (k.getDeclaredField("allocationSpinLock"));
1015     } catch (Exception e) {
1016     throw new Error(e);
1017 dl 1.59 }
1018     }
1019 tim 1.1 }