ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.128
Committed: Sat May 6 06:49:46 2017 UTC (7 years ago) by jsr166
Branch: MAIN
Changes since 1.127: +1 -1 lines
Log Message:
8177789: fix collections framework links to point to java.util package doc

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