ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.76
Committed: Mon Jun 27 21:01:06 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.75: +5 -20 lines
Log Message:
make drainTo methods more robust when c.add throws

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     int n = size - 1;
283     if (n < 0)
284 jsr166 1.74 return null;
285 dl 1.66 else {
286     Object[] array = queue;
287 jsr166 1.74 E result = (E) array[0];
288 dl 1.66 E x = (E) array[n];
289     array[n] = null;
290     Comparator<? super E> cmp = comparator;
291     if (cmp == null)
292     siftDownComparable(0, x, array, n);
293 jsr166 1.67 else
294 dl 1.66 siftDownUsingComparator(0, x, array, n, cmp);
295     size = n;
296 jsr166 1.74 return result;
297 dl 1.59 }
298     }
299    
300     /**
301     * Inserts item x at position k, maintaining heap invariant by
302     * promoting x up the tree until it is greater than or equal to
303     * its parent, or is the root.
304     *
305     * To simplify and speed up coercions and comparisons. the
306     * Comparable and Comparator versions are separated into different
307     * methods that are otherwise identical. (Similarly for siftDown.)
308 dl 1.66 * These methods are static, with heap state as arguments, to
309     * simplify use in light of possible comparator exceptions.
310 dl 1.59 *
311     * @param k the position to fill
312     * @param x the item to insert
313 dl 1.66 * @param array the heap array
314     * @param n heap size
315 dl 1.59 */
316 dl 1.66 private static <T> void siftUpComparable(int k, T x, Object[] array) {
317     Comparable<? super T> key = (Comparable<? super T>) x;
318 dl 1.59 while (k > 0) {
319     int parent = (k - 1) >>> 1;
320 dl 1.66 Object e = array[parent];
321     if (key.compareTo((T) e) >= 0)
322 dl 1.59 break;
323 dl 1.66 array[k] = e;
324 dl 1.59 k = parent;
325     }
326 dl 1.66 array[k] = key;
327 dl 1.59 }
328    
329 dl 1.66 private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
330     Comparator<? super T> cmp) {
331 dl 1.59 while (k > 0) {
332     int parent = (k - 1) >>> 1;
333 dl 1.66 Object e = array[parent];
334     if (cmp.compare(x, (T) e) >= 0)
335 dl 1.59 break;
336 dl 1.66 array[k] = e;
337 dl 1.59 k = parent;
338     }
339 dl 1.66 array[k] = x;
340 dl 1.59 }
341    
342     /**
343     * Inserts item x at position k, maintaining heap invariant by
344     * demoting x down the tree repeatedly until it is less than or
345     * equal to its children or is a leaf.
346     *
347     * @param k the position to fill
348     * @param x the item to insert
349 dl 1.66 * @param array the heap array
350     * @param n heap size
351 dl 1.59 */
352 jsr166 1.67 private static <T> void siftDownComparable(int k, T x, Object[] array,
353 dl 1.66 int n) {
354     Comparable<? super T> key = (Comparable<? super T>)x;
355     int half = n >>> 1; // loop while a non-leaf
356 dl 1.59 while (k < half) {
357     int child = (k << 1) + 1; // assume left child is least
358 dl 1.66 Object c = array[child];
359 dl 1.59 int right = child + 1;
360 dl 1.66 if (right < n &&
361     ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
362     c = array[child = right];
363     if (key.compareTo((T) c) <= 0)
364 dl 1.59 break;
365 dl 1.66 array[k] = c;
366 dl 1.59 k = child;
367     }
368 dl 1.66 array[k] = key;
369 dl 1.59 }
370    
371 dl 1.66 private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
372     int n,
373     Comparator<? super T> cmp) {
374     int half = n >>> 1;
375 dl 1.59 while (k < half) {
376     int child = (k << 1) + 1;
377 dl 1.66 Object c = array[child];
378 dl 1.59 int right = child + 1;
379 dl 1.66 if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
380     c = array[child = right];
381     if (cmp.compare(x, (T) c) <= 0)
382 dl 1.59 break;
383 dl 1.66 array[k] = c;
384 dl 1.59 k = child;
385     }
386 dl 1.66 array[k] = x;
387 dl 1.7 }
388    
389 dholmes 1.10 /**
390 dl 1.59 * Establishes the heap invariant (described above) in the entire tree,
391     * assuming nothing about the order of the elements prior to the call.
392     */
393     private void heapify() {
394 dl 1.66 Object[] array = queue;
395     int n = size;
396     int half = (n >>> 1) - 1;
397     Comparator<? super E> cmp = comparator;
398     if (cmp == null) {
399     for (int i = half; i >= 0; i--)
400     siftDownComparable(i, (E) array[i], array, n);
401     }
402     else {
403     for (int i = half; i >= 0; i--)
404     siftDownUsingComparator(i, (E) array[i], array, n, cmp);
405     }
406 dl 1.59 }
407    
408     /**
409 jsr166 1.42 * Inserts the specified element into this priority queue.
410     *
411 jsr166 1.40 * @param e the element to add
412 jsr166 1.63 * @return {@code true} (as specified by {@link Collection#add})
413 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
414 jsr166 1.42 * with elements currently in the priority queue according to the
415     * priority queue's ordering
416     * @throws NullPointerException if the specified element is null
417 dholmes 1.10 */
418 jsr166 1.40 public boolean add(E e) {
419 jsr166 1.42 return offer(e);
420 dl 1.5 }
421    
422 dholmes 1.16 /**
423 dl 1.24 * Inserts the specified element into this priority queue.
424 jsr166 1.64 * As the queue is unbounded, this method will never return {@code false}.
425 dholmes 1.16 *
426 jsr166 1.40 * @param e the element to add
427 jsr166 1.63 * @return {@code true} (as specified by {@link Queue#offer})
428 dholmes 1.16 * @throws ClassCastException if the specified element cannot be compared
429 jsr166 1.42 * with elements currently in the priority queue according to the
430     * priority queue's ordering
431     * @throws NullPointerException if the specified element is null
432 dholmes 1.16 */
433 jsr166 1.40 public boolean offer(E e) {
434 dl 1.59 if (e == null)
435     throw new NullPointerException();
436 dl 1.31 final ReentrantLock lock = this.lock;
437 dl 1.5 lock.lock();
438 dl 1.66 int n, cap;
439 dl 1.59 Object[] array;
440 dl 1.66 while ((n = size) >= (cap = (array = queue).length))
441     tryGrow(array, cap);
442 dl 1.59 try {
443 dl 1.66 Comparator<? super E> cmp = comparator;
444     if (cmp == null)
445     siftUpComparable(n, e, array);
446 dl 1.59 else
447 dl 1.66 siftUpUsingComparator(n, e, array, cmp);
448     size = n + 1;
449 dl 1.5 notEmpty.signal();
450 tim 1.19 } finally {
451 tim 1.13 lock.unlock();
452 dl 1.5 }
453 dl 1.59 return true;
454 dl 1.5 }
455    
456 dholmes 1.16 /**
457 jsr166 1.64 * Inserts the specified element into this priority queue.
458     * As the queue is unbounded, this method will never block.
459 jsr166 1.42 *
460 jsr166 1.40 * @param e the element to add
461 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
462     * with elements currently in the priority queue according to the
463     * priority queue's ordering
464     * @throws NullPointerException if the specified element is null
465 dholmes 1.16 */
466 jsr166 1.40 public void put(E e) {
467     offer(e); // never need to block
468 dl 1.5 }
469    
470 dholmes 1.16 /**
471 jsr166 1.64 * Inserts the specified element into this priority queue.
472     * As the queue is unbounded, this method will never block or
473     * return {@code false}.
474 jsr166 1.42 *
475 jsr166 1.40 * @param e the element to add
476 dholmes 1.16 * @param timeout This parameter is ignored as the method never blocks
477     * @param unit This parameter is ignored as the method never blocks
478 jsr166 1.65 * @return {@code true} (as specified by
479     * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
480 jsr166 1.42 * @throws ClassCastException if the specified element cannot be compared
481     * with elements currently in the priority queue according to the
482     * priority queue's ordering
483     * @throws NullPointerException if the specified element is null
484 dholmes 1.16 */
485 jsr166 1.40 public boolean offer(E e, long timeout, TimeUnit unit) {
486     return offer(e); // never need to block
487 dl 1.5 }
488    
489 jsr166 1.42 public E poll() {
490     final ReentrantLock lock = this.lock;
491     lock.lock();
492     try {
493 jsr166 1.74 return extract();
494 jsr166 1.42 } finally {
495     lock.unlock();
496     }
497     }
498    
499 dl 1.5 public E take() throws InterruptedException {
500 dl 1.31 final ReentrantLock lock = this.lock;
501 dl 1.5 lock.lockInterruptibly();
502 dl 1.66 E result;
503 dl 1.5 try {
504 dl 1.66 while ( (result = extract()) == null)
505 jsr166 1.55 notEmpty.await();
506 tim 1.19 } finally {
507 dl 1.5 lock.unlock();
508     }
509 dl 1.59 return result;
510 dl 1.5 }
511    
512     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
513 dholmes 1.10 long nanos = unit.toNanos(timeout);
514 dl 1.31 final ReentrantLock lock = this.lock;
515 dl 1.5 lock.lockInterruptibly();
516 dl 1.66 E result;
517 dl 1.5 try {
518 dl 1.66 while ( (result = extract()) == null && nanos > 0)
519 jsr166 1.55 nanos = notEmpty.awaitNanos(nanos);
520 tim 1.19 } finally {
521 dl 1.5 lock.unlock();
522     }
523 dl 1.59 return result;
524 dl 1.5 }
525    
526     public E peek() {
527 dl 1.31 final ReentrantLock lock = this.lock;
528 dl 1.5 lock.lock();
529     try {
530 jsr166 1.74 return (size == 0) ? null : (E) queue[0];
531 tim 1.19 } finally {
532 tim 1.13 lock.unlock();
533 dl 1.5 }
534     }
535 jsr166 1.61
536 jsr166 1.42 /**
537     * Returns the comparator used to order the elements in this queue,
538 jsr166 1.63 * or {@code null} if this queue uses the {@linkplain Comparable
539 jsr166 1.42 * natural ordering} of its elements.
540     *
541     * @return the comparator used to order the elements in this queue,
542 jsr166 1.63 * or {@code null} if this queue uses the natural
543 jsr166 1.52 * ordering of its elements
544 jsr166 1.42 */
545     public Comparator<? super E> comparator() {
546 dl 1.59 return comparator;
547 jsr166 1.42 }
548    
549 dl 1.5 public int size() {
550 dl 1.31 final ReentrantLock lock = this.lock;
551 dl 1.5 lock.lock();
552     try {
553 jsr166 1.68 return size;
554 tim 1.19 } finally {
555 dl 1.5 lock.unlock();
556     }
557     }
558    
559     /**
560 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
561     * a {@code PriorityBlockingQueue} is not capacity constrained.
562     * @return {@code Integer.MAX_VALUE} always
563 dl 1.5 */
564     public int remainingCapacity() {
565     return Integer.MAX_VALUE;
566     }
567    
568 dl 1.59 private int indexOf(Object o) {
569     if (o != null) {
570 dl 1.66 Object[] array = queue;
571     int n = size;
572     for (int i = 0; i < n; i++)
573     if (o.equals(array[i]))
574 dl 1.59 return i;
575     }
576     return -1;
577     }
578    
579     /**
580     * Removes the ith element from queue.
581     */
582     private void removeAt(int i) {
583 dl 1.66 Object[] array = queue;
584     int n = size - 1;
585     if (n == i) // removed last element
586     array[i] = null;
587 dl 1.59 else {
588 dl 1.66 E moved = (E) array[n];
589     array[n] = null;
590     Comparator<? super E> cmp = comparator;
591 jsr166 1.67 if (cmp == null)
592 dl 1.66 siftDownComparable(i, moved, array, n);
593     else
594     siftDownUsingComparator(i, moved, array, n, cmp);
595     if (array[i] == moved) {
596     if (cmp == null)
597     siftUpComparable(i, moved, array);
598     else
599     siftUpUsingComparator(i, moved, array, cmp);
600     }
601 dl 1.59 }
602 dl 1.66 size = n;
603 dl 1.59 }
604    
605 dl 1.37 /**
606 jsr166 1.42 * Removes a single instance of the specified element from this queue,
607 jsr166 1.52 * if it is present. More formally, removes an element {@code e} such
608     * that {@code o.equals(e)}, if this queue contains one or more such
609     * elements. Returns {@code true} if and only if this queue contained
610     * the specified element (or equivalently, if this queue changed as a
611     * result of the call).
612 jsr166 1.42 *
613     * @param o element to be removed from this queue, if present
614 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
615 dl 1.37 */
616 dholmes 1.14 public boolean remove(Object o) {
617 dl 1.59 boolean removed = false;
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     if (i != -1) {
623     removeAt(i);
624     removed = true;
625     }
626     } finally {
627     lock.unlock();
628     }
629     return removed;
630     }
631    
632    
633     /**
634     * Identity-based version for use in Itr.remove
635     */
636     private void removeEQ(Object o) {
637     final ReentrantLock lock = this.lock;
638     lock.lock();
639     try {
640 dl 1.66 Object[] array = queue;
641     int n = size;
642     for (int i = 0; i < n; i++) {
643     if (o == array[i]) {
644 dl 1.59 removeAt(i);
645     break;
646     }
647     }
648 tim 1.19 } finally {
649 dl 1.5 lock.unlock();
650     }
651     }
652    
653 jsr166 1.42 /**
654 jsr166 1.52 * Returns {@code true} if this queue contains the specified element.
655     * More formally, returns {@code true} if and only if this queue contains
656     * at least one element {@code e} such that {@code o.equals(e)}.
657 jsr166 1.42 *
658     * @param o object to be checked for containment in this queue
659 jsr166 1.63 * @return {@code true} if this queue contains the specified element
660 jsr166 1.42 */
661 dholmes 1.14 public boolean contains(Object o) {
662 dl 1.59 int index;
663 dl 1.31 final ReentrantLock lock = this.lock;
664 dl 1.5 lock.lock();
665     try {
666 dl 1.59 index = indexOf(o);
667 tim 1.19 } finally {
668 dl 1.5 lock.unlock();
669     }
670 dl 1.59 return index != -1;
671 dl 1.5 }
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 jsr166 1.52
697 dl 1.5 public String toString() {
698 dl 1.31 final ReentrantLock lock = this.lock;
699 dl 1.5 lock.lock();
700     try {
701 dl 1.59 int n = size;
702     if (n == 0)
703     return "[]";
704     StringBuilder sb = new StringBuilder();
705     sb.append('[');
706     for (int i = 0; i < n; ++i) {
707 jsr166 1.74 Object e = queue[i];
708 dl 1.59 sb.append(e == this ? "(this Collection)" : e);
709     if (i != n - 1)
710     sb.append(',').append(' ');
711     }
712     return sb.append(']').toString();
713 tim 1.19 } finally {
714 dl 1.5 lock.unlock();
715     }
716     }
717    
718 jsr166 1.42 /**
719     * @throws UnsupportedOperationException {@inheritDoc}
720     * @throws ClassCastException {@inheritDoc}
721     * @throws NullPointerException {@inheritDoc}
722     * @throws IllegalArgumentException {@inheritDoc}
723     */
724 dl 1.26 public int drainTo(Collection<? super E> c) {
725 jsr166 1.76 return drainTo(c, Integer.MAX_VALUE);
726 dl 1.26 }
727    
728 jsr166 1.42 /**
729     * @throws UnsupportedOperationException {@inheritDoc}
730     * @throws ClassCastException {@inheritDoc}
731     * @throws NullPointerException {@inheritDoc}
732     * @throws IllegalArgumentException {@inheritDoc}
733     */
734 dl 1.26 public int drainTo(Collection<? super E> c, int maxElements) {
735     if (c == null)
736     throw new NullPointerException();
737     if (c == this)
738     throw new IllegalArgumentException();
739     if (maxElements <= 0)
740     return 0;
741 dl 1.31 final ReentrantLock lock = this.lock;
742 dl 1.26 lock.lock();
743     try {
744 jsr166 1.76 int n = Math.min(size, maxElements);
745     for (int i = 0; i < n; i++) {
746     c.add((E) queue[0]); // In this order, in case add() throws.
747     extract();
748 dl 1.26 }
749     return n;
750     } finally {
751     lock.unlock();
752     }
753     }
754    
755 dl 1.17 /**
756 dl 1.37 * Atomically removes all of the elements from this queue.
757 dl 1.17 * The queue will be empty after this call returns.
758     */
759     public void clear() {
760 dl 1.31 final ReentrantLock lock = this.lock;
761 dl 1.17 lock.lock();
762     try {
763 dl 1.66 Object[] array = queue;
764     int n = size;
765 dl 1.59 size = 0;
766 dl 1.66 for (int i = 0; i < n; i++)
767     array[i] = null;
768 tim 1.19 } finally {
769 dl 1.17 lock.unlock();
770     }
771     }
772    
773 jsr166 1.42 /**
774     * Returns an array containing all of the elements in this queue; the
775     * runtime type of the returned array is that of the specified array.
776     * The returned array elements are in no particular order.
777     * If the queue fits in the specified array, it is returned therein.
778     * Otherwise, a new array is allocated with the runtime type of the
779     * specified array and the size of this queue.
780     *
781     * <p>If this queue fits in the specified array with room to spare
782     * (i.e., the array has more elements than this queue), the element in
783     * the array immediately following the end of the queue is set to
784 jsr166 1.63 * {@code null}.
785 jsr166 1.42 *
786     * <p>Like the {@link #toArray()} method, this method acts as bridge between
787     * array-based and collection-based APIs. Further, this method allows
788     * precise control over the runtime type of the output array, and may,
789     * under certain circumstances, be used to save allocation costs.
790     *
791 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
792 jsr166 1.42 * The following code can be used to dump the queue into a newly
793 jsr166 1.63 * allocated array of {@code String}:
794 jsr166 1.42 *
795 jsr166 1.73 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
796 jsr166 1.42 *
797 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
798     * {@code toArray()}.
799 jsr166 1.42 *
800     * @param a the array into which the elements of the queue are to
801     * be stored, if it is big enough; otherwise, a new array of the
802     * same runtime type is allocated for this purpose
803     * @return an array containing all of the elements in this queue
804     * @throws ArrayStoreException if the runtime type of the specified array
805     * is not a supertype of the runtime type of every element in
806     * this queue
807     * @throws NullPointerException if the specified array is null
808     */
809 dl 1.5 public <T> T[] toArray(T[] a) {
810 dl 1.31 final ReentrantLock lock = this.lock;
811 dl 1.5 lock.lock();
812     try {
813 dl 1.66 int n = size;
814     if (a.length < n)
815 dl 1.59 // Make a new array of a's runtime type, but my contents:
816     return (T[]) Arrays.copyOf(queue, size, a.getClass());
817 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
818     if (a.length > n)
819     a[n] = null;
820 dl 1.59 return a;
821 tim 1.19 } finally {
822 dl 1.5 lock.unlock();
823     }
824     }
825    
826 dholmes 1.16 /**
827 dl 1.23 * Returns an iterator over the elements in this queue. The
828     * iterator does not return the elements in any particular order.
829 jsr166 1.69 *
830     * <p>The returned iterator is a "weakly consistent" iterator that
831     * will never throw {@link java.util.ConcurrentModificationException
832 dl 1.51 * ConcurrentModificationException}, and guarantees to traverse
833     * elements as they existed upon construction of the iterator, and
834     * may (but is not guaranteed to) reflect any modifications
835     * subsequent to construction.
836 dholmes 1.16 *
837 jsr166 1.42 * @return an iterator over the elements in this queue
838 dholmes 1.16 */
839 dl 1.5 public Iterator<E> iterator() {
840 dl 1.51 return new Itr(toArray());
841 dl 1.5 }
842    
843 dl 1.49 /**
844     * Snapshot iterator that works off copy of underlying q array.
845     */
846 dl 1.59 final class Itr implements Iterator<E> {
847 dl 1.49 final Object[] array; // Array of all elements
848 jsr166 1.54 int cursor; // index of next element to return;
849     int lastRet; // index of last element, or -1 if no such
850 jsr166 1.50
851 dl 1.49 Itr(Object[] array) {
852     lastRet = -1;
853     this.array = array;
854 dl 1.5 }
855    
856 tim 1.13 public boolean hasNext() {
857 dl 1.49 return cursor < array.length;
858 tim 1.13 }
859    
860     public E next() {
861 dl 1.49 if (cursor >= array.length)
862     throw new NoSuchElementException();
863     lastRet = cursor;
864     return (E)array[cursor++];
865 tim 1.13 }
866    
867     public void remove() {
868 jsr166 1.50 if (lastRet < 0)
869 jsr166 1.54 throw new IllegalStateException();
870 dl 1.59 removeEQ(array[lastRet]);
871 dl 1.49 lastRet = -1;
872 tim 1.13 }
873 dl 1.5 }
874    
875     /**
876 dl 1.59 * Saves the state to a stream (that is, serializes it). For
877     * compatibility with previous version of this class,
878     * elements are first copied to a java.util.PriorityQueue,
879     * which is then serialized.
880 dl 1.5 */
881     private void writeObject(java.io.ObjectOutputStream s)
882     throws java.io.IOException {
883     lock.lock();
884     try {
885 dl 1.60 int n = size; // avoid zero capacity argument
886     q = new PriorityQueue<E>(n == 0 ? 1 : n, 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     * Reconstitutes the {@code PriorityBlockingQueue} instance from a stream
897     * (that is, deserializes it).
898     *
899     * @param s the stream
900     */
901     private void readObject(java.io.ObjectInputStream s)
902     throws java.io.IOException, ClassNotFoundException {
903 jsr166 1.67 try {
904 dl 1.66 s.defaultReadObject();
905     this.queue = new Object[q.size()];
906     comparator = q.comparator();
907     addAll(q);
908 jsr166 1.67 } finally {
909 dl 1.66 q = null;
910     }
911 dl 1.59 }
912    
913     // Unsafe mechanics
914 dl 1.70 private static final sun.misc.Unsafe UNSAFE;
915     private static final long allocationSpinLockOffset;
916     static {
917 dl 1.59 try {
918 dl 1.70 UNSAFE = sun.misc.Unsafe.getUnsafe();
919 jsr166 1.72 Class<?> k = PriorityBlockingQueue.class;
920 dl 1.70 allocationSpinLockOffset = UNSAFE.objectFieldOffset
921     (k.getDeclaredField("allocationSpinLock"));
922     } catch (Exception e) {
923     throw new Error(e);
924 dl 1.59 }
925     }
926 tim 1.1 }