ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.134
Committed: Sun May 6 19:35:51 2018 UTC (6 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.133: +77 -80 lines
Log Message:
coding style

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