ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.135
Committed: Sun May 6 21:07:41 2018 UTC (6 years ago) by jsr166
Branch: MAIN
Changes since 1.134: +27 -28 lines
Log Message:
small improvements

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 jsr166 1.135 private final ReentrantLock lock = new ReentrantLock();
142 dl 1.59
143     /**
144 jsr166 1.112 * Condition for blocking when empty.
145 dl 1.59 */
146 jsr166 1.135 private final Condition notEmpty = lock.newCondition();
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.comparator = comparator;
199 jsr166 1.135 this.queue = new Object[Math.max(1, initialCapacity)];
200 dl 1.2 }
201    
202     /**
203 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} containing the elements
204 jsr166 1.52 * in the specified collection. If the specified collection is a
205 jsr166 1.99 * {@link SortedSet} or a {@link PriorityQueue}, this
206 jsr166 1.52 * priority queue will be ordered according to the same ordering.
207     * Otherwise, this priority queue will be ordered according to the
208     * {@linkplain Comparable natural ordering} of its elements.
209 dl 1.2 *
210 jsr166 1.52 * @param c the collection whose elements are to be placed
211     * into this priority queue
212 dl 1.2 * @throws ClassCastException if elements of the specified collection
213     * cannot be compared to one another according to the priority
214 jsr166 1.52 * queue's ordering
215 jsr166 1.42 * @throws NullPointerException if the specified collection or any
216     * of its elements are null
217 dl 1.2 */
218 dholmes 1.14 public PriorityBlockingQueue(Collection<? extends E> c) {
219 dl 1.66 boolean heapify = true; // true if not known to be in heap order
220     boolean screen = true; // true if must screen for nulls
221 dl 1.59 if (c instanceof SortedSet<?>) {
222     SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
223     this.comparator = (Comparator<? super E>) ss.comparator();
224 dl 1.66 heapify = false;
225 dl 1.59 }
226     else if (c instanceof PriorityBlockingQueue<?>) {
227 jsr166 1.61 PriorityBlockingQueue<? extends E> pq =
228 dl 1.59 (PriorityBlockingQueue<? extends E>) c;
229     this.comparator = (Comparator<? super E>) pq.comparator();
230 jsr166 1.67 screen = false;
231 dl 1.66 if (pq.getClass() == PriorityBlockingQueue.class) // exact match
232     heapify = false;
233 dl 1.59 }
234 jsr166 1.134 Object[] es = c.toArray();
235     int n = es.length;
236 dl 1.59 // If c.toArray incorrectly doesn't return Object[], copy it.
237 jsr166 1.134 if (es.getClass() != Object[].class)
238     es = Arrays.copyOf(es, n, Object[].class);
239 dl 1.66 if (screen && (n == 1 || this.comparator != null)) {
240 jsr166 1.134 for (Object e : es)
241     if (e == null)
242 dl 1.59 throw new NullPointerException();
243 dl 1.66 }
244 jsr166 1.135 this.queue = ensureNonEmpty(es);
245 dl 1.66 this.size = n;
246     if (heapify)
247     heapify();
248 dl 1.59 }
249    
250 jsr166 1.135 /** Ensures that queue[0] exists, helping peek() and poll(). */
251     private static Object[] ensureNonEmpty(Object[] es) {
252     return (es.length > 0) ? es : new Object[1];
253     }
254    
255 dl 1.59 /**
256 dl 1.66 * Tries to grow array to accommodate at least one more element
257     * (but normally expand by about 50%), giving up (allowing retry)
258     * on contention (which we expect to be rare). Call only while
259     * holding lock.
260 jsr166 1.67 *
261 dl 1.66 * @param array the heap array
262     * @param oldCap the length of the array
263 dl 1.59 */
264 dl 1.66 private void tryGrow(Object[] array, int oldCap) {
265 dl 1.59 lock.unlock(); // must release and then re-acquire main lock
266     Object[] newArray = null;
267     if (allocationSpinLock == 0 &&
268 dl 1.115 ALLOCATIONSPINLOCK.compareAndSet(this, 0, 1)) {
269 dl 1.59 try {
270     int newCap = oldCap + ((oldCap < 64) ?
271 dl 1.66 (oldCap + 2) : // grow faster if small
272 dl 1.59 (oldCap >> 1));
273 dl 1.66 if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
274     int minCap = oldCap + 1;
275 dl 1.59 if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
276     throw new OutOfMemoryError();
277     newCap = MAX_ARRAY_SIZE;
278     }
279 dl 1.66 if (newCap > oldCap && queue == array)
280 dl 1.59 newArray = new Object[newCap];
281     } finally {
282     allocationSpinLock = 0;
283     }
284     }
285 dl 1.66 if (newArray == null) // back off if another thread is allocating
286 dl 1.59 Thread.yield();
287     lock.lock();
288     if (newArray != null && queue == array) {
289     queue = newArray;
290 dl 1.66 System.arraycopy(array, 0, newArray, 0, oldCap);
291 dl 1.59 }
292     }
293    
294     /**
295 jsr166 1.62 * Mechanics for poll(). Call only while holding lock.
296 dl 1.59 */
297 jsr166 1.79 private E dequeue() {
298 jsr166 1.134 // assert lock.isHeldByCurrentThread();
299 jsr166 1.135 final Object[] es;
300     final E result;
301    
302     if ((result = (E) ((es = queue)[0])) != null) {
303     final int n;
304     final E x = (E) es[(n = --size)];
305 jsr166 1.134 es[n] = null;
306     if (n > 0) {
307 jsr166 1.135 final Comparator<? super E> cmp;
308     if ((cmp = comparator) == null)
309 jsr166 1.134 siftDownComparable(0, x, es, n);
310     else
311     siftDownUsingComparator(0, x, es, n, cmp);
312     }
313 dl 1.59 }
314 jsr166 1.135 return result;
315 dl 1.59 }
316    
317     /**
318     * Inserts item x at position k, maintaining heap invariant by
319     * promoting x up the tree until it is greater than or equal to
320     * its parent, or is the root.
321     *
322 jsr166 1.121 * To simplify and speed up coercions and comparisons, the
323 dl 1.59 * Comparable and Comparator versions are separated into different
324     * methods that are otherwise identical. (Similarly for siftDown.)
325     *
326     * @param k the position to fill
327     * @param x the item to insert
328 jsr166 1.134 * @param es the heap array
329 dl 1.59 */
330 jsr166 1.134 private static <T> void siftUpComparable(int k, T x, Object[] es) {
331 dl 1.66 Comparable<? super T> key = (Comparable<? super T>) x;
332 dl 1.59 while (k > 0) {
333     int parent = (k - 1) >>> 1;
334 jsr166 1.134 Object e = es[parent];
335 dl 1.66 if (key.compareTo((T) e) >= 0)
336 dl 1.59 break;
337 jsr166 1.134 es[k] = e;
338 dl 1.59 k = parent;
339     }
340 jsr166 1.134 es[k] = key;
341 dl 1.59 }
342    
343 jsr166 1.134 private static <T> void siftUpUsingComparator(
344     int k, T x, Object[] es, Comparator<? super T> cmp) {
345 dl 1.59 while (k > 0) {
346     int parent = (k - 1) >>> 1;
347 jsr166 1.134 Object e = es[parent];
348 dl 1.66 if (cmp.compare(x, (T) e) >= 0)
349 dl 1.59 break;
350 jsr166 1.134 es[k] = e;
351 dl 1.59 k = parent;
352     }
353 jsr166 1.134 es[k] = x;
354 dl 1.59 }
355    
356     /**
357     * Inserts item x at position k, maintaining heap invariant by
358     * demoting x down the tree repeatedly until it is less than or
359     * equal to its children or is a leaf.
360     *
361     * @param k the position to fill
362     * @param x the item to insert
363 jsr166 1.134 * @param es the heap array
364 dl 1.66 * @param n heap size
365 dl 1.59 */
366 jsr166 1.134 private static <T> void siftDownComparable(int k, T x, Object[] es, int n) {
367     // assert n > 0;
368     Comparable<? super T> key = (Comparable<? super T>)x;
369     int half = n >>> 1; // loop while a non-leaf
370     while (k < half) {
371     int child = (k << 1) + 1; // assume left child is least
372     Object c = es[child];
373     int right = child + 1;
374     if (right < n &&
375     ((Comparable<? super T>) c).compareTo((T) es[right]) > 0)
376     c = es[child = right];
377     if (key.compareTo((T) c) <= 0)
378     break;
379     es[k] = c;
380     k = child;
381 dl 1.59 }
382 jsr166 1.134 es[k] = key;
383 dl 1.59 }
384    
385 jsr166 1.134 private static <T> void siftDownUsingComparator(
386     int k, T x, Object[] es, int n, Comparator<? super T> cmp) {
387     // assert n > 0;
388     int half = n >>> 1;
389     while (k < half) {
390     int child = (k << 1) + 1;
391     Object c = es[child];
392     int right = child + 1;
393     if (right < n && cmp.compare((T) c, (T) es[right]) > 0)
394     c = es[child = right];
395     if (cmp.compare(x, (T) c) <= 0)
396     break;
397     es[k] = c;
398     k = child;
399 dl 1.59 }
400 jsr166 1.134 es[k] = x;
401 dl 1.7 }
402    
403 dholmes 1.10 /**
404 dl 1.59 * Establishes the heap invariant (described above) in the entire tree,
405     * assuming nothing about the order of the elements prior to the call.
406 jsr166 1.118 * This classic algorithm due to Floyd (1964) is known to be O(size).
407 dl 1.59 */
408     private void heapify() {
409 jsr166 1.134 final Object[] es = queue;
410 jsr166 1.127 int n = size, i = (n >>> 1) - 1;
411 jsr166 1.135 final Comparator<? super E> cmp;
412     if ((cmp = comparator) == null)
413 jsr166 1.127 for (; i >= 0; i--)
414 jsr166 1.134 siftDownComparable(i, (E) es[i], es, n);
415     else
416 jsr166 1.127 for (; i >= 0; i--)
417 jsr166 1.134 siftDownUsingComparator(i, (E) es[i], es, n, cmp);
418 dl 1.59 }
419    
420     /**
421 jsr166 1.42 * Inserts the specified element into this priority queue.
422     *
423 jsr166 1.40 * @param e the element to add
424 jsr166 1.63 * @return {@code true} (as specified by {@link Collection#add})
425 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
426 jsr166 1.42 * with elements currently in the priority queue according to the
427     * priority queue's ordering
428     * @throws NullPointerException if the specified element is null
429 dholmes 1.10 */
430 jsr166 1.40 public boolean add(E e) {
431 jsr166 1.42 return offer(e);
432 dl 1.5 }
433    
434 dholmes 1.16 /**
435 dl 1.24 * Inserts the specified element into this priority queue.
436 jsr166 1.64 * As the queue is unbounded, this method will never return {@code false}.
437 dholmes 1.16 *
438 jsr166 1.40 * @param e the element to add
439 jsr166 1.63 * @return {@code true} (as specified by {@link Queue#offer})
440 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
441 jsr166 1.42 * with elements currently in the priority queue according to the
442     * priority queue's ordering
443     * @throws NullPointerException if the specified element is null
444 dholmes 1.16 */
445 jsr166 1.40 public boolean offer(E e) {
446 dl 1.59 if (e == null)
447     throw new NullPointerException();
448 dl 1.31 final ReentrantLock lock = this.lock;
449 dl 1.5 lock.lock();
450 dl 1.66 int n, cap;
451 dl 1.59 Object[] array;
452 dl 1.66 while ((n = size) >= (cap = (array = queue).length))
453     tryGrow(array, cap);
454 dl 1.59 try {
455 jsr166 1.135 final Comparator<? super E> cmp;
456     if ((cmp = comparator) == null)
457 dl 1.66 siftUpComparable(n, e, array);
458 dl 1.59 else
459 dl 1.66 siftUpUsingComparator(n, e, array, cmp);
460     size = n + 1;
461 dl 1.5 notEmpty.signal();
462 tim 1.19 } finally {
463 tim 1.13 lock.unlock();
464 dl 1.5 }
465 dl 1.59 return true;
466 dl 1.5 }
467    
468 dholmes 1.16 /**
469 jsr166 1.64 * Inserts the specified element into this priority queue.
470     * As the queue is unbounded, this method will never block.
471 jsr166 1.42 *
472 jsr166 1.40 * @param e the element to add
473 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
474     * with elements currently in the priority queue according to the
475     * priority queue's ordering
476     * @throws NullPointerException if the specified element is null
477 dholmes 1.16 */
478 jsr166 1.40 public void put(E e) {
479     offer(e); // never need to block
480 dl 1.5 }
481    
482 dholmes 1.16 /**
483 jsr166 1.64 * Inserts the specified element into this priority queue.
484     * As the queue is unbounded, this method will never block or
485     * return {@code false}.
486 jsr166 1.42 *
487 jsr166 1.40 * @param e the element to add
488 dholmes 1.16 * @param timeout This parameter is ignored as the method never blocks
489     * @param unit This parameter is ignored as the method never blocks
490 jsr166 1.65 * @return {@code true} (as specified by
491     * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
492 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
493     * with elements currently in the priority queue according to the
494     * priority queue's ordering
495     * @throws NullPointerException if the specified element is null
496 dholmes 1.16 */
497 jsr166 1.40 public boolean offer(E e, long timeout, TimeUnit unit) {
498     return offer(e); // never need to block
499 dl 1.5 }
500    
501 jsr166 1.42 public E poll() {
502     final ReentrantLock lock = this.lock;
503     lock.lock();
504     try {
505 jsr166 1.79 return dequeue();
506 jsr166 1.42 } finally {
507     lock.unlock();
508     }
509     }
510    
511 dl 1.5 public E take() throws InterruptedException {
512 dl 1.31 final ReentrantLock lock = this.lock;
513 dl 1.5 lock.lockInterruptibly();
514 dl 1.66 E result;
515 dl 1.5 try {
516 jsr166 1.79 while ( (result = dequeue()) == null)
517 jsr166 1.55 notEmpty.await();
518 tim 1.19 } finally {
519 dl 1.5 lock.unlock();
520     }
521 dl 1.59 return result;
522 dl 1.5 }
523    
524     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
525 dholmes 1.10 long nanos = unit.toNanos(timeout);
526 dl 1.31 final ReentrantLock lock = this.lock;
527 dl 1.5 lock.lockInterruptibly();
528 dl 1.66 E result;
529 dl 1.5 try {
530 jsr166 1.79 while ( (result = dequeue()) == null && nanos > 0)
531 jsr166 1.55 nanos = notEmpty.awaitNanos(nanos);
532 tim 1.19 } finally {
533 dl 1.5 lock.unlock();
534     }
535 dl 1.59 return result;
536 dl 1.5 }
537    
538     public E peek() {
539 dl 1.31 final ReentrantLock lock = this.lock;
540 dl 1.5 lock.lock();
541     try {
542 jsr166 1.135 return (E) queue[0];
543 tim 1.19 } finally {
544 tim 1.13 lock.unlock();
545 dl 1.5 }
546     }
547 jsr166 1.61
548 jsr166 1.42 /**
549     * Returns the comparator used to order the elements in this queue,
550 jsr166 1.63 * or {@code null} if this queue uses the {@linkplain Comparable
551 jsr166 1.42 * natural ordering} of its elements.
552     *
553     * @return the comparator used to order the elements in this queue,
554 jsr166 1.63 * or {@code null} if this queue uses the natural
555 jsr166 1.52 * ordering of its elements
556 jsr166 1.42 */
557     public Comparator<? super E> comparator() {
558 dl 1.59 return comparator;
559 jsr166 1.42 }
560    
561 dl 1.5 public int size() {
562 dl 1.31 final ReentrantLock lock = this.lock;
563 dl 1.5 lock.lock();
564     try {
565 jsr166 1.68 return size;
566 tim 1.19 } finally {
567 dl 1.5 lock.unlock();
568     }
569     }
570    
571     /**
572 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
573     * a {@code PriorityBlockingQueue} is not capacity constrained.
574     * @return {@code Integer.MAX_VALUE} always
575 dl 1.5 */
576     public int remainingCapacity() {
577     return Integer.MAX_VALUE;
578     }
579    
580 dl 1.59 private int indexOf(Object o) {
581     if (o != null) {
582 jsr166 1.133 final Object[] es = queue;
583     for (int i = 0, n = size; i < n; i++)
584     if (o.equals(es[i]))
585 dl 1.59 return i;
586     }
587     return -1;
588     }
589    
590     /**
591     * Removes the ith element from queue.
592     */
593     private void removeAt(int i) {
594 jsr166 1.134 final Object[] es = queue;
595 jsr166 1.135 final int n = size - 1;
596 dl 1.66 if (n == i) // removed last element
597 jsr166 1.134 es[i] = null;
598 dl 1.59 else {
599 jsr166 1.134 E moved = (E) es[n];
600     es[n] = null;
601 jsr166 1.135 final Comparator<? super E> cmp;
602     if ((cmp = comparator) == null)
603 jsr166 1.134 siftDownComparable(i, moved, es, n);
604 dl 1.66 else
605 jsr166 1.134 siftDownUsingComparator(i, moved, es, n, cmp);
606     if (es[i] == moved) {
607 dl 1.66 if (cmp == null)
608 jsr166 1.134 siftUpComparable(i, moved, es);
609 dl 1.66 else
610 jsr166 1.134 siftUpUsingComparator(i, moved, es, cmp);
611 dl 1.66 }
612 dl 1.59 }
613 dl 1.66 size = n;
614 dl 1.59 }
615    
616 dl 1.37 /**
617 jsr166 1.42 * Removes a single instance of the specified element from this queue,
618 jsr166 1.52 * if it is present. More formally, removes an element {@code e} such
619     * that {@code o.equals(e)}, if this queue contains one or more such
620     * elements. Returns {@code true} if and only if this queue contained
621     * the specified element (or equivalently, if this queue changed as a
622     * result of the call).
623 jsr166 1.42 *
624     * @param o element to be removed from this queue, if present
625 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
626 dl 1.37 */
627 dholmes 1.14 public boolean remove(Object o) {
628 dl 1.31 final ReentrantLock lock = this.lock;
629 dl 1.5 lock.lock();
630     try {
631 dl 1.59 int i = indexOf(o);
632 jsr166 1.78 if (i == -1)
633     return false;
634     removeAt(i);
635     return true;
636 dl 1.59 } finally {
637     lock.unlock();
638     }
639     }
640    
641     /**
642 jsr166 1.112 * Identity-based version for use in Itr.remove.
643 jsr166 1.133 *
644     * @param o element to be removed from this queue, if present
645 dl 1.59 */
646 jsr166 1.133 void removeEq(Object o) {
647 dl 1.59 final ReentrantLock lock = this.lock;
648     lock.lock();
649     try {
650 jsr166 1.133 final Object[] es = queue;
651 jsr166 1.78 for (int i = 0, n = size; i < n; i++) {
652 jsr166 1.133 if (o == es[i]) {
653 dl 1.59 removeAt(i);
654     break;
655     }
656     }
657 tim 1.19 } finally {
658 dl 1.5 lock.unlock();
659     }
660     }
661    
662 jsr166 1.42 /**
663 jsr166 1.52 * Returns {@code true} if this queue contains the specified element.
664     * More formally, returns {@code true} if and only if this queue contains
665     * at least one element {@code e} such that {@code o.equals(e)}.
666 jsr166 1.42 *
667     * @param o object to be checked for containment in this queue
668 jsr166 1.63 * @return {@code true} if this queue contains the specified element
669 jsr166 1.42 */
670 dholmes 1.14 public boolean contains(Object o) {
671 dl 1.31 final ReentrantLock lock = this.lock;
672 dl 1.5 lock.lock();
673     try {
674 jsr166 1.78 return indexOf(o) != -1;
675 tim 1.19 } finally {
676 dl 1.5 lock.unlock();
677     }
678     }
679    
680     public String toString() {
681 jsr166 1.111 return Helpers.collectionToString(this);
682 dl 1.5 }
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) {
691 jsr166 1.76 return drainTo(c, Integer.MAX_VALUE);
692 dl 1.26 }
693    
694 jsr166 1.42 /**
695     * @throws UnsupportedOperationException {@inheritDoc}
696     * @throws ClassCastException {@inheritDoc}
697     * @throws NullPointerException {@inheritDoc}
698     * @throws IllegalArgumentException {@inheritDoc}
699     */
700 dl 1.26 public int drainTo(Collection<? super E> c, int maxElements) {
701 jsr166 1.124 Objects.requireNonNull(c);
702 dl 1.26 if (c == this)
703     throw new IllegalArgumentException();
704     if (maxElements <= 0)
705     return 0;
706 dl 1.31 final ReentrantLock lock = this.lock;
707 dl 1.26 lock.lock();
708     try {
709 jsr166 1.76 int n = Math.min(size, maxElements);
710     for (int i = 0; i < n; i++) {
711     c.add((E) queue[0]); // In this order, in case add() throws.
712 jsr166 1.79 dequeue();
713 dl 1.26 }
714     return n;
715     } finally {
716     lock.unlock();
717     }
718     }
719    
720 dl 1.17 /**
721 dl 1.37 * Atomically removes all of the elements from this queue.
722 dl 1.17 * The queue will be empty after this call returns.
723     */
724     public void clear() {
725 dl 1.31 final ReentrantLock lock = this.lock;
726 dl 1.17 lock.lock();
727     try {
728 jsr166 1.133 final Object[] es = queue;
729     for (int i = 0, n = size; i < n; i++)
730     es[i] = null;
731 dl 1.59 size = 0;
732 tim 1.19 } finally {
733 dl 1.17 lock.unlock();
734     }
735     }
736    
737 jsr166 1.42 /**
738 jsr166 1.110 * Returns an array containing all of the elements in this queue.
739     * The returned array elements are in no particular order.
740     *
741     * <p>The returned array will be "safe" in that no references to it are
742     * maintained by this queue. (In other words, this method must allocate
743     * a new array). The caller is thus free to modify the returned array.
744     *
745     * <p>This method acts as bridge between array-based and collection-based
746     * APIs.
747     *
748     * @return an array containing all of the elements in this queue
749     */
750     public Object[] toArray() {
751     final ReentrantLock lock = this.lock;
752     lock.lock();
753     try {
754     return Arrays.copyOf(queue, size);
755     } finally {
756     lock.unlock();
757     }
758     }
759    
760     /**
761 jsr166 1.42 * Returns an array containing all of the elements in this queue; the
762     * runtime type of the returned array is that of the specified array.
763     * The returned array elements are in no particular order.
764     * If the queue fits in the specified array, it is returned therein.
765     * Otherwise, a new array is allocated with the runtime type of the
766     * specified array and the size of this queue.
767     *
768     * <p>If this queue fits in the specified array with room to spare
769     * (i.e., the array has more elements than this queue), the element in
770     * the array immediately following the end of the queue is set to
771 jsr166 1.63 * {@code null}.
772 jsr166 1.42 *
773     * <p>Like the {@link #toArray()} method, this method acts as bridge between
774     * array-based and collection-based APIs. Further, this method allows
775     * precise control over the runtime type of the output array, and may,
776     * under certain circumstances, be used to save allocation costs.
777     *
778 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
779 jsr166 1.42 * The following code can be used to dump the queue into a newly
780 jsr166 1.63 * allocated array of {@code String}:
781 jsr166 1.42 *
782 jsr166 1.109 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
783 jsr166 1.42 *
784 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
785     * {@code toArray()}.
786 jsr166 1.42 *
787     * @param a the array into which the elements of the queue are to
788     * be stored, if it is big enough; otherwise, a new array of the
789     * same runtime type is allocated for this purpose
790     * @return an array containing all of the elements in this queue
791     * @throws ArrayStoreException if the runtime type of the specified array
792     * is not a supertype of the runtime type of every element in
793     * this queue
794     * @throws NullPointerException if the specified array is null
795     */
796 dl 1.5 public <T> T[] toArray(T[] a) {
797 dl 1.31 final ReentrantLock lock = this.lock;
798 dl 1.5 lock.lock();
799     try {
800 dl 1.66 int n = size;
801     if (a.length < n)
802 dl 1.59 // Make a new array of a's runtime type, but my contents:
803     return (T[]) Arrays.copyOf(queue, size, a.getClass());
804 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
805     if (a.length > n)
806     a[n] = null;
807 dl 1.59 return a;
808 tim 1.19 } finally {
809 dl 1.5 lock.unlock();
810     }
811     }
812    
813 dholmes 1.16 /**
814 dl 1.23 * Returns an iterator over the elements in this queue. The
815     * iterator does not return the elements in any particular order.
816 jsr166 1.69 *
817 jsr166 1.103 * <p>The returned iterator is
818     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
819 dholmes 1.16 *
820 jsr166 1.42 * @return an iterator over the elements in this queue
821 dholmes 1.16 */
822 dl 1.5 public Iterator<E> iterator() {
823 dl 1.51 return new Itr(toArray());
824 dl 1.5 }
825    
826 dl 1.49 /**
827     * Snapshot iterator that works off copy of underlying q array.
828     */
829 dl 1.59 final class Itr implements Iterator<E> {
830 dl 1.49 final Object[] array; // Array of all elements
831 jsr166 1.81 int cursor; // index of next element to return
832 jsr166 1.54 int lastRet; // index of last element, or -1 if no such
833 jsr166 1.50
834 dl 1.49 Itr(Object[] array) {
835     lastRet = -1;
836     this.array = array;
837 dl 1.5 }
838    
839 tim 1.13 public boolean hasNext() {
840 dl 1.49 return cursor < array.length;
841 tim 1.13 }
842    
843     public E next() {
844 dl 1.49 if (cursor >= array.length)
845     throw new NoSuchElementException();
846 jsr166 1.120 return (E)array[lastRet = cursor++];
847 tim 1.13 }
848    
849     public void remove() {
850 jsr166 1.50 if (lastRet < 0)
851 jsr166 1.54 throw new IllegalStateException();
852 jsr166 1.133 removeEq(array[lastRet]);
853 dl 1.49 lastRet = -1;
854 tim 1.13 }
855 dl 1.5 }
856    
857     /**
858 jsr166 1.83 * Saves this queue to a stream (that is, serializes it).
859     *
860     * For compatibility with previous version of this class, elements
861     * are first copied to a java.util.PriorityQueue, which is then
862     * serialized.
863 jsr166 1.97 *
864     * @param s the stream
865 jsr166 1.98 * @throws java.io.IOException if an I/O error occurs
866 dl 1.5 */
867     private void writeObject(java.io.ObjectOutputStream s)
868     throws java.io.IOException {
869     lock.lock();
870     try {
871 jsr166 1.78 // avoid zero capacity argument
872     q = new PriorityQueue<E>(Math.max(size, 1), comparator);
873 dl 1.59 q.addAll(this);
874 dl 1.5 s.defaultWriteObject();
875 dl 1.66 } finally {
876 dl 1.59 q = null;
877 dl 1.5 lock.unlock();
878     }
879 tim 1.1 }
880    
881 dl 1.59 /**
882 jsr166 1.83 * Reconstitutes this queue from a stream (that is, deserializes it).
883 jsr166 1.97 * @param s the stream
884 jsr166 1.98 * @throws ClassNotFoundException if the class of a serialized object
885     * could not be found
886     * @throws java.io.IOException if an I/O error occurs
887 dl 1.59 */
888     private void readObject(java.io.ObjectInputStream s)
889     throws java.io.IOException, ClassNotFoundException {
890 jsr166 1.67 try {
891 dl 1.66 s.defaultReadObject();
892 jsr166 1.131 int sz = q.size();
893     SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, sz);
894 jsr166 1.135 this.queue = new Object[Math.max(1, sz)];
895 dl 1.66 comparator = q.comparator();
896     addAll(q);
897 jsr166 1.67 } finally {
898 dl 1.66 q = null;
899     }
900 dl 1.59 }
901    
902 jsr166 1.116 /**
903     * Immutable snapshot spliterator that binds to elements "late".
904     */
905 jsr166 1.119 final class PBQSpliterator implements Spliterator<E> {
906 jsr166 1.125 Object[] array; // null until late-bound-initialized
907 dl 1.93 int index;
908     int fence;
909    
910 jsr166 1.125 PBQSpliterator() {}
911    
912 jsr166 1.119 PBQSpliterator(Object[] array, int index, int fence) {
913 dl 1.93 this.array = array;
914     this.index = index;
915     this.fence = fence;
916     }
917    
918 jsr166 1.125 private int getFence() {
919     if (array == null)
920     fence = (array = toArray()).length;
921     return fence;
922 dl 1.93 }
923    
924 jsr166 1.119 public PBQSpliterator trySplit() {
925 dl 1.93 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
926     return (lo >= mid) ? null :
927 jsr166 1.119 new PBQSpliterator(array, lo, index = mid);
928 dl 1.93 }
929    
930 dl 1.95 public void forEachRemaining(Consumer<? super E> action) {
931 jsr166 1.124 Objects.requireNonNull(action);
932 jsr166 1.125 final int hi = getFence(), lo = index;
933 jsr166 1.134 final Object[] es = array;
934 jsr166 1.125 index = hi; // ensure exhaustion
935     for (int i = lo; i < hi; i++)
936 jsr166 1.134 action.accept((E) es[i]);
937 dl 1.93 }
938    
939     public boolean tryAdvance(Consumer<? super E> action) {
940 jsr166 1.124 Objects.requireNonNull(action);
941 dl 1.93 if (getFence() > index && index >= 0) {
942 jsr166 1.125 action.accept((E) array[index++]);
943 dl 1.93 return true;
944     }
945     return false;
946     }
947    
948 jsr166 1.119 public long estimateSize() { return getFence() - index; }
949 dl 1.93
950     public int characteristics() {
951 jsr166 1.123 return (Spliterator.NONNULL |
952     Spliterator.SIZED |
953     Spliterator.SUBSIZED);
954 dl 1.93 }
955     }
956    
957 jsr166 1.102 /**
958     * Returns a {@link Spliterator} over the elements in this queue.
959 jsr166 1.117 * The spliterator does not traverse elements in any particular order
960     * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported).
961 jsr166 1.102 *
962 jsr166 1.103 * <p>The returned spliterator is
963     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
964     *
965 jsr166 1.102 * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
966     * {@link Spliterator#NONNULL}.
967     *
968     * @implNote
969     * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}.
970     *
971     * @return a {@code Spliterator} over the elements in this queue
972     * @since 1.8
973     */
974 dl 1.94 public Spliterator<E> spliterator() {
975 jsr166 1.125 return new PBQSpliterator();
976 dl 1.86 }
977    
978 jsr166 1.132 /**
979     * @throws NullPointerException {@inheritDoc}
980     */
981     public void forEach(Consumer<? super E> action) {
982     Objects.requireNonNull(action);
983     final ReentrantLock lock = this.lock;
984     lock.lock();
985     try {
986     final Object[] es = queue;
987     for (int i = 0, n = size; i < n; i++)
988     action.accept((E) es[i]);
989     } finally {
990     lock.unlock();
991     }
992     }
993    
994 dl 1.115 // VarHandle mechanics
995     private static final VarHandle ALLOCATIONSPINLOCK;
996 dl 1.70 static {
997 dl 1.59 try {
998 dl 1.115 MethodHandles.Lookup l = MethodHandles.lookup();
999     ALLOCATIONSPINLOCK = l.findVarHandle(PriorityBlockingQueue.class,
1000     "allocationSpinLock",
1001     int.class);
1002 jsr166 1.107 } catch (ReflectiveOperationException e) {
1003 jsr166 1.130 throw new ExceptionInInitializerError(e);
1004 dl 1.59 }
1005     }
1006 tim 1.1 }