ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.93
Committed: Fri Feb 22 00:58:05 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.92: +61 -1 lines
Log Message:
Spliterator updates

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