ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.67
Committed: Sun Oct 17 00:14:09 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.66: +7 -7 lines
Log Message:
whitespace

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     * http://creativecommons.org/licenses/publicdomain
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     private PriorityQueue q;
143    
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.59 int n;
556 dl 1.31 final ReentrantLock lock = this.lock;
557 dl 1.5 lock.lock();
558     try {
559 dl 1.59 n = size;
560 tim 1.19 } finally {
561 dl 1.5 lock.unlock();
562     }
563 dl 1.59 return n;
564 dl 1.5 }
565    
566     /**
567 jsr166 1.63 * Always returns {@code Integer.MAX_VALUE} because
568     * a {@code PriorityBlockingQueue} is not capacity constrained.
569     * @return {@code Integer.MAX_VALUE} always
570 dl 1.5 */
571     public int remainingCapacity() {
572     return Integer.MAX_VALUE;
573     }
574    
575 dl 1.59 private int indexOf(Object o) {
576     if (o != null) {
577 dl 1.66 Object[] array = queue;
578     int n = size;
579     for (int i = 0; i < n; i++)
580     if (o.equals(array[i]))
581 dl 1.59 return i;
582     }
583     return -1;
584     }
585    
586     /**
587     * Removes the ith element from queue.
588     */
589     private void removeAt(int i) {
590 dl 1.66 Object[] array = queue;
591     int n = size - 1;
592     if (n == i) // removed last element
593     array[i] = null;
594 dl 1.59 else {
595 dl 1.66 E moved = (E) array[n];
596     array[n] = null;
597     Comparator<? super E> cmp = comparator;
598 jsr166 1.67 if (cmp == null)
599 dl 1.66 siftDownComparable(i, moved, array, n);
600     else
601     siftDownUsingComparator(i, moved, array, n, cmp);
602     if (array[i] == moved) {
603     if (cmp == null)
604     siftUpComparable(i, moved, array);
605     else
606     siftUpUsingComparator(i, moved, array, cmp);
607     }
608 dl 1.59 }
609 dl 1.66 size = n;
610 dl 1.59 }
611    
612 dl 1.37 /**
613 jsr166 1.42 * Removes a single instance of the specified element from this queue,
614 jsr166 1.52 * if it is present. More formally, removes an element {@code e} such
615     * that {@code o.equals(e)}, if this queue contains one or more such
616     * elements. Returns {@code true} if and only if this queue contained
617     * the specified element (or equivalently, if this queue changed as a
618     * result of the call).
619 jsr166 1.42 *
620     * @param o element to be removed from this queue, if present
621 jsr166 1.63 * @return {@code true} if this queue changed as a result of the call
622 dl 1.37 */
623 dholmes 1.14 public boolean remove(Object o) {
624 dl 1.59 boolean removed = false;
625 dl 1.31 final ReentrantLock lock = this.lock;
626 dl 1.5 lock.lock();
627     try {
628 dl 1.59 int i = indexOf(o);
629     if (i != -1) {
630     removeAt(i);
631     removed = true;
632     }
633     } finally {
634     lock.unlock();
635     }
636     return removed;
637     }
638    
639    
640     /**
641     * Identity-based version for use in Itr.remove
642     */
643     private void removeEQ(Object o) {
644     final ReentrantLock lock = this.lock;
645     lock.lock();
646     try {
647 dl 1.66 Object[] array = queue;
648     int n = size;
649     for (int i = 0; i < n; i++) {
650     if (o == array[i]) {
651 dl 1.59 removeAt(i);
652     break;
653     }
654     }
655 tim 1.19 } finally {
656 dl 1.5 lock.unlock();
657     }
658     }
659    
660 jsr166 1.42 /**
661 jsr166 1.52 * Returns {@code true} if this queue contains the specified element.
662     * More formally, returns {@code true} if and only if this queue contains
663     * at least one element {@code e} such that {@code o.equals(e)}.
664 jsr166 1.42 *
665     * @param o object to be checked for containment in this queue
666 jsr166 1.63 * @return {@code true} if this queue contains the specified element
667 jsr166 1.42 */
668 dholmes 1.14 public boolean contains(Object o) {
669 dl 1.59 int index;
670 dl 1.31 final ReentrantLock lock = this.lock;
671 dl 1.5 lock.lock();
672     try {
673 dl 1.59 index = indexOf(o);
674 tim 1.19 } finally {
675 dl 1.5 lock.unlock();
676     }
677 dl 1.59 return index != -1;
678 dl 1.5 }
679    
680 jsr166 1.42 /**
681     * Returns an array containing all of the elements in this queue.
682     * The returned array elements are in no particular order.
683     *
684     * <p>The returned array will be "safe" in that no references to it are
685     * maintained by this queue. (In other words, this method must allocate
686     * a new array). The caller is thus free to modify the returned array.
687 jsr166 1.43 *
688 jsr166 1.42 * <p>This method acts as bridge between array-based and collection-based
689     * APIs.
690     *
691     * @return an array containing all of the elements in this queue
692     */
693 dl 1.5 public Object[] toArray() {
694 dl 1.31 final ReentrantLock lock = this.lock;
695 dl 1.5 lock.lock();
696     try {
697 dl 1.59 return Arrays.copyOf(queue, size);
698 tim 1.19 } finally {
699 dl 1.5 lock.unlock();
700     }
701     }
702    
703 jsr166 1.52
704 dl 1.5 public String toString() {
705 dl 1.31 final ReentrantLock lock = this.lock;
706 dl 1.5 lock.lock();
707     try {
708 dl 1.59 int n = size;
709     if (n == 0)
710     return "[]";
711     StringBuilder sb = new StringBuilder();
712     sb.append('[');
713     for (int i = 0; i < n; ++i) {
714     E e = (E)queue[i];
715     sb.append(e == this ? "(this Collection)" : e);
716     if (i != n - 1)
717     sb.append(',').append(' ');
718     }
719     return sb.append(']').toString();
720 tim 1.19 } finally {
721 dl 1.5 lock.unlock();
722     }
723     }
724    
725 jsr166 1.42 /**
726     * @throws UnsupportedOperationException {@inheritDoc}
727     * @throws ClassCastException {@inheritDoc}
728     * @throws NullPointerException {@inheritDoc}
729     * @throws IllegalArgumentException {@inheritDoc}
730     */
731 dl 1.26 public int drainTo(Collection<? super E> c) {
732     if (c == null)
733     throw new NullPointerException();
734     if (c == this)
735     throw new IllegalArgumentException();
736 dl 1.31 final ReentrantLock lock = this.lock;
737 dl 1.26 lock.lock();
738     try {
739     int n = 0;
740     E e;
741 dl 1.66 while ( (e = extract()) != null) {
742 dl 1.26 c.add(e);
743     ++n;
744     }
745     return n;
746     } finally {
747     lock.unlock();
748     }
749     }
750    
751 jsr166 1.42 /**
752     * @throws UnsupportedOperationException {@inheritDoc}
753     * @throws ClassCastException {@inheritDoc}
754     * @throws NullPointerException {@inheritDoc}
755     * @throws IllegalArgumentException {@inheritDoc}
756     */
757 dl 1.26 public int drainTo(Collection<? super E> c, int maxElements) {
758     if (c == null)
759     throw new NullPointerException();
760     if (c == this)
761     throw new IllegalArgumentException();
762     if (maxElements <= 0)
763     return 0;
764 dl 1.31 final ReentrantLock lock = this.lock;
765 dl 1.26 lock.lock();
766     try {
767     int n = 0;
768     E e;
769 dl 1.66 while (n < maxElements && (e = extract()) != null) {
770 dl 1.26 c.add(e);
771     ++n;
772     }
773     return n;
774     } finally {
775     lock.unlock();
776     }
777     }
778    
779 dl 1.17 /**
780 dl 1.37 * Atomically removes all of the elements from this queue.
781 dl 1.17 * The queue will be empty after this call returns.
782     */
783     public void clear() {
784 dl 1.31 final ReentrantLock lock = this.lock;
785 dl 1.17 lock.lock();
786     try {
787 dl 1.66 Object[] array = queue;
788     int n = size;
789 dl 1.59 size = 0;
790 dl 1.66 for (int i = 0; i < n; i++)
791     array[i] = null;
792 tim 1.19 } finally {
793 dl 1.17 lock.unlock();
794     }
795     }
796    
797 jsr166 1.42 /**
798     * Returns an array containing all of the elements in this queue; the
799     * runtime type of the returned array is that of the specified array.
800     * The returned array elements are in no particular order.
801     * If the queue fits in the specified array, it is returned therein.
802     * Otherwise, a new array is allocated with the runtime type of the
803     * specified array and the size of this queue.
804     *
805     * <p>If this queue fits in the specified array with room to spare
806     * (i.e., the array has more elements than this queue), the element in
807     * the array immediately following the end of the queue is set to
808 jsr166 1.63 * {@code null}.
809 jsr166 1.42 *
810     * <p>Like the {@link #toArray()} method, this method acts as bridge between
811     * array-based and collection-based APIs. Further, this method allows
812     * precise control over the runtime type of the output array, and may,
813     * under certain circumstances, be used to save allocation costs.
814     *
815 jsr166 1.63 * <p>Suppose {@code x} is a queue known to contain only strings.
816 jsr166 1.42 * The following code can be used to dump the queue into a newly
817 jsr166 1.63 * allocated array of {@code String}:
818 jsr166 1.42 *
819     * <pre>
820     * String[] y = x.toArray(new String[0]);</pre>
821     *
822 jsr166 1.63 * Note that {@code toArray(new Object[0])} is identical in function to
823     * {@code toArray()}.
824 jsr166 1.42 *
825     * @param a the array into which the elements of the queue are to
826     * be stored, if it is big enough; otherwise, a new array of the
827     * same runtime type is allocated for this purpose
828     * @return an array containing all of the elements in this queue
829     * @throws ArrayStoreException if the runtime type of the specified array
830     * is not a supertype of the runtime type of every element in
831     * this queue
832     * @throws NullPointerException if the specified array is null
833     */
834 dl 1.5 public <T> T[] toArray(T[] a) {
835 dl 1.31 final ReentrantLock lock = this.lock;
836 dl 1.5 lock.lock();
837     try {
838 dl 1.66 int n = size;
839     if (a.length < n)
840 dl 1.59 // Make a new array of a's runtime type, but my contents:
841     return (T[]) Arrays.copyOf(queue, size, a.getClass());
842 dl 1.66 System.arraycopy(queue, 0, a, 0, n);
843     if (a.length > n)
844     a[n] = null;
845 dl 1.59 return a;
846 tim 1.19 } finally {
847 dl 1.5 lock.unlock();
848     }
849     }
850    
851 dholmes 1.16 /**
852 dl 1.23 * Returns an iterator over the elements in this queue. The
853     * iterator does not return the elements in any particular order.
854 jsr166 1.63 * The returned {@code Iterator} is a "weakly consistent"
855 dl 1.51 * iterator that will never throw {@link
856     * ConcurrentModificationException}, and guarantees to traverse
857     * elements as they existed upon construction of the iterator, and
858     * may (but is not guaranteed to) reflect any modifications
859     * subsequent to construction.
860 dholmes 1.16 *
861 jsr166 1.42 * @return an iterator over the elements in this queue
862 dholmes 1.16 */
863 dl 1.5 public Iterator<E> iterator() {
864 dl 1.51 return new Itr(toArray());
865 dl 1.5 }
866    
867 dl 1.49 /**
868     * Snapshot iterator that works off copy of underlying q array.
869     */
870 dl 1.59 final class Itr implements Iterator<E> {
871 dl 1.49 final Object[] array; // Array of all elements
872 jsr166 1.54 int cursor; // index of next element to return;
873     int lastRet; // index of last element, or -1 if no such
874 jsr166 1.50
875 dl 1.49 Itr(Object[] array) {
876     lastRet = -1;
877     this.array = array;
878 dl 1.5 }
879    
880 tim 1.13 public boolean hasNext() {
881 dl 1.49 return cursor < array.length;
882 tim 1.13 }
883    
884     public E next() {
885 dl 1.49 if (cursor >= array.length)
886     throw new NoSuchElementException();
887     lastRet = cursor;
888     return (E)array[cursor++];
889 tim 1.13 }
890    
891     public void remove() {
892 jsr166 1.50 if (lastRet < 0)
893 jsr166 1.54 throw new IllegalStateException();
894 dl 1.59 removeEQ(array[lastRet]);
895 dl 1.49 lastRet = -1;
896 tim 1.13 }
897 dl 1.5 }
898    
899     /**
900 dl 1.59 * Saves the state to a stream (that is, serializes it). For
901     * compatibility with previous version of this class,
902     * elements are first copied to a java.util.PriorityQueue,
903     * which is then serialized.
904 dl 1.5 */
905     private void writeObject(java.io.ObjectOutputStream s)
906     throws java.io.IOException {
907     lock.lock();
908     try {
909 dl 1.60 int n = size; // avoid zero capacity argument
910     q = new PriorityQueue<E>(n == 0 ? 1 : n, comparator);
911 dl 1.59 q.addAll(this);
912 dl 1.5 s.defaultWriteObject();
913 dl 1.66 } finally {
914 dl 1.59 q = null;
915 dl 1.5 lock.unlock();
916     }
917 tim 1.1 }
918    
919 dl 1.59 /**
920     * Reconstitutes the {@code PriorityBlockingQueue} instance from a stream
921     * (that is, deserializes it).
922     *
923     * @param s the stream
924     */
925     private void readObject(java.io.ObjectInputStream s)
926     throws java.io.IOException, ClassNotFoundException {
927 jsr166 1.67 try {
928 dl 1.66 s.defaultReadObject();
929     this.queue = new Object[q.size()];
930     comparator = q.comparator();
931     addAll(q);
932 jsr166 1.67 } finally {
933 dl 1.66 q = null;
934     }
935 dl 1.59 }
936    
937     // Unsafe mechanics
938     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
939     private static final long allocationSpinLockOffset =
940 jsr166 1.61 objectFieldOffset(UNSAFE, "allocationSpinLock",
941 dl 1.59 PriorityBlockingQueue.class);
942 jsr166 1.61
943 dl 1.59 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
944     String field, Class<?> klazz) {
945     try {
946     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
947     } catch (NoSuchFieldException e) {
948     // Convert Exception to corresponding Error
949     NoSuchFieldError error = new NoSuchFieldError(field);
950     error.initCause(e);
951     throw error;
952     }
953     }
954    
955 tim 1.1 }