jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent; jaroslav@1890: jaroslav@1890: import java.util.concurrent.locks.*; jaroslav@1890: import java.util.*; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * An unbounded {@linkplain BlockingQueue blocking queue} that uses jaroslav@1890: * the same ordering rules as class {@link PriorityQueue} and supplies jaroslav@1890: * blocking retrieval operations. While this queue is logically jaroslav@1890: * unbounded, attempted additions may fail due to resource exhaustion jaroslav@1890: * (causing {@code OutOfMemoryError}). This class does not permit jaroslav@1890: * {@code null} elements. A priority queue relying on {@linkplain jaroslav@1890: * Comparable natural ordering} also does not permit insertion of jaroslav@1890: * non-comparable objects (doing so results in jaroslav@1890: * {@code ClassCastException}). jaroslav@1890: * jaroslav@1890: *

This class and its iterator implement all of the jaroslav@1890: * optional methods of the {@link Collection} and {@link jaroslav@1890: * Iterator} interfaces. The Iterator provided in method {@link jaroslav@1890: * #iterator()} is not guaranteed to traverse the elements of jaroslav@1890: * the PriorityBlockingQueue in any particular order. If you need jaroslav@1890: * ordered traversal, consider using jaroslav@1890: * {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo} jaroslav@1890: * can be used to remove some or all elements in priority jaroslav@1890: * order and place them in another collection. jaroslav@1890: * jaroslav@1890: *

Operations on this class make no guarantees about the ordering jaroslav@1890: * of elements with equal priority. If you need to enforce an jaroslav@1890: * ordering, you can define custom classes or comparators that use a jaroslav@1890: * secondary key to break ties in primary priority values. For jaroslav@1890: * example, here is a class that applies first-in-first-out jaroslav@1890: * tie-breaking to comparable elements. To use it, you would insert a jaroslav@1890: * {@code new FIFOEntry(anEntry)} instead of a plain entry object. jaroslav@1890: * jaroslav@1890: *

 {@code
jaroslav@1890:  * class FIFOEntry>
jaroslav@1890:  *     implements Comparable> {
jaroslav@1890:  *   static final AtomicLong seq = new AtomicLong(0);
jaroslav@1890:  *   final long seqNum;
jaroslav@1890:  *   final E entry;
jaroslav@1890:  *   public FIFOEntry(E entry) {
jaroslav@1890:  *     seqNum = seq.getAndIncrement();
jaroslav@1890:  *     this.entry = entry;
jaroslav@1890:  *   }
jaroslav@1890:  *   public E getEntry() { return entry; }
jaroslav@1890:  *   public int compareTo(FIFOEntry other) {
jaroslav@1890:  *     int res = entry.compareTo(other.entry);
jaroslav@1890:  *     if (res == 0 && other.entry != this.entry)
jaroslav@1890:  *       res = (seqNum < other.seqNum ? -1 : 1);
jaroslav@1890:  *     return res;
jaroslav@1890:  *   }
jaroslav@1890:  * }}
jaroslav@1890: * jaroslav@1890: *

This class is a member of the jaroslav@1890: * jaroslav@1890: * Java Collections Framework. jaroslav@1890: * jaroslav@1890: * @since 1.5 jaroslav@1890: * @author Doug Lea jaroslav@1890: * @param the type of elements held in this collection jaroslav@1890: */ jaroslav@1890: public class PriorityBlockingQueue extends AbstractQueue jaroslav@1890: implements BlockingQueue, java.io.Serializable { jaroslav@1890: private static final long serialVersionUID = 5595510919245408276L; jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * The implementation uses an array-based binary heap, with public jaroslav@1890: * operations protected with a single lock. However, allocation jaroslav@1890: * during resizing uses a simple spinlock (used only while not jaroslav@1890: * holding main lock) in order to allow takes to operate jaroslav@1890: * concurrently with allocation. This avoids repeated jaroslav@1890: * postponement of waiting consumers and consequent element jaroslav@1890: * build-up. The need to back away from lock during allocation jaroslav@1890: * makes it impossible to simply wrap delegated jaroslav@1890: * java.util.PriorityQueue operations within a lock, as was done jaroslav@1890: * in a previous version of this class. To maintain jaroslav@1890: * interoperability, a plain PriorityQueue is still used during jaroslav@1890: * serialization, which maintains compatibility at the espense of jaroslav@1890: * transiently doubling overhead. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Default array capacity. jaroslav@1890: */ jaroslav@1890: private static final int DEFAULT_INITIAL_CAPACITY = 11; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The maximum size of array to allocate. jaroslav@1890: * Some VMs reserve some header words in an array. jaroslav@1890: * Attempts to allocate larger arrays may result in jaroslav@1890: * OutOfMemoryError: Requested array size exceeds VM limit jaroslav@1890: */ jaroslav@1890: private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Priority queue represented as a balanced binary heap: the two jaroslav@1890: * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The jaroslav@1890: * priority queue is ordered by comparator, or by the elements' jaroslav@1890: * natural ordering, if comparator is null: For each node n in the jaroslav@1890: * heap and each descendant d of n, n <= d. The element with the jaroslav@1890: * lowest value is in queue[0], assuming the queue is nonempty. jaroslav@1890: */ jaroslav@1890: private transient Object[] queue; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of elements in the priority queue. jaroslav@1890: */ jaroslav@1890: private transient int size; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The comparator, or null if priority queue uses elements' jaroslav@1890: * natural ordering. jaroslav@1890: */ jaroslav@1890: private transient Comparator comparator; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Lock used for all public operations jaroslav@1890: */ jaroslav@1890: private final ReentrantLock lock; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Condition for blocking when empty jaroslav@1890: */ jaroslav@1890: private final Condition notEmpty; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Spinlock for allocation, acquired via CAS. jaroslav@1890: */ jaroslav@1890: private transient volatile int allocationSpinLock; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * A plain PriorityQueue used only for serialization, jaroslav@1890: * to maintain compatibility with previous versions jaroslav@1890: * of this class. Non-null only during serialization/deserialization. jaroslav@1890: */ jaroslav@1890: private PriorityQueue q; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code PriorityBlockingQueue} with the default jaroslav@1890: * initial capacity (11) that orders its elements according to jaroslav@1890: * their {@linkplain Comparable natural ordering}. jaroslav@1890: */ jaroslav@1890: public PriorityBlockingQueue() { jaroslav@1890: this(DEFAULT_INITIAL_CAPACITY, null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code PriorityBlockingQueue} with the specified jaroslav@1890: * initial capacity that orders its elements according to their jaroslav@1890: * {@linkplain Comparable natural ordering}. jaroslav@1890: * jaroslav@1890: * @param initialCapacity the initial capacity for this priority queue jaroslav@1890: * @throws IllegalArgumentException if {@code initialCapacity} is less jaroslav@1890: * than 1 jaroslav@1890: */ jaroslav@1890: public PriorityBlockingQueue(int initialCapacity) { jaroslav@1890: this(initialCapacity, null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code PriorityBlockingQueue} with the specified initial jaroslav@1890: * capacity that orders its elements according to the specified jaroslav@1890: * comparator. jaroslav@1890: * jaroslav@1890: * @param initialCapacity the initial capacity for this priority queue jaroslav@1890: * @param comparator the comparator that will be used to order this jaroslav@1890: * priority queue. If {@code null}, the {@linkplain Comparable jaroslav@1890: * natural ordering} of the elements will be used. jaroslav@1890: * @throws IllegalArgumentException if {@code initialCapacity} is less jaroslav@1890: * than 1 jaroslav@1890: */ jaroslav@1890: public PriorityBlockingQueue(int initialCapacity, jaroslav@1890: Comparator comparator) { jaroslav@1890: if (initialCapacity < 1) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: this.lock = new ReentrantLock(); jaroslav@1890: this.notEmpty = lock.newCondition(); jaroslav@1890: this.comparator = comparator; jaroslav@1890: this.queue = new Object[initialCapacity]; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code PriorityBlockingQueue} containing the elements jaroslav@1890: * in the specified collection. If the specified collection is a jaroslav@1890: * {@link SortedSet} or a {@link PriorityQueue}, this jaroslav@1890: * priority queue will be ordered according to the same ordering. jaroslav@1890: * Otherwise, this priority queue will be ordered according to the jaroslav@1890: * {@linkplain Comparable natural ordering} of its elements. jaroslav@1890: * jaroslav@1890: * @param c the collection whose elements are to be placed jaroslav@1890: * into this priority queue jaroslav@1890: * @throws ClassCastException if elements of the specified collection jaroslav@1890: * cannot be compared to one another according to the priority jaroslav@1890: * queue's ordering jaroslav@1890: * @throws NullPointerException if the specified collection or any jaroslav@1890: * of its elements are null jaroslav@1890: */ jaroslav@1890: public PriorityBlockingQueue(Collection c) { jaroslav@1890: this.lock = new ReentrantLock(); jaroslav@1890: this.notEmpty = lock.newCondition(); jaroslav@1890: boolean heapify = true; // true if not known to be in heap order jaroslav@1890: boolean screen = true; // true if must screen for nulls jaroslav@1890: if (c instanceof SortedSet) { jaroslav@1890: SortedSet ss = (SortedSet) c; jaroslav@1890: this.comparator = (Comparator) ss.comparator(); jaroslav@1890: heapify = false; jaroslav@1890: } jaroslav@1890: else if (c instanceof PriorityBlockingQueue) { jaroslav@1890: PriorityBlockingQueue pq = jaroslav@1890: (PriorityBlockingQueue) c; jaroslav@1890: this.comparator = (Comparator) pq.comparator(); jaroslav@1890: screen = false; jaroslav@1890: if (pq.getClass() == PriorityBlockingQueue.class) // exact match jaroslav@1890: heapify = false; jaroslav@1890: } jaroslav@1890: Object[] a = c.toArray(); jaroslav@1890: int n = a.length; jaroslav@1890: // If c.toArray incorrectly doesn't return Object[], copy it. jaroslav@1890: if (a.getClass() != Object[].class) jaroslav@1890: a = Arrays.copyOf(a, n, Object[].class); jaroslav@1890: if (screen && (n == 1 || this.comparator != null)) { jaroslav@1890: for (int i = 0; i < n; ++i) jaroslav@1890: if (a[i] == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: } jaroslav@1890: this.queue = a; jaroslav@1890: this.size = n; jaroslav@1890: if (heapify) jaroslav@1890: heapify(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to grow array to accommodate at least one more element jaroslav@1890: * (but normally expand by about 50%), giving up (allowing retry) jaroslav@1890: * on contention (which we expect to be rare). Call only while jaroslav@1890: * holding lock. jaroslav@1890: * jaroslav@1890: * @param array the heap array jaroslav@1890: * @param oldCap the length of the array jaroslav@1890: */ jaroslav@1890: private void tryGrow(Object[] array, int oldCap) { jaroslav@1890: lock.unlock(); // must release and then re-acquire main lock jaroslav@1890: Object[] newArray = null; jaroslav@1890: if (allocationSpinLock == 0 && jaroslav@1890: UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset, jaroslav@1890: 0, 1)) { jaroslav@1890: try { jaroslav@1890: int newCap = oldCap + ((oldCap < 64) ? jaroslav@1890: (oldCap + 2) : // grow faster if small jaroslav@1890: (oldCap >> 1)); jaroslav@1890: if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow jaroslav@1890: int minCap = oldCap + 1; jaroslav@1890: if (minCap < 0 || minCap > MAX_ARRAY_SIZE) jaroslav@1890: throw new OutOfMemoryError(); jaroslav@1890: newCap = MAX_ARRAY_SIZE; jaroslav@1890: } jaroslav@1890: if (newCap > oldCap && queue == array) jaroslav@1890: newArray = new Object[newCap]; jaroslav@1890: } finally { jaroslav@1890: allocationSpinLock = 0; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: if (newArray == null) // back off if another thread is allocating jaroslav@1890: Thread.yield(); jaroslav@1890: lock.lock(); jaroslav@1890: if (newArray != null && queue == array) { jaroslav@1890: queue = newArray; jaroslav@1890: System.arraycopy(array, 0, newArray, 0, oldCap); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Mechanics for poll(). Call only while holding lock. jaroslav@1890: */ jaroslav@1890: private E extract() { jaroslav@1890: E result; jaroslav@1890: int n = size - 1; jaroslav@1890: if (n < 0) jaroslav@1890: result = null; jaroslav@1890: else { jaroslav@1890: Object[] array = queue; jaroslav@1890: result = (E) array[0]; jaroslav@1890: E x = (E) array[n]; jaroslav@1890: array[n] = null; jaroslav@1890: Comparator cmp = comparator; jaroslav@1890: if (cmp == null) jaroslav@1890: siftDownComparable(0, x, array, n); jaroslav@1890: else jaroslav@1890: siftDownUsingComparator(0, x, array, n, cmp); jaroslav@1890: size = n; jaroslav@1890: } jaroslav@1890: return result; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts item x at position k, maintaining heap invariant by jaroslav@1890: * promoting x up the tree until it is greater than or equal to jaroslav@1890: * its parent, or is the root. jaroslav@1890: * jaroslav@1890: * To simplify and speed up coercions and comparisons. the jaroslav@1890: * Comparable and Comparator versions are separated into different jaroslav@1890: * methods that are otherwise identical. (Similarly for siftDown.) jaroslav@1890: * These methods are static, with heap state as arguments, to jaroslav@1890: * simplify use in light of possible comparator exceptions. jaroslav@1890: * jaroslav@1890: * @param k the position to fill jaroslav@1890: * @param x the item to insert jaroslav@1890: * @param array the heap array jaroslav@1890: * @param n heap size jaroslav@1890: */ jaroslav@1890: private static void siftUpComparable(int k, T x, Object[] array) { jaroslav@1890: Comparable key = (Comparable) x; jaroslav@1890: while (k > 0) { jaroslav@1890: int parent = (k - 1) >>> 1; jaroslav@1890: Object e = array[parent]; jaroslav@1890: if (key.compareTo((T) e) >= 0) jaroslav@1890: break; jaroslav@1890: array[k] = e; jaroslav@1890: k = parent; jaroslav@1890: } jaroslav@1890: array[k] = key; jaroslav@1890: } jaroslav@1890: jaroslav@1890: private static void siftUpUsingComparator(int k, T x, Object[] array, jaroslav@1890: Comparator cmp) { jaroslav@1890: while (k > 0) { jaroslav@1890: int parent = (k - 1) >>> 1; jaroslav@1890: Object e = array[parent]; jaroslav@1890: if (cmp.compare(x, (T) e) >= 0) jaroslav@1890: break; jaroslav@1890: array[k] = e; jaroslav@1890: k = parent; jaroslav@1890: } jaroslav@1890: array[k] = x; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts item x at position k, maintaining heap invariant by jaroslav@1890: * demoting x down the tree repeatedly until it is less than or jaroslav@1890: * equal to its children or is a leaf. jaroslav@1890: * jaroslav@1890: * @param k the position to fill jaroslav@1890: * @param x the item to insert jaroslav@1890: * @param array the heap array jaroslav@1890: * @param n heap size jaroslav@1890: */ jaroslav@1890: private static void siftDownComparable(int k, T x, Object[] array, jaroslav@1890: int n) { jaroslav@1890: Comparable key = (Comparable)x; jaroslav@1890: int half = n >>> 1; // loop while a non-leaf jaroslav@1890: while (k < half) { jaroslav@1890: int child = (k << 1) + 1; // assume left child is least jaroslav@1890: Object c = array[child]; jaroslav@1890: int right = child + 1; jaroslav@1890: if (right < n && jaroslav@1890: ((Comparable) c).compareTo((T) array[right]) > 0) jaroslav@1890: c = array[child = right]; jaroslav@1890: if (key.compareTo((T) c) <= 0) jaroslav@1890: break; jaroslav@1890: array[k] = c; jaroslav@1890: k = child; jaroslav@1890: } jaroslav@1890: array[k] = key; jaroslav@1890: } jaroslav@1890: jaroslav@1890: private static void siftDownUsingComparator(int k, T x, Object[] array, jaroslav@1890: int n, jaroslav@1890: Comparator cmp) { jaroslav@1890: int half = n >>> 1; jaroslav@1890: while (k < half) { jaroslav@1890: int child = (k << 1) + 1; jaroslav@1890: Object c = array[child]; jaroslav@1890: int right = child + 1; jaroslav@1890: if (right < n && cmp.compare((T) c, (T) array[right]) > 0) jaroslav@1890: c = array[child = right]; jaroslav@1890: if (cmp.compare(x, (T) c) <= 0) jaroslav@1890: break; jaroslav@1890: array[k] = c; jaroslav@1890: k = child; jaroslav@1890: } jaroslav@1890: array[k] = x; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Establishes the heap invariant (described above) in the entire tree, jaroslav@1890: * assuming nothing about the order of the elements prior to the call. jaroslav@1890: */ jaroslav@1890: private void heapify() { jaroslav@1890: Object[] array = queue; jaroslav@1890: int n = size; jaroslav@1890: int half = (n >>> 1) - 1; jaroslav@1890: Comparator cmp = comparator; jaroslav@1890: if (cmp == null) { jaroslav@1890: for (int i = half; i >= 0; i--) jaroslav@1890: siftDownComparable(i, (E) array[i], array, n); jaroslav@1890: } jaroslav@1890: else { jaroslav@1890: for (int i = half; i >= 0; i--) jaroslav@1890: siftDownUsingComparator(i, (E) array[i], array, n, cmp); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this priority queue. jaroslav@1890: * jaroslav@1890: * @param e the element to add jaroslav@1890: * @return {@code true} (as specified by {@link Collection#add}) jaroslav@1890: * @throws ClassCastException if the specified element cannot be compared jaroslav@1890: * with elements currently in the priority queue according to the jaroslav@1890: * priority queue's ordering jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean add(E e) { jaroslav@1890: return offer(e); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this priority queue. jaroslav@1890: * As the queue is unbounded, this method will never return {@code false}. jaroslav@1890: * jaroslav@1890: * @param e the element to add jaroslav@1890: * @return {@code true} (as specified by {@link Queue#offer}) jaroslav@1890: * @throws ClassCastException if the specified element cannot be compared jaroslav@1890: * with elements currently in the priority queue according to the jaroslav@1890: * priority queue's ordering jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean offer(E e) { jaroslav@1890: if (e == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: int n, cap; jaroslav@1890: Object[] array; jaroslav@1890: while ((n = size) >= (cap = (array = queue).length)) jaroslav@1890: tryGrow(array, cap); jaroslav@1890: try { jaroslav@1890: Comparator cmp = comparator; jaroslav@1890: if (cmp == null) jaroslav@1890: siftUpComparable(n, e, array); jaroslav@1890: else jaroslav@1890: siftUpUsingComparator(n, e, array, cmp); jaroslav@1890: size = n + 1; jaroslav@1890: notEmpty.signal(); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this priority queue. jaroslav@1890: * As the queue is unbounded, this method will never block. jaroslav@1890: * jaroslav@1890: * @param e the element to add jaroslav@1890: * @throws ClassCastException if the specified element cannot be compared jaroslav@1890: * with elements currently in the priority queue according to the jaroslav@1890: * priority queue's ordering jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public void put(E e) { jaroslav@1890: offer(e); // never need to block jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this priority queue. jaroslav@1890: * As the queue is unbounded, this method will never block or jaroslav@1890: * return {@code false}. jaroslav@1890: * jaroslav@1890: * @param e the element to add jaroslav@1890: * @param timeout This parameter is ignored as the method never blocks jaroslav@1890: * @param unit This parameter is ignored as the method never blocks jaroslav@1890: * @return {@code true} (as specified by jaroslav@1890: * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer}) jaroslav@1890: * @throws ClassCastException if the specified element cannot be compared jaroslav@1890: * with elements currently in the priority queue according to the jaroslav@1890: * priority queue's ordering jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean offer(E e, long timeout, TimeUnit unit) { jaroslav@1890: return offer(e); // never need to block jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E poll() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: E result; jaroslav@1890: try { jaroslav@1890: result = extract(); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return result; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E take() throws InterruptedException { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lockInterruptibly(); jaroslav@1890: E result; jaroslav@1890: try { jaroslav@1890: while ( (result = extract()) == null) jaroslav@1890: notEmpty.await(); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return result; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E poll(long timeout, TimeUnit unit) throws InterruptedException { jaroslav@1890: long nanos = unit.toNanos(timeout); jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lockInterruptibly(); jaroslav@1890: E result; jaroslav@1890: try { jaroslav@1890: while ( (result = extract()) == null && nanos > 0) jaroslav@1890: nanos = notEmpty.awaitNanos(nanos); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return result; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E peek() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: E result; jaroslav@1890: try { jaroslav@1890: result = size > 0 ? (E) queue[0] : null; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return result; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the comparator used to order the elements in this queue, jaroslav@1890: * or {@code null} if this queue uses the {@linkplain Comparable jaroslav@1890: * natural ordering} of its elements. jaroslav@1890: * jaroslav@1890: * @return the comparator used to order the elements in this queue, jaroslav@1890: * or {@code null} if this queue uses the natural jaroslav@1890: * ordering of its elements jaroslav@1890: */ jaroslav@1890: public Comparator comparator() { jaroslav@1890: return comparator; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public int size() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: return size; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns {@code Integer.MAX_VALUE} because jaroslav@1890: * a {@code PriorityBlockingQueue} is not capacity constrained. jaroslav@1890: * @return {@code Integer.MAX_VALUE} always jaroslav@1890: */ jaroslav@1890: public int remainingCapacity() { jaroslav@1890: return Integer.MAX_VALUE; jaroslav@1890: } jaroslav@1890: jaroslav@1890: private int indexOf(Object o) { jaroslav@1890: if (o != null) { jaroslav@1890: Object[] array = queue; jaroslav@1890: int n = size; jaroslav@1890: for (int i = 0; i < n; i++) jaroslav@1890: if (o.equals(array[i])) jaroslav@1890: return i; jaroslav@1890: } jaroslav@1890: return -1; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Removes the ith element from queue. jaroslav@1890: */ jaroslav@1890: private void removeAt(int i) { jaroslav@1890: Object[] array = queue; jaroslav@1890: int n = size - 1; jaroslav@1890: if (n == i) // removed last element jaroslav@1890: array[i] = null; jaroslav@1890: else { jaroslav@1890: E moved = (E) array[n]; jaroslav@1890: array[n] = null; jaroslav@1890: Comparator cmp = comparator; jaroslav@1890: if (cmp == null) jaroslav@1890: siftDownComparable(i, moved, array, n); jaroslav@1890: else jaroslav@1890: siftDownUsingComparator(i, moved, array, n, cmp); jaroslav@1890: if (array[i] == moved) { jaroslav@1890: if (cmp == null) jaroslav@1890: siftUpComparable(i, moved, array); jaroslav@1890: else jaroslav@1890: siftUpUsingComparator(i, moved, array, cmp); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: size = n; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Removes a single instance of the specified element from this queue, jaroslav@1890: * if it is present. More formally, removes an element {@code e} such jaroslav@1890: * that {@code o.equals(e)}, if this queue contains one or more such jaroslav@1890: * elements. Returns {@code true} if and only if this queue contained jaroslav@1890: * the specified element (or equivalently, if this queue changed as a jaroslav@1890: * result of the call). jaroslav@1890: * jaroslav@1890: * @param o element to be removed from this queue, if present jaroslav@1890: * @return {@code true} if this queue changed as a result of the call jaroslav@1890: */ jaroslav@1890: public boolean remove(Object o) { jaroslav@1890: boolean removed = false; jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int i = indexOf(o); jaroslav@1890: if (i != -1) { jaroslav@1890: removeAt(i); jaroslav@1890: removed = true; jaroslav@1890: } jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return removed; jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Identity-based version for use in Itr.remove jaroslav@1890: */ jaroslav@1890: private void removeEQ(Object o) { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: Object[] array = queue; jaroslav@1890: int n = size; jaroslav@1890: for (int i = 0; i < n; i++) { jaroslav@1890: if (o == array[i]) { jaroslav@1890: removeAt(i); jaroslav@1890: break; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this queue contains the specified element. jaroslav@1890: * More formally, returns {@code true} if and only if this queue contains jaroslav@1890: * at least one element {@code e} such that {@code o.equals(e)}. jaroslav@1890: * jaroslav@1890: * @param o object to be checked for containment in this queue jaroslav@1890: * @return {@code true} if this queue contains the specified element jaroslav@1890: */ jaroslav@1890: public boolean contains(Object o) { jaroslav@1890: int index; jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: index = indexOf(o); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: return index != -1; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an array containing all of the elements in this queue. jaroslav@1890: * The returned array elements are in no particular order. jaroslav@1890: * jaroslav@1890: *

The returned array will be "safe" in that no references to it are jaroslav@1890: * maintained by this queue. (In other words, this method must allocate jaroslav@1890: * a new array). The caller is thus free to modify the returned array. jaroslav@1890: * jaroslav@1890: *

This method acts as bridge between array-based and collection-based jaroslav@1890: * APIs. jaroslav@1890: * jaroslav@1890: * @return an array containing all of the elements in this queue jaroslav@1890: */ jaroslav@1890: public Object[] toArray() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: return Arrays.copyOf(queue, size); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: public String toString() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int n = size; jaroslav@1890: if (n == 0) jaroslav@1890: return "[]"; jaroslav@1890: StringBuilder sb = new StringBuilder(); jaroslav@1890: sb.append('['); jaroslav@1890: for (int i = 0; i < n; ++i) { jaroslav@1890: E e = (E)queue[i]; jaroslav@1890: sb.append(e == this ? "(this Collection)" : e); jaroslav@1890: if (i != n - 1) jaroslav@1890: sb.append(',').append(' '); jaroslav@1890: } jaroslav@1890: return sb.append(']').toString(); jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws UnsupportedOperationException {@inheritDoc} jaroslav@1890: * @throws ClassCastException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while ( (e = extract()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws UnsupportedOperationException {@inheritDoc} jaroslav@1890: * @throws ClassCastException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c, int maxElements) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: if (maxElements <= 0) jaroslav@1890: return 0; jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while (n < maxElements && (e = extract()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Atomically removes all of the elements from this queue. jaroslav@1890: * The queue will be empty after this call returns. jaroslav@1890: */ jaroslav@1890: public void clear() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: Object[] array = queue; jaroslav@1890: int n = size; jaroslav@1890: size = 0; jaroslav@1890: for (int i = 0; i < n; i++) jaroslav@1890: array[i] = null; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an array containing all of the elements in this queue; the jaroslav@1890: * runtime type of the returned array is that of the specified array. jaroslav@1890: * The returned array elements are in no particular order. jaroslav@1890: * If the queue fits in the specified array, it is returned therein. jaroslav@1890: * Otherwise, a new array is allocated with the runtime type of the jaroslav@1890: * specified array and the size of this queue. jaroslav@1890: * jaroslav@1890: *

If this queue fits in the specified array with room to spare jaroslav@1890: * (i.e., the array has more elements than this queue), the element in jaroslav@1890: * the array immediately following the end of the queue is set to jaroslav@1890: * {@code null}. jaroslav@1890: * jaroslav@1890: *

Like the {@link #toArray()} method, this method acts as bridge between jaroslav@1890: * array-based and collection-based APIs. Further, this method allows jaroslav@1890: * precise control over the runtime type of the output array, and may, jaroslav@1890: * under certain circumstances, be used to save allocation costs. jaroslav@1890: * jaroslav@1890: *

Suppose {@code x} is a queue known to contain only strings. jaroslav@1890: * The following code can be used to dump the queue into a newly jaroslav@1890: * allocated array of {@code String}: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890:      *     String[] y = x.toArray(new String[0]);
jaroslav@1890: * jaroslav@1890: * Note that {@code toArray(new Object[0])} is identical in function to jaroslav@1890: * {@code toArray()}. jaroslav@1890: * jaroslav@1890: * @param a the array into which the elements of the queue are to jaroslav@1890: * be stored, if it is big enough; otherwise, a new array of the jaroslav@1890: * same runtime type is allocated for this purpose jaroslav@1890: * @return an array containing all of the elements in this queue jaroslav@1890: * @throws ArrayStoreException if the runtime type of the specified array jaroslav@1890: * is not a supertype of the runtime type of every element in jaroslav@1890: * this queue jaroslav@1890: * @throws NullPointerException if the specified array is null jaroslav@1890: */ jaroslav@1890: public T[] toArray(T[] a) { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int n = size; jaroslav@1890: if (a.length < n) jaroslav@1890: // Make a new array of a's runtime type, but my contents: jaroslav@1890: return (T[]) Arrays.copyOf(queue, size, a.getClass()); jaroslav@1890: System.arraycopy(queue, 0, a, 0, n); jaroslav@1890: if (a.length > n) jaroslav@1890: a[n] = null; jaroslav@1890: return a; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an iterator over the elements in this queue. The jaroslav@1890: * iterator does not return the elements in any particular order. jaroslav@1890: * jaroslav@1890: *

The returned iterator is a "weakly consistent" iterator that jaroslav@1890: * will never throw {@link java.util.ConcurrentModificationException jaroslav@1890: * ConcurrentModificationException}, and guarantees to traverse jaroslav@1890: * elements as they existed upon construction of the iterator, and jaroslav@1890: * may (but is not guaranteed to) reflect any modifications jaroslav@1890: * subsequent to construction. jaroslav@1890: * jaroslav@1890: * @return an iterator over the elements in this queue jaroslav@1890: */ jaroslav@1890: public Iterator iterator() { jaroslav@1890: return new Itr(toArray()); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Snapshot iterator that works off copy of underlying q array. jaroslav@1890: */ jaroslav@1890: final class Itr implements Iterator { jaroslav@1890: final Object[] array; // Array of all elements jaroslav@1890: int cursor; // index of next element to return; jaroslav@1890: int lastRet; // index of last element, or -1 if no such jaroslav@1890: jaroslav@1890: Itr(Object[] array) { jaroslav@1890: lastRet = -1; jaroslav@1890: this.array = array; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public boolean hasNext() { jaroslav@1890: return cursor < array.length; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E next() { jaroslav@1890: if (cursor >= array.length) jaroslav@1890: throw new NoSuchElementException(); jaroslav@1890: lastRet = cursor; jaroslav@1890: return (E)array[cursor++]; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public void remove() { jaroslav@1890: if (lastRet < 0) jaroslav@1890: throw new IllegalStateException(); jaroslav@1890: removeEQ(array[lastRet]); jaroslav@1890: lastRet = -1; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Saves the state to a stream (that is, serializes it). For jaroslav@1890: * compatibility with previous version of this class, jaroslav@1890: * elements are first copied to a java.util.PriorityQueue, jaroslav@1890: * which is then serialized. jaroslav@1890: */ jaroslav@1890: private void writeObject(java.io.ObjectOutputStream s) jaroslav@1890: throws java.io.IOException { jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: int n = size; // avoid zero capacity argument jaroslav@1890: q = new PriorityQueue(n == 0 ? 1 : n, comparator); jaroslav@1890: q.addAll(this); jaroslav@1890: s.defaultWriteObject(); jaroslav@1890: } finally { jaroslav@1890: q = null; jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Reconstitutes the {@code PriorityBlockingQueue} instance from a stream jaroslav@1890: * (that is, deserializes it). jaroslav@1890: * jaroslav@1890: * @param s the stream jaroslav@1890: */ jaroslav@1890: private void readObject(java.io.ObjectInputStream s) jaroslav@1890: throws java.io.IOException, ClassNotFoundException { jaroslav@1890: try { jaroslav@1890: s.defaultReadObject(); jaroslav@1890: this.queue = new Object[q.size()]; jaroslav@1890: comparator = q.comparator(); jaroslav@1890: addAll(q); jaroslav@1890: } finally { jaroslav@1890: q = null; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: // Unsafe mechanics jaroslav@1890: private static final sun.misc.Unsafe UNSAFE; jaroslav@1890: private static final long allocationSpinLockOffset; jaroslav@1890: static { jaroslav@1890: try { jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe(); jaroslav@1890: Class k = PriorityBlockingQueue.class; jaroslav@1890: allocationSpinLockOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("allocationSpinLock")); jaroslav@1890: } catch (Exception e) { jaroslav@1890: throw new Error(e); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: }