ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.146
Committed: Fri Nov 27 17:42:00 2020 UTC (3 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.145: +1 -1 lines
Log Message:
Incorporate snippets code improvements from Pavel Rappo

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 dl 1.146 * static final AtomicLong seq = new AtomicLong();
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 jsr166 1.145 if (c.getClass() != java.util.ArrayList.class)
232 jsr166 1.134 es = Arrays.copyOf(es, n, Object[].class);
233 dl 1.66 if (screen && (n == 1 || this.comparator != null)) {
234 jsr166 1.134 for (Object e : es)
235     if (e == null)
236 dl 1.59 throw new NullPointerException();
237 dl 1.66 }
238 jsr166 1.135 this.queue = ensureNonEmpty(es);
239 dl 1.66 this.size = n;
240     if (heapify)
241     heapify();
242 dl 1.59 }
243    
244 jsr166 1.135 /** Ensures that queue[0] exists, helping peek() and poll(). */
245     private static Object[] ensureNonEmpty(Object[] es) {
246     return (es.length > 0) ? es : new Object[1];
247     }
248    
249 dl 1.59 /**
250 dl 1.66 * Tries to grow array to accommodate at least one more element
251     * (but normally expand by about 50%), giving up (allowing retry)
252     * on contention (which we expect to be rare). Call only while
253     * holding lock.
254 jsr166 1.67 *
255 dl 1.66 * @param array the heap array
256     * @param oldCap the length of the array
257 dl 1.59 */
258 dl 1.66 private void tryGrow(Object[] array, int oldCap) {
259 dl 1.59 lock.unlock(); // must release and then re-acquire main lock
260     Object[] newArray = null;
261     if (allocationSpinLock == 0 &&
262 dl 1.115 ALLOCATIONSPINLOCK.compareAndSet(this, 0, 1)) {
263 dl 1.59 try {
264 jsr166 1.144 int growth = (oldCap < 64)
265     ? (oldCap + 2) // grow faster if small
266     : (oldCap >> 1);
267 jsr166 1.143 int newCap = ArraysSupport.newLength(oldCap, 1, growth);
268     if (queue == array)
269 dl 1.59 newArray = new Object[newCap];
270     } finally {
271     allocationSpinLock = 0;
272     }
273     }
274 dl 1.66 if (newArray == null) // back off if another thread is allocating
275 dl 1.59 Thread.yield();
276     lock.lock();
277     if (newArray != null && queue == array) {
278     queue = newArray;
279 dl 1.66 System.arraycopy(array, 0, newArray, 0, oldCap);
280 dl 1.59 }
281     }
282    
283     /**
284 jsr166 1.62 * Mechanics for poll(). Call only while holding lock.
285 dl 1.59 */
286 jsr166 1.79 private E dequeue() {
287 jsr166 1.134 // assert lock.isHeldByCurrentThread();
288 jsr166 1.135 final Object[] es;
289     final E result;
290    
291     if ((result = (E) ((es = queue)[0])) != null) {
292     final int n;
293     final E x = (E) es[(n = --size)];
294 jsr166 1.134 es[n] = null;
295     if (n > 0) {
296 jsr166 1.135 final Comparator<? super E> cmp;
297     if ((cmp = comparator) == null)
298 jsr166 1.134 siftDownComparable(0, x, es, n);
299     else
300     siftDownUsingComparator(0, x, es, n, cmp);
301     }
302 dl 1.59 }
303 jsr166 1.135 return result;
304 dl 1.59 }
305    
306     /**
307     * Inserts item x at position k, maintaining heap invariant by
308     * promoting x up the tree until it is greater than or equal to
309     * its parent, or is the root.
310     *
311 jsr166 1.121 * To simplify and speed up coercions and comparisons, the
312 dl 1.59 * Comparable and Comparator versions are separated into different
313     * methods that are otherwise identical. (Similarly for siftDown.)
314     *
315     * @param k the position to fill
316     * @param x the item to insert
317 jsr166 1.134 * @param es the heap array
318 dl 1.59 */
319 jsr166 1.134 private static <T> void siftUpComparable(int k, T x, Object[] es) {
320 dl 1.66 Comparable<? super T> key = (Comparable<? super T>) x;
321 dl 1.59 while (k > 0) {
322     int parent = (k - 1) >>> 1;
323 jsr166 1.134 Object e = es[parent];
324 dl 1.66 if (key.compareTo((T) e) >= 0)
325 dl 1.59 break;
326 jsr166 1.134 es[k] = e;
327 dl 1.59 k = parent;
328     }
329 jsr166 1.134 es[k] = key;
330 dl 1.59 }
331    
332 jsr166 1.134 private static <T> void siftUpUsingComparator(
333     int k, T x, Object[] es, Comparator<? super T> cmp) {
334 dl 1.59 while (k > 0) {
335     int parent = (k - 1) >>> 1;
336 jsr166 1.134 Object e = es[parent];
337 dl 1.66 if (cmp.compare(x, (T) e) >= 0)
338 dl 1.59 break;
339 jsr166 1.134 es[k] = e;
340 dl 1.59 k = parent;
341     }
342 jsr166 1.134 es[k] = x;
343 dl 1.59 }
344    
345     /**
346     * Inserts item x at position k, maintaining heap invariant by
347     * demoting x down the tree repeatedly until it is less than or
348     * equal to its children or is a leaf.
349     *
350     * @param k the position to fill
351     * @param x the item to insert
352 jsr166 1.134 * @param es the heap array
353 dl 1.66 * @param n heap size
354 dl 1.59 */
355 jsr166 1.134 private static <T> void siftDownComparable(int k, T x, Object[] es, int n) {
356     // assert n > 0;
357     Comparable<? super T> key = (Comparable<? super T>)x;
358     int half = n >>> 1; // loop while a non-leaf
359     while (k < half) {
360     int child = (k << 1) + 1; // assume left child is least
361     Object c = es[child];
362     int right = child + 1;
363     if (right < n &&
364     ((Comparable<? super T>) c).compareTo((T) es[right]) > 0)
365     c = es[child = right];
366     if (key.compareTo((T) c) <= 0)
367     break;
368     es[k] = c;
369     k = child;
370 dl 1.59 }
371 jsr166 1.134 es[k] = key;
372 dl 1.59 }
373    
374 jsr166 1.134 private static <T> void siftDownUsingComparator(
375     int k, T x, Object[] es, int n, Comparator<? super T> cmp) {
376     // assert n > 0;
377     int half = n >>> 1;
378     while (k < half) {
379     int child = (k << 1) + 1;
380     Object c = es[child];
381     int right = child + 1;
382     if (right < n && cmp.compare((T) c, (T) es[right]) > 0)
383     c = es[child = right];
384     if (cmp.compare(x, (T) c) <= 0)
385     break;
386     es[k] = c;
387     k = child;
388 dl 1.59 }
389 jsr166 1.134 es[k] = x;
390 dl 1.7 }
391    
392 dholmes 1.10 /**
393 dl 1.59 * Establishes the heap invariant (described above) in the entire tree,
394     * assuming nothing about the order of the elements prior to the call.
395 jsr166 1.118 * This classic algorithm due to Floyd (1964) is known to be O(size).
396 dl 1.59 */
397     private void heapify() {
398 jsr166 1.134 final Object[] es = queue;
399 jsr166 1.127 int n = size, i = (n >>> 1) - 1;
400 jsr166 1.135 final Comparator<? super E> cmp;
401     if ((cmp = comparator) == null)
402 jsr166 1.127 for (; i >= 0; i--)
403 jsr166 1.134 siftDownComparable(i, (E) es[i], es, n);
404     else
405 jsr166 1.127 for (; i >= 0; i--)
406 jsr166 1.134 siftDownUsingComparator(i, (E) es[i], es, n, cmp);
407 dl 1.59 }
408    
409     /**
410 jsr166 1.42 * Inserts the specified element into this priority queue.
411     *
412 jsr166 1.40 * @param e the element to add
413 jsr166 1.63 * @return {@code true} (as specified by {@link Collection#add})
414 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
415 jsr166 1.42 * with elements currently in the priority queue according to the
416     * priority queue's ordering
417     * @throws NullPointerException if the specified element is null
418 dholmes 1.10 */
419 jsr166 1.40 public boolean add(E e) {
420 jsr166 1.42 return offer(e);
421 dl 1.5 }
422    
423 dholmes 1.16 /**
424 dl 1.24 * Inserts the specified element into this priority queue.
425 jsr166 1.64 * As the queue is unbounded, this method will never return {@code false}.
426 dholmes 1.16 *
427 jsr166 1.40 * @param e the element to add
428 jsr166 1.63 * @return {@code true} (as specified by {@link Queue#offer})
429 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
430 jsr166 1.42 * with elements currently in the priority queue according to the
431     * priority queue's ordering
432     * @throws NullPointerException if the specified element is null
433 dholmes 1.16 */
434 jsr166 1.40 public boolean offer(E e) {
435 dl 1.59 if (e == null)
436     throw new NullPointerException();
437 dl 1.31 final ReentrantLock lock = this.lock;
438 dl 1.5 lock.lock();
439 dl 1.66 int n, cap;
440 jsr166 1.138 Object[] es;
441     while ((n = size) >= (cap = (es = queue).length))
442     tryGrow(es, cap);
443 dl 1.59 try {
444 jsr166 1.135 final Comparator<? super E> cmp;
445     if ((cmp = comparator) == null)
446 jsr166 1.138 siftUpComparable(n, e, es);
447 dl 1.59 else
448 jsr166 1.138 siftUpUsingComparator(n, e, es, cmp);
449 dl 1.66 size = n + 1;
450 dl 1.5 notEmpty.signal();
451 tim 1.19 } finally {
452 tim 1.13 lock.unlock();
453 dl 1.5 }
454 dl 1.59 return true;
455 dl 1.5 }
456    
457 dholmes 1.16 /**
458 jsr166 1.64 * Inserts the specified element into this priority queue.
459     * As the queue is unbounded, this method will never block.
460 jsr166 1.42 *
461 jsr166 1.40 * @param e the element to add
462 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
463     * with elements currently in the priority queue according to the
464     * priority queue's ordering
465     * @throws NullPointerException if the specified element is null
466 dholmes 1.16 */
467 jsr166 1.40 public void put(E e) {
468     offer(e); // never need to block
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 or
474     * return {@code false}.
475 jsr166 1.42 *
476 jsr166 1.40 * @param e the element to add
477 dholmes 1.16 * @param timeout This parameter is ignored as the method never blocks
478     * @param unit This parameter is ignored as the method never blocks
479 jsr166 1.65 * @return {@code true} (as specified by
480     * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
481 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
482     * with elements currently in the priority queue according to the
483     * priority queue's ordering
484     * @throws NullPointerException if the specified element is null
485 dholmes 1.16 */
486 jsr166 1.40 public boolean offer(E e, long timeout, TimeUnit unit) {
487     return offer(e); // never need to block
488 dl 1.5 }
489    
490 jsr166 1.42 public E poll() {
491     final ReentrantLock lock = this.lock;
492     lock.lock();
493     try {
494 jsr166 1.79 return dequeue();
495 jsr166 1.42 } finally {
496     lock.unlock();
497     }
498     }
499    
500 dl 1.5 public E take() throws InterruptedException {
501 dl 1.31 final ReentrantLock lock = this.lock;
502 dl 1.5 lock.lockInterruptibly();
503 dl 1.66 E result;
504 dl 1.5 try {
505 jsr166 1.79 while ( (result = dequeue()) == null)
506 jsr166 1.55 notEmpty.await();
507 tim 1.19 } finally {
508 dl 1.5 lock.unlock();
509     }
510 dl 1.59 return result;
511 dl 1.5 }
512    
513     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
514 dholmes 1.10 long nanos = unit.toNanos(timeout);
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 && nanos > 0)
520 jsr166 1.55 nanos = notEmpty.awaitNanos(nanos);
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 peek() {
528 dl 1.31 final ReentrantLock lock = this.lock;
529 dl 1.5 lock.lock();
530     try {
531 jsr166 1.135 return (E) queue[0];
532 tim 1.19 } finally {
533 tim 1.13 lock.unlock();
534 dl 1.5 }
535     }
536 jsr166 1.61
537 jsr166 1.42 /**
538     * Returns the comparator used to order the elements in this queue,
539 jsr166 1.63 * or {@code null} if this queue uses the {@linkplain Comparable
540 jsr166 1.42 * natural ordering} of its elements.
541     *
542     * @return the comparator used to order the elements in this queue,
543 jsr166 1.63 * or {@code null} if this queue uses the natural
544 jsr166 1.52 * ordering of its elements
545 jsr166 1.42 */
546     public Comparator<? super E> comparator() {
547 dl 1.59 return comparator;
548 jsr166 1.42 }
549    
550 dl 1.5 public int size() {
551 dl 1.31 final ReentrantLock lock = this.lock;
552 dl 1.5 lock.lock();
553     try {
554 jsr166 1.68 return size;
555 tim 1.19 } finally {
556 dl 1.5 lock.unlock();
557     }
558     }
559    
560     /**
561 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
562     * a {@code PriorityBlockingQueue} is not capacity constrained.
563     * @return {@code Integer.MAX_VALUE} always
564 dl 1.5 */
565     public int remainingCapacity() {
566     return Integer.MAX_VALUE;
567     }
568    
569 dl 1.59 private int indexOf(Object o) {
570     if (o != null) {
571 jsr166 1.133 final Object[] es = queue;
572     for (int i = 0, n = size; i < n; i++)
573     if (o.equals(es[i]))
574 dl 1.59 return i;
575     }
576     return -1;
577     }
578    
579     /**
580     * Removes the ith element from queue.
581     */
582     private void removeAt(int i) {
583 jsr166 1.134 final Object[] es = queue;
584 jsr166 1.135 final int n = size - 1;
585 dl 1.66 if (n == i) // removed last element
586 jsr166 1.134 es[i] = null;
587 dl 1.59 else {
588 jsr166 1.134 E moved = (E) es[n];
589     es[n] = null;
590 jsr166 1.135 final Comparator<? super E> cmp;
591     if ((cmp = comparator) == null)
592 jsr166 1.134 siftDownComparable(i, moved, es, n);
593 dl 1.66 else
594 jsr166 1.134 siftDownUsingComparator(i, moved, es, n, cmp);
595     if (es[i] == moved) {
596 dl 1.66 if (cmp == null)
597 jsr166 1.134 siftUpComparable(i, moved, es);
598 dl 1.66 else
599 jsr166 1.134 siftUpUsingComparator(i, moved, es, cmp);
600 dl 1.66 }
601 dl 1.59 }
602 dl 1.66 size = n;
603 dl 1.59 }
604    
605 dl 1.37 /**
606 jsr166 1.42 * Removes a single instance of the specified element from this queue,
607 jsr166 1.52 * if it is present. More formally, removes an element {@code e} such
608     * that {@code o.equals(e)}, if this queue contains one or more such
609     * elements. Returns {@code true} if and only if this queue contained
610     * the specified element (or equivalently, if this queue changed as a
611     * result of the call).
612 jsr166 1.42 *
613     * @param o element to be removed from this queue, if present
614 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
615 dl 1.37 */
616 dholmes 1.14 public boolean remove(Object o) {
617 dl 1.31 final ReentrantLock lock = this.lock;
618 dl 1.5 lock.lock();
619     try {
620 dl 1.59 int i = indexOf(o);
621 jsr166 1.78 if (i == -1)
622     return false;
623     removeAt(i);
624     return true;
625 dl 1.59 } finally {
626     lock.unlock();
627     }
628     }
629    
630     /**
631 jsr166 1.112 * Identity-based version for use in Itr.remove.
632 jsr166 1.133 *
633     * @param o element to be removed from this queue, if present
634 dl 1.59 */
635 jsr166 1.133 void removeEq(Object o) {
636 dl 1.59 final ReentrantLock lock = this.lock;
637     lock.lock();
638     try {
639 jsr166 1.133 final Object[] es = queue;
640 jsr166 1.78 for (int i = 0, n = size; i < n; i++) {
641 jsr166 1.133 if (o == es[i]) {
642 dl 1.59 removeAt(i);
643     break;
644     }
645     }
646 tim 1.19 } finally {
647 dl 1.5 lock.unlock();
648     }
649     }
650    
651 jsr166 1.42 /**
652 jsr166 1.52 * Returns {@code true} if this queue contains the specified element.
653     * More formally, returns {@code true} if and only if this queue contains
654     * at least one element {@code e} such that {@code o.equals(e)}.
655 jsr166 1.42 *
656     * @param o object to be checked for containment in this queue
657 jsr166 1.63 * @return {@code true} if this queue contains the specified element
658 jsr166 1.42 */
659 dholmes 1.14 public boolean contains(Object o) {
660 dl 1.31 final ReentrantLock lock = this.lock;
661 dl 1.5 lock.lock();
662     try {
663 jsr166 1.78 return indexOf(o) != -1;
664 tim 1.19 } finally {
665 dl 1.5 lock.unlock();
666     }
667     }
668    
669     public String toString() {
670 jsr166 1.111 return Helpers.collectionToString(this);
671 dl 1.5 }
672    
673 jsr166 1.42 /**
674     * @throws UnsupportedOperationException {@inheritDoc}
675     * @throws ClassCastException {@inheritDoc}
676     * @throws NullPointerException {@inheritDoc}
677     * @throws IllegalArgumentException {@inheritDoc}
678     */
679 dl 1.26 public int drainTo(Collection<? super E> c) {
680 jsr166 1.76 return drainTo(c, Integer.MAX_VALUE);
681 dl 1.26 }
682    
683 jsr166 1.42 /**
684     * @throws UnsupportedOperationException {@inheritDoc}
685     * @throws ClassCastException {@inheritDoc}
686     * @throws NullPointerException {@inheritDoc}
687     * @throws IllegalArgumentException {@inheritDoc}
688     */
689 dl 1.26 public int drainTo(Collection<? super E> c, int maxElements) {
690 jsr166 1.124 Objects.requireNonNull(c);
691 dl 1.26 if (c == this)
692     throw new IllegalArgumentException();
693     if (maxElements <= 0)
694     return 0;
695 dl 1.31 final ReentrantLock lock = this.lock;
696 dl 1.26 lock.lock();
697     try {
698 jsr166 1.76 int n = Math.min(size, maxElements);
699     for (int i = 0; i < n; i++) {
700     c.add((E) queue[0]); // In this order, in case add() throws.
701 jsr166 1.79 dequeue();
702 dl 1.26 }
703     return n;
704     } finally {
705     lock.unlock();
706     }
707     }
708    
709 dl 1.17 /**
710 dl 1.37 * Atomically removes all of the elements from this queue.
711 dl 1.17 * The queue will be empty after this call returns.
712     */
713     public void clear() {
714 dl 1.31 final ReentrantLock lock = this.lock;
715 dl 1.17 lock.lock();
716     try {
717 jsr166 1.133 final Object[] es = queue;
718     for (int i = 0, n = size; i < n; i++)
719     es[i] = null;
720 dl 1.59 size = 0;
721 tim 1.19 } finally {
722 dl 1.17 lock.unlock();
723     }
724     }
725    
726 jsr166 1.42 /**
727 jsr166 1.110 * Returns an array containing all of the elements in this queue.
728     * The returned array elements are in no particular order.
729     *
730     * <p>The returned array will be "safe" in that no references to it are
731     * maintained by this queue. (In other words, this method must allocate
732     * a new array). The caller is thus free to modify the returned array.
733     *
734     * <p>This method acts as bridge between array-based and collection-based
735     * APIs.
736     *
737     * @return an array containing all of the elements in this queue
738     */
739     public Object[] toArray() {
740     final ReentrantLock lock = this.lock;
741     lock.lock();
742     try {
743     return Arrays.copyOf(queue, size);
744     } finally {
745     lock.unlock();
746     }
747     }
748    
749     /**
750 jsr166 1.42 * Returns an array containing all of the elements in this queue; the
751     * runtime type of the returned array is that of the specified array.
752     * The returned array elements are in no particular order.
753     * If the queue fits in the specified array, it is returned therein.
754     * Otherwise, a new array is allocated with the runtime type of the
755     * specified array and the size of this queue.
756     *
757     * <p>If this queue fits in the specified array with room to spare
758     * (i.e., the array has more elements than this queue), the element in
759     * the array immediately following the end of the queue is set to
760 jsr166 1.63 * {@code null}.
761 jsr166 1.42 *
762     * <p>Like the {@link #toArray()} method, this method acts as bridge between
763     * array-based and collection-based APIs. Further, this method allows
764     * precise control over the runtime type of the output array, and may,
765     * under certain circumstances, be used to save allocation costs.
766     *
767 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
768 jsr166 1.42 * The following code can be used to dump the queue into a newly
769 jsr166 1.63 * allocated array of {@code String}:
770 jsr166 1.42 *
771 jsr166 1.109 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
772 jsr166 1.42 *
773 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
774     * {@code toArray()}.
775 jsr166 1.42 *
776     * @param a the array into which the elements of the queue are to
777     * be stored, if it is big enough; otherwise, a new array of the
778     * same runtime type is allocated for this purpose
779     * @return an array containing all of the elements in this queue
780     * @throws ArrayStoreException if the runtime type of the specified array
781     * is not a supertype of the runtime type of every element in
782     * this queue
783     * @throws NullPointerException if the specified array is null
784     */
785 dl 1.5 public <T> T[] toArray(T[] a) {
786 dl 1.31 final ReentrantLock lock = this.lock;
787 dl 1.5 lock.lock();
788     try {
789 dl 1.66 int n = size;
790     if (a.length < n)
791 dl 1.59 // Make a new array of a's runtime type, but my contents:
792     return (T[]) Arrays.copyOf(queue, size, a.getClass());
793 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
794     if (a.length > n)
795     a[n] = null;
796 dl 1.59 return a;
797 tim 1.19 } finally {
798 dl 1.5 lock.unlock();
799     }
800     }
801    
802 dholmes 1.16 /**
803 dl 1.23 * Returns an iterator over the elements in this queue. The
804     * iterator does not return the elements in any particular order.
805 jsr166 1.69 *
806 jsr166 1.103 * <p>The returned iterator is
807     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
808 dholmes 1.16 *
809 jsr166 1.42 * @return an iterator over the elements in this queue
810 dholmes 1.16 */
811 dl 1.5 public Iterator<E> iterator() {
812 dl 1.51 return new Itr(toArray());
813 dl 1.5 }
814    
815 dl 1.49 /**
816     * Snapshot iterator that works off copy of underlying q array.
817     */
818 dl 1.59 final class Itr implements Iterator<E> {
819 dl 1.49 final Object[] array; // Array of all elements
820 jsr166 1.81 int cursor; // index of next element to return
821 jsr166 1.136 int lastRet = -1; // index of last element, or -1 if no such
822 jsr166 1.50
823 dl 1.49 Itr(Object[] array) {
824     this.array = array;
825 dl 1.5 }
826    
827 tim 1.13 public boolean hasNext() {
828 dl 1.49 return cursor < array.length;
829 tim 1.13 }
830    
831     public E next() {
832 dl 1.49 if (cursor >= array.length)
833     throw new NoSuchElementException();
834 jsr166 1.120 return (E)array[lastRet = cursor++];
835 tim 1.13 }
836    
837     public void remove() {
838 jsr166 1.50 if (lastRet < 0)
839 jsr166 1.54 throw new IllegalStateException();
840 jsr166 1.133 removeEq(array[lastRet]);
841 dl 1.49 lastRet = -1;
842 tim 1.13 }
843 jsr166 1.137
844     public void forEachRemaining(Consumer<? super E> action) {
845     Objects.requireNonNull(action);
846     final Object[] es = array;
847     int i;
848     if ((i = cursor) < es.length) {
849     lastRet = -1;
850     cursor = es.length;
851     for (; i < es.length; i++)
852     action.accept((E) es[i]);
853     lastRet = es.length - 1;
854     }
855     }
856 dl 1.5 }
857    
858     /**
859 jsr166 1.83 * Saves this queue to a stream (that is, serializes it).
860     *
861     * For compatibility with previous version of this class, elements
862     * are first copied to a java.util.PriorityQueue, which is then
863     * serialized.
864 jsr166 1.97 *
865     * @param s the stream
866 jsr166 1.98 * @throws java.io.IOException if an I/O error occurs
867 dl 1.5 */
868     private void writeObject(java.io.ObjectOutputStream s)
869     throws java.io.IOException {
870     lock.lock();
871     try {
872 jsr166 1.78 // avoid zero capacity argument
873     q = new PriorityQueue<E>(Math.max(size, 1), comparator);
874 dl 1.59 q.addAll(this);
875 dl 1.5 s.defaultWriteObject();
876 dl 1.66 } finally {
877 dl 1.59 q = null;
878 dl 1.5 lock.unlock();
879     }
880 tim 1.1 }
881    
882 dl 1.59 /**
883 jsr166 1.83 * Reconstitutes this queue from a stream (that is, deserializes it).
884 jsr166 1.97 * @param s the stream
885 jsr166 1.98 * @throws ClassNotFoundException if the class of a serialized object
886     * could not be found
887     * @throws java.io.IOException if an I/O error occurs
888 dl 1.59 */
889     private void readObject(java.io.ObjectInputStream s)
890     throws java.io.IOException, ClassNotFoundException {
891 jsr166 1.67 try {
892 dl 1.66 s.defaultReadObject();
893 jsr166 1.131 int sz = q.size();
894 jsr166 1.141 jsr166.Platform.checkArray(s, Object[].class, sz);
895 jsr166 1.135 this.queue = new Object[Math.max(1, sz)];
896 dl 1.66 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 jsr166 1.134 final Object[] es = array;
935 jsr166 1.125 index = hi; // ensure exhaustion
936     for (int i = lo; i < hi; i++)
937 jsr166 1.134 action.accept((E) es[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 jsr166 1.132 /**
980     * @throws NullPointerException {@inheritDoc}
981     */
982 jsr166 1.139 public boolean removeIf(Predicate<? super E> filter) {
983     Objects.requireNonNull(filter);
984     return bulkRemove(filter);
985     }
986    
987     /**
988     * @throws NullPointerException {@inheritDoc}
989     */
990     public boolean removeAll(Collection<?> c) {
991     Objects.requireNonNull(c);
992     return bulkRemove(e -> c.contains(e));
993     }
994    
995     /**
996     * @throws NullPointerException {@inheritDoc}
997     */
998     public boolean retainAll(Collection<?> c) {
999     Objects.requireNonNull(c);
1000     return bulkRemove(e -> !c.contains(e));
1001     }
1002    
1003     // A tiny bit set implementation
1004    
1005     private static long[] nBits(int n) {
1006     return new long[((n - 1) >> 6) + 1];
1007     }
1008     private static void setBit(long[] bits, int i) {
1009     bits[i >> 6] |= 1L << i;
1010     }
1011     private static boolean isClear(long[] bits, int i) {
1012     return (bits[i >> 6] & (1L << i)) == 0;
1013     }
1014    
1015     /** Implementation of bulk remove methods. */
1016     private boolean bulkRemove(Predicate<? super E> filter) {
1017     final ReentrantLock lock = this.lock;
1018     lock.lock();
1019     try {
1020     final Object[] es = queue;
1021     final int end = size;
1022     int i;
1023     // Optimize for initial run of survivors
1024     for (i = 0; i < end && !filter.test((E) es[i]); i++)
1025     ;
1026     if (i >= end)
1027     return false;
1028     // Tolerate predicates that reentrantly access the
1029     // collection for read, so traverse once to find elements
1030     // to delete, a second pass to physically expunge.
1031     final int beg = i;
1032     final long[] deathRow = nBits(end - beg);
1033     deathRow[0] = 1L; // set bit 0
1034     for (i = beg + 1; i < end; i++)
1035     if (filter.test((E) es[i]))
1036     setBit(deathRow, i - beg);
1037     int w = beg;
1038     for (i = beg; i < end; i++)
1039     if (isClear(deathRow, i - beg))
1040     es[w++] = es[i];
1041     for (i = size = w; i < end; i++)
1042     es[i] = null;
1043     heapify();
1044     return true;
1045     } finally {
1046     lock.unlock();
1047     }
1048     }
1049    
1050     /**
1051     * @throws NullPointerException {@inheritDoc}
1052     */
1053 jsr166 1.132 public void forEach(Consumer<? super E> action) {
1054     Objects.requireNonNull(action);
1055     final ReentrantLock lock = this.lock;
1056     lock.lock();
1057     try {
1058     final Object[] es = queue;
1059     for (int i = 0, n = size; i < n; i++)
1060     action.accept((E) es[i]);
1061     } finally {
1062     lock.unlock();
1063     }
1064     }
1065    
1066 dl 1.115 // VarHandle mechanics
1067     private static final VarHandle ALLOCATIONSPINLOCK;
1068 dl 1.70 static {
1069 dl 1.59 try {
1070 dl 1.115 MethodHandles.Lookup l = MethodHandles.lookup();
1071     ALLOCATIONSPINLOCK = l.findVarHandle(PriorityBlockingQueue.class,
1072     "allocationSpinLock",
1073     int.class);
1074 jsr166 1.107 } catch (ReflectiveOperationException e) {
1075 jsr166 1.130 throw new ExceptionInInitializerError(e);
1076 dl 1.59 }
1077     }
1078 tim 1.1 }