ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.73
Committed: Thu Jun 9 07:48:43 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.72: +1 -2 lines
Log Message:
consistent style for code snippets

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 dl 1.5 public class PriorityBlockingQueue<E> extends AbstractQueue<E>
69 dl 1.15 implements BlockingQueue<E>, java.io.Serializable {
70 dl 1.21 private static final long serialVersionUID = 5595510919245408276L;
71 tim 1.1
72 dl 1.59 /*
73 dl 1.66 * The implementation uses an array-based binary heap, with public
74     * operations protected with a single lock. However, allocation
75     * during resizing uses a simple spinlock (used only while not
76     * holding main lock) in order to allow takes to operate
77     * concurrently with allocation. This avoids repeated
78     * postponement of waiting consumers and consequent element
79     * build-up. The need to back away from lock during allocation
80     * makes it impossible to simply wrap delegated
81     * java.util.PriorityQueue operations within a lock, as was done
82     * in a previous version of this class. To maintain
83     * interoperability, a plain PriorityQueue is still used during
84     * serialization, which maintains compatibility at the espense of
85     * transiently doubling overhead.
86 dl 1.59 */
87    
88     /**
89     * Default array capacity.
90     */
91     private static final int DEFAULT_INITIAL_CAPACITY = 11;
92    
93     /**
94 dl 1.66 * The maximum size of array to allocate.
95     * Some VMs reserve some header words in an array.
96     * Attempts to allocate larger arrays may result in
97     * OutOfMemoryError: Requested array size exceeds VM limit
98     */
99     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
100    
101     /**
102 dl 1.59 * Priority queue represented as a balanced binary heap: the two
103     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
104     * priority queue is ordered by comparator, or by the elements'
105     * natural ordering, if comparator is null: For each node n in the
106     * heap and each descendant d of n, n <= d. The element with the
107     * lowest value is in queue[0], assuming the queue is nonempty.
108     */
109     private transient Object[] queue;
110    
111     /**
112     * The number of elements in the priority queue.
113     */
114 dl 1.66 private transient int size;
115 dl 1.59
116     /**
117     * The comparator, or null if priority queue uses elements'
118     * natural ordering.
119     */
120     private transient Comparator<? super E> comparator;
121    
122     /**
123 dl 1.66 * Lock used for all public operations
124 dl 1.59 */
125 dl 1.66 private final ReentrantLock lock;
126 dl 1.59
127     /**
128 dl 1.66 * Condition for blocking when empty
129 dl 1.59 */
130 dl 1.66 private final Condition notEmpty;
131 dl 1.5
132 dl 1.2 /**
133 dl 1.59 * Spinlock for allocation, acquired via CAS.
134     */
135     private transient volatile int allocationSpinLock;
136    
137     /**
138 dl 1.66 * A plain PriorityQueue used only for serialization,
139     * to maintain compatibility with previous versions
140     * of this class. Non-null only during serialization/deserialization.
141     */
142 jsr166 1.72 private PriorityQueue<E> q;
143 dl 1.66
144     /**
145 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the default
146 jsr166 1.42 * initial capacity (11) that orders its elements according to
147     * their {@linkplain Comparable natural ordering}.
148 dl 1.2 */
149     public PriorityBlockingQueue() {
150 dl 1.59 this(DEFAULT_INITIAL_CAPACITY, null);
151 dl 1.2 }
152    
153     /**
154 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the specified
155 jsr166 1.42 * initial capacity that orders its elements according to their
156     * {@linkplain Comparable natural ordering}.
157 dl 1.2 *
158 jsr166 1.42 * @param initialCapacity the initial capacity for this priority queue
159 jsr166 1.63 * @throws IllegalArgumentException if {@code initialCapacity} is less
160 jsr166 1.52 * than 1
161 dl 1.2 */
162     public PriorityBlockingQueue(int initialCapacity) {
163 dl 1.59 this(initialCapacity, null);
164 dl 1.2 }
165    
166     /**
167 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} with the specified initial
168 jsr166 1.39 * capacity that orders its elements according to the specified
169     * comparator.
170 dl 1.2 *
171 jsr166 1.42 * @param initialCapacity the initial capacity for this priority queue
172 jsr166 1.52 * @param comparator the comparator that will be used to order this
173     * priority queue. If {@code null}, the {@linkplain Comparable
174     * natural ordering} of the elements will be used.
175 jsr166 1.63 * @throws IllegalArgumentException if {@code initialCapacity} is less
176 jsr166 1.52 * than 1
177 dl 1.2 */
178 tim 1.13 public PriorityBlockingQueue(int initialCapacity,
179 dholmes 1.14 Comparator<? super E> comparator) {
180 dl 1.59 if (initialCapacity < 1)
181     throw new IllegalArgumentException();
182 dl 1.66 this.lock = new ReentrantLock();
183     this.notEmpty = lock.newCondition();
184     this.comparator = comparator;
185 dl 1.59 this.queue = new Object[initialCapacity];
186 dl 1.2 }
187    
188     /**
189 jsr166 1.63 * Creates a {@code PriorityBlockingQueue} containing the elements
190 jsr166 1.52 * in the specified collection. If the specified collection is a
191     * {@link SortedSet} or a {@link PriorityQueue}, this
192     * priority queue will be ordered according to the same ordering.
193     * Otherwise, this priority queue will be ordered according to the
194     * {@linkplain Comparable natural ordering} of its elements.
195 dl 1.2 *
196 jsr166 1.52 * @param c the collection whose elements are to be placed
197     * into this priority queue
198 dl 1.2 * @throws ClassCastException if elements of the specified collection
199     * cannot be compared to one another according to the priority
200 jsr166 1.52 * queue's ordering
201 jsr166 1.42 * @throws NullPointerException if the specified collection or any
202     * of its elements are null
203 dl 1.2 */
204 dholmes 1.14 public PriorityBlockingQueue(Collection<? extends E> c) {
205 dl 1.66 this.lock = new ReentrantLock();
206     this.notEmpty = lock.newCondition();
207     boolean heapify = true; // true if not known to be in heap order
208     boolean screen = true; // true if must screen for nulls
209 dl 1.59 if (c instanceof SortedSet<?>) {
210     SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
211     this.comparator = (Comparator<? super E>) ss.comparator();
212 dl 1.66 heapify = false;
213 dl 1.59 }
214     else if (c instanceof PriorityBlockingQueue<?>) {
215 jsr166 1.61 PriorityBlockingQueue<? extends E> pq =
216 dl 1.59 (PriorityBlockingQueue<? extends E>) c;
217     this.comparator = (Comparator<? super E>) pq.comparator();
218 jsr166 1.67 screen = false;
219 dl 1.66 if (pq.getClass() == PriorityBlockingQueue.class) // exact match
220     heapify = false;
221 dl 1.59 }
222     Object[] a = c.toArray();
223 dl 1.66 int n = a.length;
224 dl 1.59 // If c.toArray incorrectly doesn't return Object[], copy it.
225     if (a.getClass() != Object[].class)
226 dl 1.66 a = Arrays.copyOf(a, n, Object[].class);
227     if (screen && (n == 1 || this.comparator != null)) {
228     for (int i = 0; i < n; ++i)
229 dl 1.59 if (a[i] == null)
230     throw new NullPointerException();
231 dl 1.66 }
232 dl 1.59 this.queue = a;
233 dl 1.66 this.size = n;
234     if (heapify)
235     heapify();
236 dl 1.59 }
237    
238     /**
239 dl 1.66 * Tries to grow array to accommodate at least one more element
240     * (but normally expand by about 50%), giving up (allowing retry)
241     * on contention (which we expect to be rare). Call only while
242     * holding lock.
243 jsr166 1.67 *
244 dl 1.66 * @param array the heap array
245     * @param oldCap the length of the array
246 dl 1.59 */
247 dl 1.66 private void tryGrow(Object[] array, int oldCap) {
248 dl 1.59 lock.unlock(); // must release and then re-acquire main lock
249     Object[] newArray = null;
250     if (allocationSpinLock == 0 &&
251 jsr166 1.61 UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
252 dl 1.59 0, 1)) {
253     try {
254     int newCap = oldCap + ((oldCap < 64) ?
255 dl 1.66 (oldCap + 2) : // grow faster if small
256 dl 1.59 (oldCap >> 1));
257 dl 1.66 if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
258     int minCap = oldCap + 1;
259 dl 1.59 if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
260     throw new OutOfMemoryError();
261     newCap = MAX_ARRAY_SIZE;
262     }
263 dl 1.66 if (newCap > oldCap && queue == array)
264 dl 1.59 newArray = new Object[newCap];
265     } finally {
266     allocationSpinLock = 0;
267     }
268     }
269 dl 1.66 if (newArray == null) // back off if another thread is allocating
270 dl 1.59 Thread.yield();
271     lock.lock();
272     if (newArray != null && queue == array) {
273     queue = newArray;
274 dl 1.66 System.arraycopy(array, 0, newArray, 0, oldCap);
275 dl 1.59 }
276     }
277    
278     /**
279 jsr166 1.62 * Mechanics for poll(). Call only while holding lock.
280 dl 1.59 */
281 dl 1.66 private E extract() {
282     E result;
283     int n = size - 1;
284     if (n < 0)
285     result = null;
286     else {
287     Object[] array = queue;
288     result = (E) array[0];
289     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 dl 1.59 }
298 dl 1.66 return result;
299 dl 1.59 }
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 dl 1.66 E result;
494 jsr166 1.42 try {
495 dl 1.66 result = extract();
496 jsr166 1.42 } finally {
497     lock.unlock();
498     }
499 dl 1.66 return result;
500 jsr166 1.42 }
501    
502 dl 1.5 public E take() throws InterruptedException {
503 dl 1.31 final ReentrantLock lock = this.lock;
504 dl 1.5 lock.lockInterruptibly();
505 dl 1.66 E result;
506 dl 1.5 try {
507 dl 1.66 while ( (result = extract()) == null)
508 jsr166 1.55 notEmpty.await();
509 tim 1.19 } finally {
510 dl 1.5 lock.unlock();
511     }
512 dl 1.59 return result;
513 dl 1.5 }
514    
515     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
516 dholmes 1.10 long nanos = unit.toNanos(timeout);
517 dl 1.31 final ReentrantLock lock = this.lock;
518 dl 1.5 lock.lockInterruptibly();
519 dl 1.66 E result;
520 dl 1.5 try {
521 dl 1.66 while ( (result = extract()) == null && nanos > 0)
522 jsr166 1.55 nanos = notEmpty.awaitNanos(nanos);
523 tim 1.19 } finally {
524 dl 1.5 lock.unlock();
525     }
526 dl 1.59 return result;
527 dl 1.5 }
528    
529     public E peek() {
530 dl 1.31 final ReentrantLock lock = this.lock;
531 dl 1.5 lock.lock();
532 dl 1.66 E result;
533 dl 1.5 try {
534 dl 1.66 result = size > 0 ? (E) queue[0] : null;
535 tim 1.19 } finally {
536 tim 1.13 lock.unlock();
537 dl 1.5 }
538 dl 1.59 return result;
539 dl 1.5 }
540 jsr166 1.61
541 jsr166 1.42 /**
542     * Returns the comparator used to order the elements in this queue,
543 jsr166 1.63 * or {@code null} if this queue uses the {@linkplain Comparable
544 jsr166 1.42 * natural ordering} of its elements.
545     *
546     * @return the comparator used to order the elements in this queue,
547 jsr166 1.63 * or {@code null} if this queue uses the natural
548 jsr166 1.52 * ordering of its elements
549 jsr166 1.42 */
550     public Comparator<? super E> comparator() {
551 dl 1.59 return comparator;
552 jsr166 1.42 }
553    
554 dl 1.5 public int size() {
555 dl 1.31 final ReentrantLock lock = this.lock;
556 dl 1.5 lock.lock();
557     try {
558 jsr166 1.68 return size;
559 tim 1.19 } finally {
560 dl 1.5 lock.unlock();
561     }
562     }
563    
564     /**
565 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
566     * a {@code PriorityBlockingQueue} is not capacity constrained.
567     * @return {@code Integer.MAX_VALUE} always
568 dl 1.5 */
569     public int remainingCapacity() {
570     return Integer.MAX_VALUE;
571     }
572    
573 dl 1.59 private int indexOf(Object o) {
574     if (o != null) {
575 dl 1.66 Object[] array = queue;
576     int n = size;
577     for (int i = 0; i < n; i++)
578     if (o.equals(array[i]))
579 dl 1.59 return i;
580     }
581     return -1;
582     }
583    
584     /**
585     * Removes the ith element from queue.
586     */
587     private void removeAt(int i) {
588 dl 1.66 Object[] array = queue;
589     int n = size - 1;
590     if (n == i) // removed last element
591     array[i] = null;
592 dl 1.59 else {
593 dl 1.66 E moved = (E) array[n];
594     array[n] = null;
595     Comparator<? super E> cmp = comparator;
596 jsr166 1.67 if (cmp == null)
597 dl 1.66 siftDownComparable(i, moved, array, n);
598     else
599     siftDownUsingComparator(i, moved, array, n, cmp);
600     if (array[i] == moved) {
601     if (cmp == null)
602     siftUpComparable(i, moved, array);
603     else
604     siftUpUsingComparator(i, moved, array, cmp);
605     }
606 dl 1.59 }
607 dl 1.66 size = n;
608 dl 1.59 }
609    
610 dl 1.37 /**
611 jsr166 1.42 * Removes a single instance of the specified element from this queue,
612 jsr166 1.52 * if it is present. More formally, removes an element {@code e} such
613     * that {@code o.equals(e)}, if this queue contains one or more such
614     * elements. Returns {@code true} if and only if this queue contained
615     * the specified element (or equivalently, if this queue changed as a
616     * result of the call).
617 jsr166 1.42 *
618     * @param o element to be removed from this queue, if present
619 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
620 dl 1.37 */
621 dholmes 1.14 public boolean remove(Object o) {
622 dl 1.59 boolean removed = false;
623 dl 1.31 final ReentrantLock lock = this.lock;
624 dl 1.5 lock.lock();
625     try {
626 dl 1.59 int i = indexOf(o);
627     if (i != -1) {
628     removeAt(i);
629     removed = true;
630     }
631     } finally {
632     lock.unlock();
633     }
634     return removed;
635     }
636    
637    
638     /**
639     * Identity-based version for use in Itr.remove
640     */
641     private void removeEQ(Object o) {
642     final ReentrantLock lock = this.lock;
643     lock.lock();
644     try {
645 dl 1.66 Object[] array = queue;
646     int n = size;
647     for (int i = 0; i < n; i++) {
648     if (o == array[i]) {
649 dl 1.59 removeAt(i);
650     break;
651     }
652     }
653 tim 1.19 } finally {
654 dl 1.5 lock.unlock();
655     }
656     }
657    
658 jsr166 1.42 /**
659 jsr166 1.52 * Returns {@code true} if this queue contains the specified element.
660     * More formally, returns {@code true} if and only if this queue contains
661     * at least one element {@code e} such that {@code o.equals(e)}.
662 jsr166 1.42 *
663     * @param o object to be checked for containment in this queue
664 jsr166 1.63 * @return {@code true} if this queue contains the specified element
665 jsr166 1.42 */
666 dholmes 1.14 public boolean contains(Object o) {
667 dl 1.59 int index;
668 dl 1.31 final ReentrantLock lock = this.lock;
669 dl 1.5 lock.lock();
670     try {
671 dl 1.59 index = indexOf(o);
672 tim 1.19 } finally {
673 dl 1.5 lock.unlock();
674     }
675 dl 1.59 return index != -1;
676 dl 1.5 }
677    
678 jsr166 1.42 /**
679     * Returns an array containing all of the elements in this queue.
680     * The returned array elements are in no particular order.
681     *
682     * <p>The returned array will be "safe" in that no references to it are
683     * maintained by this queue. (In other words, this method must allocate
684     * a new array). The caller is thus free to modify the returned array.
685 jsr166 1.43 *
686 jsr166 1.42 * <p>This method acts as bridge between array-based and collection-based
687     * APIs.
688     *
689     * @return an array containing all of the elements in this queue
690     */
691 dl 1.5 public Object[] toArray() {
692 dl 1.31 final ReentrantLock lock = this.lock;
693 dl 1.5 lock.lock();
694     try {
695 dl 1.59 return Arrays.copyOf(queue, size);
696 tim 1.19 } finally {
697 dl 1.5 lock.unlock();
698     }
699     }
700    
701 jsr166 1.52
702 dl 1.5 public String toString() {
703 dl 1.31 final ReentrantLock lock = this.lock;
704 dl 1.5 lock.lock();
705     try {
706 dl 1.59 int n = size;
707     if (n == 0)
708     return "[]";
709     StringBuilder sb = new StringBuilder();
710     sb.append('[');
711     for (int i = 0; i < n; ++i) {
712     E e = (E)queue[i];
713     sb.append(e == this ? "(this Collection)" : e);
714     if (i != n - 1)
715     sb.append(',').append(' ');
716     }
717     return sb.append(']').toString();
718 tim 1.19 } finally {
719 dl 1.5 lock.unlock();
720     }
721     }
722    
723 jsr166 1.42 /**
724     * @throws UnsupportedOperationException {@inheritDoc}
725     * @throws ClassCastException {@inheritDoc}
726     * @throws NullPointerException {@inheritDoc}
727     * @throws IllegalArgumentException {@inheritDoc}
728     */
729 dl 1.26 public int drainTo(Collection<? super E> c) {
730     if (c == null)
731     throw new NullPointerException();
732     if (c == this)
733     throw new IllegalArgumentException();
734 dl 1.31 final ReentrantLock lock = this.lock;
735 dl 1.26 lock.lock();
736     try {
737     int n = 0;
738     E e;
739 dl 1.66 while ( (e = extract()) != null) {
740 dl 1.26 c.add(e);
741     ++n;
742     }
743     return n;
744     } finally {
745     lock.unlock();
746     }
747     }
748    
749 jsr166 1.42 /**
750     * @throws UnsupportedOperationException {@inheritDoc}
751     * @throws ClassCastException {@inheritDoc}
752     * @throws NullPointerException {@inheritDoc}
753     * @throws IllegalArgumentException {@inheritDoc}
754     */
755 dl 1.26 public int drainTo(Collection<? super E> c, int maxElements) {
756     if (c == null)
757     throw new NullPointerException();
758     if (c == this)
759     throw new IllegalArgumentException();
760     if (maxElements <= 0)
761     return 0;
762 dl 1.31 final ReentrantLock lock = this.lock;
763 dl 1.26 lock.lock();
764     try {
765     int n = 0;
766     E e;
767 dl 1.66 while (n < maxElements && (e = extract()) != null) {
768 dl 1.26 c.add(e);
769     ++n;
770     }
771     return n;
772     } finally {
773     lock.unlock();
774     }
775     }
776    
777 dl 1.17 /**
778 dl 1.37 * Atomically removes all of the elements from this queue.
779 dl 1.17 * The queue will be empty after this call returns.
780     */
781     public void clear() {
782 dl 1.31 final ReentrantLock lock = this.lock;
783 dl 1.17 lock.lock();
784     try {
785 dl 1.66 Object[] array = queue;
786     int n = size;
787 dl 1.59 size = 0;
788 dl 1.66 for (int i = 0; i < n; i++)
789     array[i] = null;
790 tim 1.19 } finally {
791 dl 1.17 lock.unlock();
792     }
793     }
794    
795 jsr166 1.42 /**
796     * Returns an array containing all of the elements in this queue; the
797     * runtime type of the returned array is that of the specified array.
798     * The returned array elements are in no particular order.
799     * If the queue fits in the specified array, it is returned therein.
800     * Otherwise, a new array is allocated with the runtime type of the
801     * specified array and the size of this queue.
802     *
803     * <p>If this queue fits in the specified array with room to spare
804     * (i.e., the array has more elements than this queue), the element in
805     * the array immediately following the end of the queue is set to
806 jsr166 1.63 * {@code null}.
807 jsr166 1.42 *
808     * <p>Like the {@link #toArray()} method, this method acts as bridge between
809     * array-based and collection-based APIs. Further, this method allows
810     * precise control over the runtime type of the output array, and may,
811     * under certain circumstances, be used to save allocation costs.
812     *
813 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
814 jsr166 1.42 * The following code can be used to dump the queue into a newly
815 jsr166 1.63 * allocated array of {@code String}:
816 jsr166 1.42 *
817 jsr166 1.73 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
818 jsr166 1.42 *
819 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
820     * {@code toArray()}.
821 jsr166 1.42 *
822     * @param a the array into which the elements of the queue are to
823     * be stored, if it is big enough; otherwise, a new array of the
824     * same runtime type is allocated for this purpose
825     * @return an array containing all of the elements in this queue
826     * @throws ArrayStoreException if the runtime type of the specified array
827     * is not a supertype of the runtime type of every element in
828     * this queue
829     * @throws NullPointerException if the specified array is null
830     */
831 dl 1.5 public <T> T[] toArray(T[] a) {
832 dl 1.31 final ReentrantLock lock = this.lock;
833 dl 1.5 lock.lock();
834     try {
835 dl 1.66 int n = size;
836     if (a.length < n)
837 dl 1.59 // Make a new array of a's runtime type, but my contents:
838     return (T[]) Arrays.copyOf(queue, size, a.getClass());
839 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
840     if (a.length > n)
841     a[n] = null;
842 dl 1.59 return a;
843 tim 1.19 } finally {
844 dl 1.5 lock.unlock();
845     }
846     }
847    
848 dholmes 1.16 /**
849 dl 1.23 * Returns an iterator over the elements in this queue. The
850     * iterator does not return the elements in any particular order.
851 jsr166 1.69 *
852     * <p>The returned iterator is a "weakly consistent" iterator that
853     * will never throw {@link java.util.ConcurrentModificationException
854 dl 1.51 * ConcurrentModificationException}, and guarantees to traverse
855     * elements as they existed upon construction of the iterator, and
856     * may (but is not guaranteed to) reflect any modifications
857     * subsequent to construction.
858 dholmes 1.16 *
859 jsr166 1.42 * @return an iterator over the elements in this queue
860 dholmes 1.16 */
861 dl 1.5 public Iterator<E> iterator() {
862 dl 1.51 return new Itr(toArray());
863 dl 1.5 }
864    
865 dl 1.49 /**
866     * Snapshot iterator that works off copy of underlying q array.
867     */
868 dl 1.59 final class Itr implements Iterator<E> {
869 dl 1.49 final Object[] array; // Array of all elements
870 jsr166 1.54 int cursor; // index of next element to return;
871     int lastRet; // index of last element, or -1 if no such
872 jsr166 1.50
873 dl 1.49 Itr(Object[] array) {
874     lastRet = -1;
875     this.array = array;
876 dl 1.5 }
877    
878 tim 1.13 public boolean hasNext() {
879 dl 1.49 return cursor < array.length;
880 tim 1.13 }
881    
882     public E next() {
883 dl 1.49 if (cursor >= array.length)
884     throw new NoSuchElementException();
885     lastRet = cursor;
886     return (E)array[cursor++];
887 tim 1.13 }
888    
889     public void remove() {
890 jsr166 1.50 if (lastRet < 0)
891 jsr166 1.54 throw new IllegalStateException();
892 dl 1.59 removeEQ(array[lastRet]);
893 dl 1.49 lastRet = -1;
894 tim 1.13 }
895 dl 1.5 }
896    
897     /**
898 dl 1.59 * Saves the state to a stream (that is, serializes it). For
899     * compatibility with previous version of this class,
900     * elements are first copied to a java.util.PriorityQueue,
901     * which is then serialized.
902 dl 1.5 */
903     private void writeObject(java.io.ObjectOutputStream s)
904     throws java.io.IOException {
905     lock.lock();
906     try {
907 dl 1.60 int n = size; // avoid zero capacity argument
908     q = new PriorityQueue<E>(n == 0 ? 1 : n, comparator);
909 dl 1.59 q.addAll(this);
910 dl 1.5 s.defaultWriteObject();
911 dl 1.66 } finally {
912 dl 1.59 q = null;
913 dl 1.5 lock.unlock();
914     }
915 tim 1.1 }
916    
917 dl 1.59 /**
918     * Reconstitutes the {@code PriorityBlockingQueue} instance from a stream
919     * (that is, deserializes it).
920     *
921     * @param s the stream
922     */
923     private void readObject(java.io.ObjectInputStream s)
924     throws java.io.IOException, ClassNotFoundException {
925 jsr166 1.67 try {
926 dl 1.66 s.defaultReadObject();
927     this.queue = new Object[q.size()];
928     comparator = q.comparator();
929     addAll(q);
930 jsr166 1.67 } finally {
931 dl 1.66 q = null;
932     }
933 dl 1.59 }
934    
935     // Unsafe mechanics
936 dl 1.70 private static final sun.misc.Unsafe UNSAFE;
937     private static final long allocationSpinLockOffset;
938     static {
939 dl 1.59 try {
940 dl 1.70 UNSAFE = sun.misc.Unsafe.getUnsafe();
941 jsr166 1.72 Class<?> k = PriorityBlockingQueue.class;
942 dl 1.70 allocationSpinLockOffset = UNSAFE.objectFieldOffset
943     (k.getDeclaredField("allocationSpinLock"));
944     } catch (Exception e) {
945     throw new Error(e);
946 dl 1.59 }
947     }
948 tim 1.1 }