ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.106
Committed: Wed Dec 31 09:37:20 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.105: +0 -2 lines
Log Message:
remove unused/redundant imports

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