ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.82
Committed: Fri Dec 2 14:37:32 2011 UTC (12 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.81: +1 -0 lines
Log Message:
blanket unchecked warning suppression for comparator-using classes

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