ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.114
Committed: Tue Apr 19 22:55:30 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.113: +1 -1 lines
Log Message:
s~\bsun\.(misc\.Unsafe)\b~jdk.internal.$1~g;
s~\bputOrdered([A-Za-z]+)\b~put${1}Release~g

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