APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class ArrayBlockingQueue<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
Type Parameters
<E>
the type of elements held in this queue
Imports
java.io.IOException, java.lang.ref.WeakReference, java.util.AbstractQueue, .Arrays, .Collection, .Iterator, .NoSuchElementException, .Objects, .Spliterator, .Spliterators, java.util.concurrent.locks.Condition, .ReentrantLock, java.util.function.Consumer, .Predicate

A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

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
private class
ArrayBlockingQueue.Itr

Iterator for ArrayBlockingQueue.

pack-priv class
ArrayBlockingQueue.Itrs

Shared data between iterators and their queue, allowing queue modifications to update iterators when elements are removed.

Field Summary

Modifier and TypeField and Description
pack-priv int
pack-priv final Object[]
pack-priv transient ArrayBlockingQueue<E>.Itrs
itrs

Shared state for currently active iterators, or null if there are known not to be any.

pack-priv final ReentrantLock
private final Condition
private final Condition
pack-priv int
private static final long
serialVersionUID

Serialization ID. This class relies on default serialization even for the items array, which is default-serialized, even if it is empty.

pack-priv int

Constructor Summary

AccessConstructor and Description
public
ArrayBlockingQueue(int
the capacity of this queue
capacity
)

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.

public
ArrayBlockingQueue(int
the capacity of this queue
capacity
,
boolean
if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified.
fair
)

Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.

public
ArrayBlockingQueue(int
the capacity of this queue
capacity
,
boolean
if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified.
fair
,
Collection<? extends E>
the collection of elements to initially contain
c
)

Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection's iterator.

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 at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and throwing an IllegalStateException if this queue is full.

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

Implementation of bulk remove methods.

private boolean
bulkRemoveModified(Predicate<? super E> filter, final int
valid index of first element to be deleted
beg
)

Helper for bulkRemove, in case of at least one deletion.

pack-priv void
checkInvariants()

debugging

private static void
circularClear(Object[] items, int i, int end)

Nulls out slots starting at array index i, up to index end.

public void
clear()

Overrides java.util.AbstractQueue.clear.

Implements java.util.Collection.clear.

Atomically removes all of the elements from this queue.

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.

pack-priv static final int
dec(int i, int modulus)

Decrements i, mod modulus.

private E
dequeue()

Extracts element at current take position, advances, and signals.

private int
distanceNonEmpty(int i, int j)

Returns circular distance from i to j, disambiguating i == j to items.length; never returns 0.

public int
drainTo(Collection<? super E> 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> c, int 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 void
enqueue(E e)

Inserts element at current put position, advances, and signals.

public void
forEach(Consumer<? super E> 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.

pack-priv static final int
inc(int i, int modulus)

Increments i, mod modulus.

private boolean
private static boolean
isClear(long[] bits, int i)

pack-priv final E
itemAt(int i)

Returns item at index i.

pack-priv static <E> E
itemAt(Object[] items, int i)

Returns element at array index i.

public Iterator<E>

Returns:

an iterator over the elements in this queue in proper sequence
iterator
()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Collection.iterator.

Returns an iterator over the elements in this queue in proper sequence.

private static long[]
nBits(int n)

public boolean
offer(E e)

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

Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.

public boolean
offer(E e, long timeout, TimeUnit unit)

Implements java.util.concurrent.BlockingQueue.offer.

Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.

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 timeout, TimeUnit 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 e)

Implements java.util.concurrent.BlockingQueue.put.

Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.

private void
readObject(ObjectInputStream
the stream
s
)

Reconstitutes this queue from a stream (that is, deserializes it).

public int
remainingCapacity()

Implements java.util.concurrent.BlockingQueue.remainingCapacity.

Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.

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<?> 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).

pack-priv void
removeAt(final int removeIndex)

Deletes item at array index removeIndex.

public boolean
removeIf(Predicate<? super E> 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<?> 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)

public int

Returns:

the number of elements in this queue
size
()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Collection.size.

Returns the number of elements in this queue.

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, in proper sequence.

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, in proper sequence; 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
writeObject(ObjectOutputStream
the stream
s
)

Writes the queue to the stream whilst holding the locks to prevent broken invariants.

Inherited from java.util.AbstractQueue:
addAllelementremove

Field Detail

countback to summary
pack-priv int count
itemsback to summary
pack-priv final Object[] items
Annotations
@SuppressWarnings:serial
itrsback to summary
pack-priv transient ArrayBlockingQueue<E>.Itrs itrs

Shared state for currently active iterators, or null if there are known not to be any. Allows queue operations to update iterator state.

lockback to summary
pack-priv final ReentrantLock lock
notEmptyback to summary
private final Condition notEmpty
Annotations
@SuppressWarnings:serial
notFullback to summary
private final Condition notFull
Annotations
@SuppressWarnings:serial
putIndexback to summary
pack-priv int putIndex
serialVersionUIDback to summary
private static final long serialVersionUID

Serialization ID. This class relies on default serialization even for the items array, which is default-serialized, even if it is empty. Otherwise it could not be declared final, which is necessary here.

takeIndexback to summary
pack-priv int takeIndex

Constructor Detail

ArrayBlockingQueueback to summary
public ArrayBlockingQueue(int capacity)

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.

Parameters
capacity:int

the capacity of this queue

Exceptions
IllegalArgumentException:
if capacity < 1
ArrayBlockingQueueback to summary
public ArrayBlockingQueue(int capacity, boolean fair)

Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.

Parameters
capacity:int

the capacity of this queue

fair:boolean

if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified.

Exceptions
IllegalArgumentException:
if capacity < 1
ArrayBlockingQueueback to summary
public ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)

Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Parameters
capacity:int

the capacity of this queue

fair:boolean

if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified.

c:Collection<? extends E>

the collection of elements to initially contain

Exceptions
IllegalArgumentException:
if capacity is less than c.size(), or less than 1.
NullPointerException:
if the specified collection or any of its elements are null

Method Detail

addback to summary
public boolean add(E e)

Overrides java.util.AbstractQueue.add.

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

Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and throwing an IllegalStateException if this queue is full.

Parameters
e:E

the element to add

Returns:boolean

true (as specified by Collection#add)

Exceptions
IllegalStateException:
if this queue is full
NullPointerException:
if the specified element is null
bulkRemoveback to summary
private boolean bulkRemove(Predicate<? super E> filter)

Implementation of bulk remove methods.

bulkRemoveModifiedback to summary
private boolean bulkRemoveModified(Predicate<? super E> filter, final int beg)

Helper for bulkRemove, in case of at least one deletion. Tolerate predicates that reentrantly access the collection for read (but not write), so traverse once to find elements to delete, a second pass to physically expunge.

Parameters
beg:int

valid index of first element to be deleted

checkInvariantsback to summary
pack-priv void checkInvariants()

debugging

circularClearback to summary
private static void circularClear(Object[] items, int i, int end)

Nulls out slots starting at array index i, up to index end. Condition i == end means "full" - the entire array is cleared.

clearback to summary
public void clear()

Overrides java.util.AbstractQueue.clear.

Implements java.util.Collection.clear.

Atomically removes all of the elements from this queue. The queue will be empty after this call returns.

containsback to summary
public boolean contains(Object 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. More formally, returns true if and only if this queue contains at least one element e such that o.equals(e).

Parameters
o:Object

object to be checked for containment in this queue

Returns:boolean

true if this queue contains the specified element

decback to summary
pack-priv static final int dec(int i, int modulus)

Decrements i, mod modulus. Precondition and postcondition: 0 <= i < modulus.

dequeueback to summary
private E dequeue()

Extracts element at current take position, advances, and signals. Call only when holding lock.

distanceNonEmptyback to summary
private int distanceNonEmpty(int i, int j)

Returns circular distance from i to j, disambiguating i == j to items.length; never returns 0.

drainToback to summary
public int drainTo(Collection<? super E> c)

Implements java.util.concurrent.BlockingQueue.drainTo.

Doc from java.util.concurrent.BlockingQueue.drainTo.

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 c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Exceptions
UnsupportedOperationException:
if addition of elements is not supported by the specified collection
ClassCastException:
if the class of an element of this queue prevents it from being added to the specified collection
NullPointerException:
if the specified collection is null
IllegalArgumentException:
if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection
drainToback to summary
public int drainTo(Collection<? super E> c, int maxElements)

Implements java.util.concurrent.BlockingQueue.drainTo.

Doc from java.util.concurrent.BlockingQueue.drainTo.

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 c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Exceptions
UnsupportedOperationException:
if addition of elements is not supported by the specified collection
ClassCastException:
if the class of an element of this queue prevents it from being added to the specified collection
NullPointerException:
if the specified collection is null
IllegalArgumentException:
if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection
enqueueback to summary
private void enqueue(E e)

Inserts element at current put position, advances, and signals. Call only when holding lock.

forEachback to summary
public void forEach(Consumer<? super E> action)

Overrides default java.lang.Iterable.forEach.

Doc from 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. 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 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.

Exceptions
NullPointerException:
if the specified action is null
incback to summary
pack-priv static final int inc(int i, int modulus)

Increments i, mod modulus. Precondition and postcondition: 0 <= i < modulus.

invariantsSatisfiedback to summary
private boolean invariantsSatisfied()
isClearback to summary
private static boolean isClear(long[] bits, int i)
itemAtback to summary
pack-priv final E itemAt(int i)

Returns item at index i.

Annotations
@SuppressWarnings:unchecked
itemAtback to summary
pack-priv static <E> E itemAt(Object[] items, int i)

Returns element at array index i. This is a slight abuse of generics, accepted by javac.

Annotations
@SuppressWarnings:unchecked
iteratorback to summary
public Iterator<E> iterator()

Implements abstract java.util.AbstractCollection.iterator.

Implements java.util.Collection.iterator.

Returns an iterator over the elements in this queue in proper sequence. The elements will be returned in order from first (head) to last (tail).

The returned iterator is weakly consistent.

Returns:Iterator<E>

an iterator over the elements in this queue in proper sequence

nBitsback to summary
private static long[] nBits(int n)
offerback to summary
public boolean offer(E e)

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

Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full. This method is generally preferable to method add, which can fail to insert an element only by throwing an exception.

Exceptions
NullPointerException:
if the specified element is null
offerback to summary
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.offer.

Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.

Exceptions
InterruptedException:
if interrupted while waiting
NullPointerException:
if the specified element is null
peekback to summary
public E peek()

Implements java.util.Queue.peek.

Doc from java.util.Queue.peek.

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

pollback to summary
public E poll()

Implements java.util.Queue.poll.

Doc from java.util.Queue.poll.

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

pollback to summary
public E poll(long timeout, TimeUnit unit) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.poll.

Doc from 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.

Exceptions
InterruptedException:
if interrupted while waiting
putback to summary
public void put(E e) throws InterruptedException

Implements java.util.concurrent.BlockingQueue.put.

Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.

Exceptions
InterruptedException:
if interrupted while waiting
NullPointerException:
if the specified element is null
readObjectback to summary
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException

Reconstitutes this queue from a stream (that is, deserializes it).

Parameters
s:ObjectInputStream

the stream

Exceptions
IOException:
if an I/O error occurs
ClassNotFoundException:
if the class of a serialized object could not be found
InvalidObjectException:
if invariants are violated
remainingCapacityback to summary
public int remainingCapacity()

Implements java.util.concurrent.BlockingQueue.remainingCapacity.

Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking. This is always equal to the initial capacity of this queue less the current size of this queue.

Note that you cannot always tell if an attempt to insert an element will succeed by inspecting remainingCapacity because it may be the case that another thread is about to insert or remove an element.

removeback to summary
public boolean remove(Object 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. More formally, removes an element e such that o.equals(e), if this queue contains one or more such elements. Returns true if this queue contained the specified element (or equivalently, if this queue changed as a result of the call).

Removal of interior elements in circular array based queues is an intrinsically slow and disruptive operation, so should be undertaken only in exceptional circumstances, ideally only when the queue is known not to be accessible by other threads.

Parameters
o:Object

element to be removed from this queue, if present

Returns:boolean

true if this queue changed as a result of the call

removeAllback to summary
public boolean removeAll(Collection<?> c)

Overrides java.util.AbstractCollection.removeAll.

Implements java.util.Collection.removeAll.

Doc from java.util.Collection.removeAll.

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.

Exceptions
NullPointerException:
if this collection contains one or more null elements and the specified collection does not support null elements (optional) or if the specified collection is null
removeAtback to summary
pack-priv void removeAt(final int removeIndex)

Deletes item at array index removeIndex. Utility for remove(Object) and iterator.remove. Call only when holding lock.

removeIfback to summary
public boolean removeIf(Predicate<? super E> filter)

Overrides default java.util.Collection.removeIf.

Doc from java.util.Collection.removeIf.

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.

Exceptions
NullPointerException:
if the specified filter is null
retainAllback to summary
public boolean retainAll(Collection<?> c)

Overrides java.util.AbstractCollection.retainAll.

Implements java.util.Collection.retainAll.

Doc from java.util.Collection.retainAll.

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.

Exceptions
NullPointerException:
if this collection contains one or more null elements and the specified collection does not permit null elements (optional) or if the specified collection is null
setBitback to summary
private static void setBit(long[] bits, int i)
sizeback to summary
public int size()

Implements abstract java.util.AbstractCollection.size.

Implements java.util.Collection.size.

Returns the number of elements in this queue.

Returns:int

the number of elements in this queue

spliteratorback to summary
public Spliterator<E> spliterator()

Overrides default java.util.Collection.spliterator.

Returns a Spliterator over the elements in this queue.

The returned spliterator is weakly consistent.

The Spliterator reports Spliterator#CONCURRENT, Spliterator#ORDERED, and Spliterator#NONNULL.

Implementation Note

The Spliterator implements trySplit to permit limited parallelism.

Returns:Spliterator<E>

a Spliterator over the elements in this queue

Since
1.8
takeback to summary
public E take() throws InterruptedException

Implements java.util.concurrent.BlockingQueue.take.

Doc from java.util.concurrent.BlockingQueue.take.

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Exceptions
InterruptedException:
if interrupted while waiting
toArrayback to summary
public Object[] toArray()

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

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

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.

Returns:Object[]

an array containing all of the elements in this queue

toArrayback to summary
public <T> T[] toArray(T[] a)

Overrides java.util.AbstractCollection.toArray.

Implements java.util.Collection.toArray.

Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array. 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 null.

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

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

 String[] y = x.toArray(new String[0]);
Note that toArray(new Object[0]) is identical in function to toArray().
Parameters
a: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

Returns:T[]

an array containing all of the elements in this queue

Annotations
@SuppressWarnings:unchecked
Exceptions
ArrayStoreException:
if the runtime type of the specified array is not a supertype of the runtime type of every element in this queue
NullPointerException:
if the specified array is null
toStringback to summary
public String toString()

Overrides java.util.AbstractCollection.toString.

Doc from java.util.AbstractCollection.toString.

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 ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String#valueOf(Object).

writeObjectback to summary
private void writeObject(ObjectOutputStream s) throws IOException

Writes the queue to the stream whilst holding the locks to prevent broken invariants.

Parameters
s:ObjectOutputStream

the stream

Exceptions
IOException:
if an I/O error occurs
java.util.concurrent back to summary

private Class ArrayBlockingQueue.Itr

extends Object
implements Iterator<E>
Class Inheritance
All Implemented Interfaces
java.util.Iterator

Iterator for ArrayBlockingQueue. To maintain weak consistency with respect to puts and takes, we read ahead one slot, so as to not report hasNext true but then not have an element to return. We switch into "detached" mode (allowing prompt unlinking from itrs without help from the GC) when all indices are negative, or when hasNext returns false for the first time. This allows the iterator to track concurrent updates completely accurately, except for the corner case of the user calling Iterator.remove() after hasNext() returned false. Even in this case, we ensure that we don't remove the wrong element by keeping track of the expected element to remove, in lastItem. Yes, we may fail to remove lastItem from the queue if it moved due to an interleaved interior remove while in detached mode. Method forEachRemaining, added in Java 8, is treated similarly to hasNext returning false, in that we switch to detached mode, but we regard it as an even stronger request to "close" this iteration, and don't bother supporting subsequent remove().

Field Summary

Modifier and TypeField and Description
private int
cursor

Index to look for new nextItem; NONE at end

private static final int
DETACHED

Special value for prevTakeIndex indicating "detached mode"

private E
lastItem

Last element returned; null if none or not detached.

private int
lastRet

Index of lastItem, NONE if none, REMOVED if removed elsewhere

private int
nextIndex

Index of nextItem; NONE if none, REMOVED if removed elsewhere

private E
nextItem

Element to be returned by next call to next(); null if none

private static final int
NONE

Special index value indicating "not available" or "undefined"

private int
prevCycles

Previous value of iters.cycles

private int
prevTakeIndex

Previous value of takeIndex, or DETACHED when detached

private static final int
REMOVED

Special index value indicating "removed elsewhere", that is, removed by some operation other than a call to this.remove().

Constructor Summary

AccessConstructor and Description
pack-priv
Itr()

Method Summary

Modifier and TypeMethod and Description
private void
detach()

Called when itrs should stop tracking this iterator, either because there are no more indices to update (cursor < 0 && nextIndex < 0 && lastRet < 0) or as a special exception, when lastRet >= 0, because hasNext() is about to return false for the first time.

private int
distance(int index, int prevTakeIndex, int length)

public void
forEachRemaining(Consumer<? super E> action)

Overrides default java.util.Iterator.forEachRemaining.

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

public boolean
hasNext()

Implements java.util.Iterator.hasNext.

For performance reasons, we would like not to acquire a lock in hasNext in the common case.

private int
incCursor(int index)

private void
incorporateDequeues()

Adjusts indices to incorporate all dequeues since the last operation on this iterator.

private boolean
invalidated(int index, int prevTakeIndex, long dequeues, int length)

Returns true if index is invalidated by the given number of dequeues, starting from prevTakeIndex.

pack-priv boolean
public E
next()

Implements java.util.Iterator.next.

Returns the next element in the iteration.

private void
public void
remove()

Overrides default java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation).

pack-priv boolean

Returns:

true if this iterator should be unlinked from itrs
removedAt
(int removedIndex)

Called whenever an interior remove (not at takeIndex) occurred.

pack-priv void
shutdown()

Called to notify the iterator that the queue is empty, or that it has fallen hopelessly behind, so that it should abandon any further iteration, except possibly to return one more element from next(), as promised by returning true from hasNext().

pack-priv boolean

Returns:

true if this iterator should be unlinked from itrs
takeIndexWrapped
()

Called whenever takeIndex wraps around to zero.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

cursorback to summary
private int cursor

Index to look for new nextItem; NONE at end

DETACHEDback to summary
private static final int DETACHED

Special value for prevTakeIndex indicating "detached mode"

lastItemback to summary
private E lastItem

Last element returned; null if none or not detached.

lastRetback to summary
private int lastRet

Index of lastItem, NONE if none, REMOVED if removed elsewhere

nextIndexback to summary
private int nextIndex

Index of nextItem; NONE if none, REMOVED if removed elsewhere

nextItemback to summary
private E nextItem

Element to be returned by next call to next(); null if none

NONEback to summary
private static final int NONE

Special index value indicating "not available" or "undefined"

prevCyclesback to summary
private int prevCycles

Previous value of iters.cycles

prevTakeIndexback to summary
private int prevTakeIndex

Previous value of takeIndex, or DETACHED when detached

REMOVEDback to summary
private static final int REMOVED

Special index value indicating "removed elsewhere", that is, removed by some operation other than a call to this.remove().

Constructor Detail

Itrback to summary
pack-priv Itr()

Method Detail

detachback to summary
private void detach()

Called when itrs should stop tracking this iterator, either because there are no more indices to update (cursor < 0 && nextIndex < 0 && lastRet < 0) or as a special exception, when lastRet >= 0, because hasNext() is about to return false for the first time. Call only from iterating thread.

distanceback to summary
private int distance(int index, int prevTakeIndex, int length)
forEachRemainingback to summary
public void forEachRemaining(Consumer<? super E> action)

Overrides default java.util.Iterator.forEachRemaining.

Doc from java.util.Iterator.forEachRemaining.

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 remove method or other mutator methods of Iterator subtypes), unless an overriding class has specified a concurrent modification policy.

Subsequent behavior of an iterator is unspecified if the action throws an exception.

hasNextback to summary
public boolean hasNext()

Implements java.util.Iterator.hasNext.

For performance reasons, we would like not to acquire a lock in hasNext in the common case. To allow for this, we only access fields (i.e. nextItem) that are not modified by update operations triggered by queue modifications.

incCursorback to summary
private int incCursor(int index)
incorporateDequeuesback to summary
private void incorporateDequeues()

Adjusts indices to incorporate all dequeues since the last operation on this iterator. Call only from iterating thread.

invalidatedback to summary
private boolean invalidated(int index, int prevTakeIndex, long dequeues, int length)

Returns true if index is invalidated by the given number of dequeues, starting from prevTakeIndex.

isDetachedback to summary
pack-priv boolean isDetached()
nextback to summary
public E next()

Implements java.util.Iterator.next.

Doc from java.util.Iterator.next.

Returns the next element in the iteration.

noNextback to summary
private void noNext()
removeback to summary
public void remove()

Overrides default java.util.Iterator.remove.

Doc from java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next.

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 forEachRemaining method.

removedAtback to summary
pack-priv boolean removedAt(int removedIndex)

Called whenever an interior remove (not at takeIndex) occurred.

Returns:boolean

true if this iterator should be unlinked from itrs

shutdownback to summary
pack-priv void shutdown()

Called to notify the iterator that the queue is empty, or that it has fallen hopelessly behind, so that it should abandon any further iteration, except possibly to return one more element from next(), as promised by returning true from hasNext().

takeIndexWrappedback to summary
pack-priv boolean takeIndexWrapped()

Called whenever takeIndex wraps around to zero.

Returns:boolean

true if this iterator should be unlinked from itrs

java.util.concurrent back to summary

pack-priv Class ArrayBlockingQueue.Itrs

extends Object
Class Inheritance

Shared data between iterators and their queue, allowing queue modifications to update iterators when elements are removed. This adds a lot of complexity for the sake of correctly handling some uncommon operations, but the combination of circular-arrays and supporting interior removes (i.e., those not at head) would cause iterators to sometimes lose their places and/or (re)report elements they shouldn't. To avoid this, when a queue has one or more iterators, it keeps iterator state consistent by: (1) keeping track of the number of "cycles", that is, the number of times takeIndex has wrapped around to 0. (2) notifying all iterators via the callback removedAt whenever an interior element is removed (and thus other elements may be shifted). These suffice to eliminate iterator inconsistencies, but unfortunately add the secondary responsibility of maintaining the list of iterators. We track all active iterators in a simple linked list (accessed only when the queue's lock is held) of weak references to Itr. The list is cleaned up using 3 different mechanisms: (1) Whenever a new iterator is created, do some O(1) checking for stale list elements. (2) Whenever takeIndex wraps around to 0, check for iterators that have been unused for more than one wrap-around cycle. (3) Whenever the queue becomes empty, all iterators are notified and this entire data structure is discarded. So in addition to the removedAt callback that is necessary for correctness, iterators have the shutdown and takeIndexWrapped callbacks that help remove stale iterators from the list. Whenever a list element is examined, it is expunged if either the GC has determined that the iterator is discarded, or if the iterator reports that it is "detached" (does not need any further state updates). Overhead is maximal when takeIndex never advances, iterators are discarded before they are exhausted, and all removals are interior removes, in which case all stale iterators are discovered by the GC. But even in this case we don't increase the amortized complexity. Care must be taken to keep list sweeping methods from reentrantly invoking another such method, causing subtle corruption bugs.

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
ArrayBlockingQueue.Itrs.Node

Node in a linked list of weak iterator references.

Field Summary

Modifier and TypeField and Description
pack-priv int
cycles

Incremented whenever takeIndex wraps around to 0

private ArrayBlockingQueue<E>.Itrs.Node
head

Linked list of weak iterator references

private static final int
private static final int
private ArrayBlockingQueue<E>.Itrs.Node
sweeper

Used to expunge stale iterators

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
pack-priv void
doSomeSweeping(boolean
whether to start in try-harder mode, because there is known to be at least one iterator to collect
tryHarder
)

Sweeps itrs, looking for and expunging stale iterators.

pack-priv void
elementDequeued()

Called whenever an element has been dequeued (at takeIndex).

pack-priv void
queueIsEmpty()

Called whenever the queue becomes empty.

pack-priv void
register(ArrayBlockingQueue<E>.Itr itr)

Adds a new iterator to the linked list of tracked iterators.

pack-priv void
removedAt(int removedIndex)

Called whenever an interior remove (not at takeIndex) occurred.

pack-priv void
takeIndexWrapped()

Called whenever takeIndex wraps around to 0.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

cyclesback to summary
pack-priv int cycles

Incremented whenever takeIndex wraps around to 0

headback to summary
private ArrayBlockingQueue<E>.Itrs.Node head

Linked list of weak iterator references

LONG_SWEEP_PROBESback to summary
private static final int LONG_SWEEP_PROBES
SHORT_SWEEP_PROBESback to summary
private static final int SHORT_SWEEP_PROBES
sweeperback to summary
private ArrayBlockingQueue<E>.Itrs.Node sweeper

Used to expunge stale iterators

Constructor Detail

Itrsback to summary
pack-priv Itrs(ArrayBlockingQueue<E>.Itr initial)

Method Detail

doSomeSweepingback to summary
pack-priv void doSomeSweeping(boolean tryHarder)

Sweeps itrs, looking for and expunging stale iterators. If at least one was found, tries harder to find more. Called only from iterating thread.

Parameters
tryHarder:boolean

whether to start in try-harder mode, because there is known to be at least one iterator to collect

elementDequeuedback to summary
pack-priv void elementDequeued()

Called whenever an element has been dequeued (at takeIndex).

queueIsEmptyback to summary
pack-priv void queueIsEmpty()

Called whenever the queue becomes empty. Notifies all active iterators that the queue is empty, clears all weak refs, and unlinks the itrs datastructure.

registerback to summary
pack-priv void register(ArrayBlockingQueue<E>.Itr itr)

Adds a new iterator to the linked list of tracked iterators.

removedAtback to summary
pack-priv void removedAt(int removedIndex)

Called whenever an interior remove (not at takeIndex) occurred. Notifies all iterators, and expunges any that are now stale.

takeIndexWrappedback to summary
pack-priv void takeIndexWrapped()

Called whenever takeIndex wraps around to 0. Notifies all iterators, and expunges any that are now stale.

java.util.concurrent back to summary

private Class ArrayBlockingQueue.Itrs.Node

extends WeakReference<ArrayBlockingQueue<E>.Itr>
Class Inheritance

Node in a linked list of weak iterator references.

Field Summary

Modifier and TypeField and Description
pack-priv ArrayBlockingQueue<E>.Itrs.Node

Constructor Summary

AccessConstructor and Description
pack-priv

Constructor Detail

Nodeback to summary
pack-priv Node(ArrayBlockingQueue<E>.Itr iterator, ArrayBlockingQueue<E>.Itrs.Node next)