Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class PriorityBlockingQueue<E>

extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.util.concurrent.BlockingQueue, java.util.Queue, java.util.Collection, java.lang.Iterable
Annotations
@SuppressWarnings:unchecked
Type Parameters
<E>
the type of elements held in this queue
Imports
java.lang.invoke.MethodHandles, .VarHandle, java.util.AbstractQueue, .Arrays, .Collection, .Comparator, .Iterator, .NoSuchElementException, .Objects, .PriorityQueue, .Queue, .SortedSet, .Spliterator, java.util.concurrent.locks.Condition, .ReentrantLock, java.util.function.Consumer, .Predicate, jdk.internal.access.SharedSecrets, jdk.internal.util.ArraysSupport

An unbounded blocking queue that uses the same ordering rules as class 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.

Author
Doug Lea
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv class
PriorityBlockingQueue.Itr

Snapshot iterator that works off copy of underlying q array.

pack-priv class
PriorityBlockingQueue.PBQSpliterator

Immutable snapshot spliterator that binds to elements "late".

Field Summary

Modifier and TypeField and Description
private transient volatile int
allocationSpinLock

Spinlock for allocation, acquired via CAS.

private static final VarHandle
private transient Comparator<? super E>
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
lock

Lock used for all public operations.

private final Condition
notEmpty

Condition for blocking when empty.

private PriorityQueue<E>
q

A plain PriorityQueue used only for serialization, to maintain compatibility with previous versions of this class.

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.

Constructor Summary

AccessConstructor and Description
public
PriorityBlockingQueue()

Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

public
PriorityBlockingQueue(int
the initial capacity for this priority queue
initialCapacity
)

Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.

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 null, the natural ordering of the elements will be used.
comparator
)

Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.

public
PriorityBlockingQueue(Collection<? extends E>
the collection whose elements are to be placed into this priority queue
c
)

Creates a PriorityBlockingQueue containing the elements in the specified collection.

Method Summary

Modifier and TypeMethod and Description
public boolean

Returns:

true (as specified by Collection#add)
add
(E
the element to add
e
)

Overrides java.util.AbstractQueue.add.

Implements java.util.concurrent.BlockingQueue.add, java.util.Queue.add, java.util.Collection.add.

Inserts the specified element into this priority queue.

private boolean
bulkRemove(Predicate<? super E> filter)

Implementation of bulk remove methods.

public void
clear()

Overrides java.util.AbstractQueue.clear.

Implements java.util.Collection.clear.

Atomically removes all of the elements from this queue.

public Comparator<? super E>

Returns:

the comparator used to order the elements in this queue, or null if this queue uses the natural ordering of its elements
comparator
()

Returns the comparator used to order the elements in this queue, or null if this queue uses the natural ordering of its elements.

public boolean

Returns:

true if this queue contains the specified element
contains
(Object
object to be checked for containment in this queue
o
)

Overrides java.util.AbstractCollection.contains.

Implements java.util.concurrent.BlockingQueue.contains, java.util.Collection.contains.

Returns true if this queue contains the specified element.

private E
dequeue()

Mechanics for poll().

public int
drainTo(Collection<? super E>
the collection to transfer elements into
c
)

Implements java.util.concurrent.BlockingQueue.drainTo.

Removes all available elements from this queue and adds them to the given collection.

public int
drainTo(Collection<? super E>
the collection to transfer elements into
c
,
int
the maximum number of elements to transfer
maxElements
)

Implements java.util.concurrent.BlockingQueue.drainTo.

Removes at most the given number of available elements from this queue and adds them to the given collection.

private static Object[]
ensureNonEmpty(Object[] es)

Ensures that queue[0] exists, helping peek() and poll().

public void
forEach(Consumer<? super E>
The action to be performed for each element
action
)

Overrides default java.lang.Iterable.forEach.

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

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
isClear(long[] bits, int i)

public Iterator<E>

Returns:

an iterator over the elements in this queue
iterator
()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Collection.iterator.

Returns an iterator over the elements in this queue.

private static long[]
nBits(int n)

public boolean

Returns:

true (as specified by Queue#offer)
offer
(E
the element to add
e
)

Implements java.util.concurrent.BlockingQueue.offer, java.util.Queue.offer.

Inserts the specified element into this priority queue.

public boolean

Returns:

true (as specified by BlockingQueue.offer)
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.util.concurrent.BlockingQueue.offer.

Inserts the specified element into this priority queue.

public E
peek()

Implements java.util.Queue.peek.

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

public E
poll()

Implements java.util.Queue.poll.

Retrieves and removes the head of this queue, or returns null if this queue is empty.

public E
poll(long
how long to wait before giving up, in units of unit
timeout
,
TimeUnit
a TimeUnit determining how to interpret the timeout parameter
unit
)

Implements java.util.concurrent.BlockingQueue.poll.

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.util.concurrent.BlockingQueue.put.

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 always
remainingCapacity
()

Implements java.util.concurrent.BlockingQueue.remainingCapacity.

Always returns Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.

public boolean

Returns:

true if this queue changed as a result of the call
remove
(Object
element to be removed from this queue, if present
o
)

Overrides java.util.AbstractCollection.remove.

Implements java.util.concurrent.BlockingQueue.remove, java.util.Collection.remove.

Removes a single instance of the specified element from this queue, if it is present.

public boolean
removeAll(Collection<?>
collection containing elements to be removed from this collection
c
)

Overrides java.util.AbstractCollection.removeAll.

Implements java.util.Collection.removeAll.

Removes all of this collection's elements that are also contained in the specified collection (optional operation).

private void
removeAt(int i)

Removes the ith element from queue.

pack-priv void
removeEq(Object
element to be removed from this queue, if present
o
)

Identity-based version for use in Itr.remove.

public boolean
removeIf(Predicate<? super E>
a predicate which returns true for elements to be removed
filter
)

Overrides default java.util.Collection.removeIf.

Removes all of the elements of this collection that satisfy the given predicate (optional operation).

public boolean
retainAll(Collection<?>
collection containing elements to be retained in this collection
c
)

Overrides java.util.AbstractCollection.retainAll.

Implements java.util.Collection.retainAll.

Retains only the elements in this collection that are contained in the specified collection (optional operation).

private static void
setBit(long[] bits, int i)

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
siftDownUsingComparator(int k, T x, Object[] es, int n, Comparator<? super T> cmp)

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
siftUpUsingComparator(int k, T x, Object[] es, Comparator<? super T> cmp)

public int
size()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Collection.size.

Returns the number of elements in this collection.

public Spliterator<E>

Returns:

a Spliterator over the elements in this queue
spliterator
()

Overrides default java.util.Collection.spliterator.

Returns a Spliterator over the elements in this queue.

public E
take()

Implements java.util.concurrent.BlockingQueue.take.

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 queue
toArray
()

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Returns an array containing all of the elements in this queue.

public <T> T[]

Returns:

an array containing all of the elements in this queue
toArray
(T[]
the 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.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

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.util.AbstractCollection.toString.

Returns a string representation of this collection.

private void
tryGrow(Object[]
the heap array
array
,
int
the length of the array
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).

private void
writeObject(ObjectOutputStream
the stream
s
)

Saves this queue to a stream (that is, serializes it).

Inherited from java.util.AbstractQueue:
addAllelementremove