ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.144
Committed: Thu Jun 11 17:17:45 2020 UTC (3 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.143: +3 -1 lines
Log Message:
restore historic comment and parens

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