ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.85
Committed: Sun Jun 17 11:13:21 2012 UTC (11 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.84: +30 -26 lines
Log Message:
Guard siftDown to avoid unnecessary item retention

File Contents

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