PriorityQueue and supplies
blocking retrieval operations. While this queue is logically
unbounded, attempted additions may fail due to resource exhaustion
(causing OutOfMemoryError). This class does not permit
null elements. A priority queue relying on natural ordering also does not permit insertion of
non-comparable objects (doing so results in
ClassCastException).
This class and its iterator implement all of the optional
methods of the Collection and Iterator interfaces.
The Iterator provided in method iterator() and the
Spliterator provided in method spliterator() are not
guaranteed to traverse the elements of the PriorityBlockingQueue in
any particular order. If you need ordered traversal, consider using
Arrays.sort(pq.toArray()). Also, method drainTo can
be used to remove some or all elements in priority order and
place them in another collection.
Operations on this class make no guarantees about the ordering
of elements with equal priority. If you need to enforce an
ordering, you can define custom classes or comparators that use a
secondary key to break ties in primary priority values. For
example, here is a class that applies first-in-first-out
tie-breaking to comparable elements. To use it, you would insert a
new FIFOEntry(anEntry) instead of a plain entry object.
class FIFOEntry<E extends Comparable<? super E>>
implements Comparable<FIFOEntry<E>> {
static final AtomicLong seq = new AtomicLong();
final long seqNum;
final E entry;
public FIFOEntry(E entry) {
seqNum = seq.getAndIncrement();
this.entry = entry;
}
public E getEntry() { return entry; }
public int compareTo(FIFOEntry<E> other) {
int res = entry.compareTo(other.entry);
if (res == 0 && other.entry != this.entry)
res = (seqNum < other.seqNum ? -1 : 1);
return res;
}
}
This class is a member of the Java Collections Framework.
| Modifier and Type | Class and Description |
|---|---|
| pack-priv class | PriorityBlockingQueue.
Snapshot iterator that works off copy of underlying q array. |
| pack-priv class | PriorityBlockingQueue.
Immutable snapshot spliterator that binds to elements "late". |
| Modifier and Type | Field and Description |
|---|---|
| private transient volatile int | allocationSpinLock
Spinlock for allocation, acquired via CAS. |
| private static final VarHandle | |
| private transient Comparator | comparator
The comparator, or null if priority queue uses elements' natural ordering. |
| private static final int | DEFAULT_INITIAL_CAPACITY
Default array capacity. |
| private final ReentrantLock | |
| private final Condition | |
| private PriorityQueue | |
| private transient Object[] | queue
Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. |
| private static final long | |
| private transient int | size
The number of elements in the priority queue. |
| Access | Constructor and Description |
|---|---|
| public | PriorityBlockingQueue()
Creates a |
| public | PriorityBlockingQueue(int
the initial capacity for this priority queue initialCapacity)Creates a |
| public | PriorityBlockingQueue(int
the initial capacity for this priority queue initialCapacity, Comparator<? super E> the comparator that will be used to order this
priority queue. If comparator)null, the natural ordering of the elements will be used.Creates a |
| public | PriorityBlockingQueue(Collection<? extends E>
the collection whose elements are to be placed
into this priority queue c)Creates a |
| Modifier and Type | Method and Description |
|---|---|
| public boolean | add(E
the element to add e)Overrides java. Implements java. Inserts the specified element into this priority queue. |
| private boolean | |
| public void | clear()
Overrides java. Implements java. Atomically removes all of the elements from this queue. |
| public Comparator | Returns: the comparator used to order the elements in this queue, ornull if this queue uses the natural
ordering of its elementsReturns the comparator used to order the elements in this queue,
or |
| public boolean | Returns: true if this queue contains the specified elementobject to be checked for containment in this queue o)Overrides java. Implements java. Returns |
| private E | |
| public int | drainTo(Collection<? super E> c)
Implements java. Removes all available elements from this queue and adds them to the given collection. |
| public int | drainTo(Collection<? super E> c, int maxElements)
Implements java. Removes at most the given number of available elements from this queue and adds them to the given collection. |
| private static Object[] | |
| public void | forEach(Consumer<? super E> action)
Overrides default java. Performs the given action for each element of the |
| private void | heapify()
Establishes the heap invariant (described above) in the entire tree, assuming nothing about the order of the elements prior to the call. |
| private int | |
| private static boolean | |
| public Iterator | Returns: an iterator over the elements in this queueImplements abstract java. Implements java. Returns an iterator over the elements in this queue. |
| private static long[] | |
| public boolean | offer(E
the element to add e)Implements java. Inserts the specified element into this priority queue. |
| public boolean | offer(E
the element to add e, long This parameter is ignored as the method never blocks timeout, TimeUnit This parameter is ignored as the method never blocks unit)Implements java. Inserts the specified element into this priority queue. |
| public E | peek()
Implements java. Retrieves, but does not remove, the head of this queue,
or returns |
| public E | poll()
Implements java. Retrieves and removes the head of this queue,
or returns |
| public E | poll(long timeout, TimeUnit unit)
Implements java. Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available. |
| public void | put(E
the element to add e)Implements java. Inserts the specified element into this priority queue. |
| private void | readObject(ObjectInputStream
the stream s)Reconstitutes this queue from a stream (that is, deserializes it). |
| public int | Returns: Integer.MAX_VALUE alwaysImplements java. Always returns |
| public boolean | Returns: true if this queue changed as a result of the callelement to be removed from this queue, if present o)Overrides java. Implements java. Removes a single instance of the specified element from this queue, if it is present. |
| public boolean | removeAll(Collection<?> c)
Overrides java. Implements java. Removes all of this collection's elements that are also contained in the specified collection (optional operation). |
| private void | |
| pack-priv void | |
| public boolean | removeIf(Predicate<? super E> filter)
Overrides default java. Removes all of the elements of this collection that satisfy the given predicate (optional operation). |
| public boolean | retainAll(Collection<?> c)
Overrides java. Implements java. Retains only the elements in this collection that are contained in the specified collection (optional operation). |
| private static void | |
| private static <T> void | siftDownComparable(int
the position to fill k, T the item to insert x, Object[] the heap array es, int heap size n)Inserts item x at position k, maintaining heap invariant by demoting x down the tree repeatedly until it is less than or equal to its children or is a leaf. |
| private static <T> void | |
| private static <T> void | siftUpComparable(int
the position to fill k, T the item to insert x, Object[] the heap array es)Inserts item x at position k, maintaining heap invariant by promoting x up the tree until it is greater than or equal to its parent, or is the root. |
| private static <T> void | |
| public int | size()
Implements abstract java. Implements java. Returns the number of elements in this collection. |
| public Spliterator | Returns: aSpliterator over the elements in this queueOverrides default java. Returns a |
| public E | take()
Implements java. Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. |
| public Object[] | Returns: an array containing all of the elements in this queueOverrides java. Implements java. Returns an array containing all of the elements in this queue. |
| public <T> T[] | Returns: an array containing all of the elements in this queuethe array into which the elements of the queue are to
be stored, if it is big enough; otherwise, a new array of the
same runtime type is allocated for this purpose a)Overrides java. Implements java. Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. |
| public String | toString()
Overrides java. Returns a string representation of this collection. |
| private void | |
| private void |
| allocationSpinLock | back to summary |
|---|---|
| private transient volatile int allocationSpinLock Spinlock for allocation, acquired via CAS. | |
| ALLOCATIONSPINLOCK | back to summary |
|---|---|
| private static final VarHandle ALLOCATIONSPINLOCK | |
| comparator | back to summary |
|---|---|
| private transient Comparator<? super E> comparator The comparator, or null if priority queue uses elements' natural ordering. | |
| DEFAULT_INITIAL_CAPACITY | back to summary |
|---|---|
| private static final int DEFAULT_INITIAL_CAPACITY Default array capacity. | |
| lock | back to summary |
|---|---|
| private final ReentrantLock lock | |
| notEmpty | back to summary |
|---|---|
private final Condition notEmpty
| |
| q | back to summary |
|---|---|
| private PriorityQueue<E> q | |
| queue | back to summary |
|---|---|
| private transient Object[] queue Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The priority queue is ordered by comparator, or by the elements' natural ordering, if comparator is null: For each node n in the heap and each descendant d of n, n <= d. The element with the lowest value is in queue[0], assuming the queue is nonempty. | |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID | |
| size | back to summary |
|---|---|
| private transient int size The number of elements in the priority queue. | |
| PriorityBlockingQueue | back to summary |
|---|---|
| public PriorityBlockingQueue() Creates a | |
| PriorityBlockingQueue | back to summary |
|---|---|
| public PriorityBlockingQueue(int initialCapacity) Creates a
| |
| PriorityBlockingQueue | back to summary |
|---|---|
| public PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) Creates a
| |
| PriorityBlockingQueue | back to summary |
|---|---|
| public PriorityBlockingQueue(Collection<? extends E> c) Creates a
| |
| add | back to summary |
|---|---|
| public boolean add(E e) Overrides java. Implements java. Inserts the specified element into this priority queue.
| |
| bulkRemove | back to summary |
|---|---|
| private boolean bulkRemove(Predicate<? super E> filter) Implementation of bulk remove methods. | |
| clear | back to summary |
|---|---|
| public void clear() Overrides java. Implements java. Atomically removes all of the elements from this queue. The queue will be empty after this call returns. | |
| comparator | back to summary |
|---|---|
| public Comparator Returns the comparator used to order the elements in this queue,
or
| |
| contains | back to summary |
|---|---|
| public boolean contains(Object o) Overrides java. Implements java. Returns
| |
| dequeue | back to summary |
|---|---|
| private E dequeue() Mechanics for poll(). Call only while holding lock. | |
| drainTo | back to summary |
|---|---|
| public int drainTo(Collection<? super E> c) Implements java. Doc from java. Removes all available elements from this queue and adds them
to the given collection. This operation may be more
efficient than repeatedly polling this queue. A failure
encountered while attempting to add elements to
collection
| |
| drainTo | back to summary |
|---|---|
| public int drainTo(Collection<? super E> c, int maxElements) Implements java. Doc from java. Removes at most the given number of available elements from
this queue and adds them to the given collection. A failure
encountered while attempting to add elements to
collection
| |
| ensureNonEmpty | back to summary |
|---|---|
| private static Object[] ensureNonEmpty(Object[] es) Ensures that queue[0] exists, helping peek() and poll(). | |
| forEach | back to summary |
|---|---|
| public void forEach(Consumer<? super E> action) Overrides default java. Doc from java. Performs the given action for each element of the The behavior of this method is unspecified if the action performs side-effects that modify the underlying source of elements, unless an overriding class has specified a concurrent modification policy.
| |
| heapify | back to summary |
|---|---|
| private void heapify() Establishes the heap invariant (described above) in the entire tree, assuming nothing about the order of the elements prior to the call. This classic algorithm due to Floyd (1964) is known to be O(size). | |
| indexOf | back to summary |
|---|---|
| private int indexOf(Object o) | |
| isClear | back to summary |
|---|---|
| private static boolean isClear(long[] bits, int i) | |
| iterator | back to summary |
|---|---|
| public Iterator Implements abstract java. Implements java. Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order. The returned iterator is weakly consistent.
| |
| nBits | back to summary |
|---|---|
| private static long[] nBits(int n) | |
| offer | back to summary |
|---|---|
| public boolean offer(E e) Implements java. Inserts the specified element into this priority queue.
As the queue is unbounded, this method will never return
| |
| offer | back to summary |
|---|---|
| public boolean offer(E e, long timeout, TimeUnit unit) Implements java. Inserts the specified element into this priority queue.
As the queue is unbounded, this method will never block or
return
| |
| peek | back to summary |
|---|---|
| public E peek() Implements java. Doc from java. Retrieves, but does not remove, the head of this queue,
or returns | |
| poll | back to summary |
|---|---|
| public E poll() Implements java. Doc from java. Retrieves and removes the head of this queue,
or returns | |
| poll | back to summary |
|---|---|
| public E poll(long timeout, TimeUnit unit) throws InterruptedException Implements java. Doc from java. Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
| |
| put | back to summary |
|---|---|
| public void put(E e) Implements java. Inserts the specified element into this priority queue. As the queue is unbounded, this method will never block.
| |
| readObject | back to summary |
|---|---|
| private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException Reconstitutes this queue from a stream (that is, deserializes it).
| |
| remainingCapacity | back to summary |
|---|---|
| public int remainingCapacity() Implements java. Always returns
| |
| remove | back to summary |
|---|---|
| public boolean remove(Object o) Overrides java. Implements java. Removes a single instance of the specified element from this queue,
if it is present. More formally, removes an element
| |
| removeAll | back to summary |
|---|---|
| public boolean removeAll(Collection<?> c) Overrides java. Implements java. Doc from java. Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.
| |
| removeAt | back to summary |
|---|---|
| private void removeAt(int i) Removes the ith element from queue. | |
| removeEq | back to summary |
|---|---|
| pack-priv void removeEq(Object o) Identity-based version for use in Itr.remove.
| |
| removeIf | back to summary |
|---|---|
| public boolean removeIf(Predicate<? super E> filter) Overrides default java. Doc from java. Removes all of the elements of this collection that satisfy the given predicate (optional operation). Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.
| |
| retainAll | back to summary |
|---|---|
| public boolean retainAll(Collection<?> c) Overrides java. Implements java. Doc from java. Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.
| |
| setBit | back to summary |
|---|---|
| private static void setBit(long[] bits, int i) | |
| siftDownComparable | back to summary |
|---|---|
| private static <T> void siftDownComparable(int k, T x, Object[] es, int n) Inserts item x at position k, maintaining heap invariant by demoting x down the tree repeatedly until it is less than or equal to its children or is a leaf.
| |
| siftDownUsingComparator | back to summary |
|---|---|
| private static <T> void siftDownUsingComparator(int k, T x, Object[] es, int n, Comparator<? super T> cmp) | |
| siftUpComparable | back to summary |
|---|---|
| private static <T> void siftUpComparable(int k, T x, Object[] es) Inserts item x at position k, maintaining heap invariant by promoting x up the tree until it is greater than or equal to its parent, or is the root. To simplify and speed up coercions and comparisons, the Comparable and Comparator versions are separated into different methods that are otherwise identical. (Similarly for siftDown.)
| |
| siftUpUsingComparator | back to summary |
|---|---|
| private static <T> void siftUpUsingComparator(int k, T x, Object[] es, Comparator<? super T> cmp) | |
| size | back to summary |
|---|---|
| public int size() Implements abstract java. Implements java. Doc from java. Returns the number of elements in this collection. If this collection
contains more than | |
| spliterator | back to summary |
|---|---|
| public Spliterator Overrides default java. Returns a The returned spliterator is weakly consistent. The Implementation Note The
| |
| take | back to summary |
|---|---|
| public E take() throws InterruptedException Implements java. Doc from java. Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
| |
| toArray | back to summary |
|---|---|
| public Object[] toArray() Overrides java. Implements java. Returns an array containing all of the elements in this queue. The returned array elements are in no particular order. The returned array will be "safe" in that no references to it are maintained by this queue. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. This method acts as bridge between array-based and collection-based APIs.
| |
| toArray | back to summary |
|---|---|
| public <T> T[] toArray(T[] a) Overrides java. Implements java. Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. The returned array elements are in no particular order. If the queue fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this queue. If this queue fits in the specified array with room to spare
(i.e., the array has more elements than this queue), the element in
the array immediately following the end of the queue is set to
Like the Suppose
Note that toArray(new Object[0]) is identical in function to
toArray().
| |
| toString | back to summary |
|---|---|
| public String toString() Overrides java. Doc from java. Returns a string representation of this collection. The string
representation consists of a list of the collection's elements in the
order they are returned by its iterator, enclosed in square brackets
( | |
| tryGrow | back to summary |
|---|---|
| private void tryGrow(Object[] array, int oldCap) Tries to grow array to accommodate at least one more element (but normally expand by about 50%), giving up (allowing retry) on contention (which we expect to be rare). Call only while holding lock.
| |
| writeObject | back to summary |
|---|---|
| private void writeObject(ObjectOutputStream s) throws IOException Saves this queue to a stream (that is, serializes it). For compatibility with previous version of this class, elements are first copied to a java.util.PriorityQueue, which is then serialized.
| |
| Modifier and Type | Field and Description |
|---|---|
| pack-priv final Object[] | |
| pack-priv int | |
| pack-priv int |
| Modifier and Type | Method and Description |
|---|---|
| public void | forEachRemaining(Consumer<? super E> action)
Overrides default java. Performs the given action for each remaining element until all elements have been processed or the action throws an exception. |
| public boolean | |
| public E | |
| public void | remove()
Overrides default java. Removes from the underlying collection the last element returned by this iterator (optional operation). |
| array | back to summary |
|---|---|
| pack-priv final Object[] array | |
| cursor | back to summary |
|---|---|
| pack-priv int cursor | |
| lastRet | back to summary |
|---|---|
| pack-priv int lastRet | |
| Itr | back to summary |
|---|---|
| pack-priv Itr(Object[] array) | |
| forEachRemaining | back to summary |
|---|---|
| public void forEachRemaining(Consumer<? super E> action) Overrides default java. Doc from java. Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.
The behavior of an iterator is unspecified if the action modifies the
collection in any way (even by calling the Subsequent behavior of an iterator is unspecified if the action throws an exception. | |
| hasNext | back to summary |
|---|---|
| public boolean hasNext() Implements java. Doc from java. Returns | |
| next | back to summary |
|---|---|
| public E next() Implements java. Doc from java. Returns the next element in the iteration. | |
| remove | back to summary |
|---|---|
| public void remove() Overrides default java. Doc from java. Removes from the underlying collection the last element returned
by this iterator (optional operation). This method can be called
only once per call to The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.
The behavior of an iterator is unspecified if this method is called
after a call to the | |
| Modifier and Type | Field and Description |
|---|---|
| pack-priv Object[] | |
| pack-priv int | |
| pack-priv int |
| Access | Constructor and Description |
|---|---|
| pack-priv | |
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public int | characteristics()
Implements java. Returns a set of characteristics of this Spliterator and its elements. |
| public long | estimateSize()
Implements java. Returns an estimate of the number of elements that would be
encountered by a |
| public void | forEachRemaining(Consumer<? super E> action)
Overrides default java. Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. |
| private int | |
| public boolean | tryAdvance(Consumer<? super E> action)
Implements java. If a remaining element exists: performs the given action on it,
returning |
| public PriorityBlockingQueue | trySplit()
Implements java. If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator. |
| array | back to summary |
|---|---|
| pack-priv Object[] array | |
| fence | back to summary |
|---|---|
| pack-priv int fence | |
| index | back to summary |
|---|---|
| pack-priv int index | |
| PBQSpliterator | back to summary |
|---|---|
| pack-priv PBQSpliterator() | |
| PBQSpliterator | back to summary |
|---|---|
| pack-priv PBQSpliterator(Object[] array, int index, int fence) | |
| characteristics | back to summary |
|---|---|
| public int characteristics() Implements java. Doc from java. Returns a set of characteristics of this Spliterator and its
elements. The result is represented as ORed values from If a Spliterator reports an inconsistent set of characteristics (either those returned from a single invocation or across multiple invocations), no guarantees can be made about any computation using this Spliterator. | |
| estimateSize | back to summary |
|---|---|
| public long estimateSize() Implements java. Doc from java. Returns an estimate of the number of elements that would be
encountered by a If this Spliterator is | |
| forEachRemaining | back to summary |
|---|---|
| public void forEachRemaining(Consumer<? super E> action) Overrides default java. Doc from java. Performs the given action for each remaining element, sequentially in
the current thread, until all elements have been processed or the action
throws an exception. If this Spliterator is Subsequent behavior of a spliterator is unspecified if the action throws an exception. | |
| getFence | back to summary |
|---|---|
| private int getFence() | |
| tryAdvance | back to summary |
|---|---|
| public boolean tryAdvance(Consumer<? super E> action) Implements java. Doc from java. If a remaining element exists: performs the given action on it,
returning Subsequent behavior of a spliterator is unspecified if the action throws an exception. | |
| trySplit | back to summary |
|---|---|
| public PriorityBlockingQueue Implements java. Doc from java. If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator. If this Spliterator is Unless this Spliterator covers an infinite number of elements,
repeated calls to
This method may return | |