ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/PriorityBlockingQueue.java
Revision: 1.65
Committed: Mon Oct 11 18:27:39 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.64: +2 -1 lines
Log Message:
sync offer method @return javadoc

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