0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea with assistance from members of JCP JSR-166
0N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/Apackage java.util.concurrent;
0N/Aimport java.util.concurrent.locks.*;
0N/Aimport java.util.*;
0N/A
0N/A/**
0N/A * A bounded {@linkplain BlockingQueue blocking queue} backed by an
0N/A * array. This queue orders elements FIFO (first-in-first-out). The
0N/A * <em>head</em> of the queue is that element that has been on the
0N/A * queue the longest time. The <em>tail</em> of the queue is that
0N/A * element that has been on the queue the shortest time. New elements
0N/A * are inserted at the tail of the queue, and the queue retrieval
0N/A * operations obtain elements at the head of the queue.
0N/A *
0N/A * <p>This is a classic &quot;bounded buffer&quot;, in which a
0N/A * fixed-sized array holds elements inserted by producers and
0N/A * extracted by consumers. Once created, the capacity cannot be
3387N/A * changed. Attempts to {@code put} an element into a full queue
3387N/A * will result in the operation blocking; attempts to {@code take} an
0N/A * element from an empty queue will similarly block.
0N/A *
3387N/A * <p>This class supports an optional fairness policy for ordering
0N/A * waiting producer and consumer threads. By default, this ordering
0N/A * is not guaranteed. However, a queue constructed with fairness set
3387N/A * to {@code true} grants threads access in FIFO order. Fairness
0N/A * generally decreases throughput but reduces variability and avoids
0N/A * starvation.
0N/A *
0N/A * <p>This class and its iterator implement all of the
0N/A * <em>optional</em> methods of the {@link Collection} and {@link
0N/A * Iterator} interfaces.
0N/A *
0N/A * <p>This class is a member of the
0N/A * <a href="{@docRoot}/../technotes/guides/collections/index.html">
0N/A * Java Collections Framework</a>.
0N/A *
0N/A * @since 1.5
0N/A * @author Doug Lea
0N/A * @param <E> the type of elements held in this collection
0N/A */
0N/Apublic class ArrayBlockingQueue<E> extends AbstractQueue<E>
0N/A implements BlockingQueue<E>, java.io.Serializable {
0N/A
0N/A /**
0N/A * Serialization ID. This class relies on default serialization
0N/A * even for the items array, which is default-serialized, even if
0N/A * it is empty. Otherwise it could not be declared final, which is
0N/A * necessary here.
0N/A */
0N/A private static final long serialVersionUID = -817911632652898426L;
0N/A
3387N/A /** The queued items */
3387N/A final Object[] items;
3387N/A
3387N/A /** items index for next take, poll, peek or remove */
3387N/A int takeIndex;
3387N/A
3387N/A /** items index for next put, offer, or add */
3387N/A int putIndex;
3387N/A
3387N/A /** Number of elements in the queue */
3387N/A int count;
0N/A
0N/A /*
0N/A * Concurrency control uses the classic two-condition algorithm
0N/A * found in any textbook.
0N/A */
0N/A
0N/A /** Main lock guarding all access */
3387N/A final ReentrantLock lock;
0N/A /** Condition for waiting takes */
0N/A private final Condition notEmpty;
0N/A /** Condition for waiting puts */
0N/A private final Condition notFull;
0N/A
0N/A // Internal helper methods
0N/A
0N/A /**
0N/A * Circularly increment i.
0N/A */
0N/A final int inc(int i) {
3387N/A return (++i == items.length) ? 0 : i;
3387N/A }
3387N/A
3387N/A /**
3387N/A * Circularly decrement i.
3387N/A */
3387N/A final int dec(int i) {
3387N/A return ((i == 0) ? items.length : i) - 1;
3387N/A }
3387N/A
3387N/A @SuppressWarnings("unchecked")
3387N/A static <E> E cast(Object item) {
3387N/A return (E) item;
3387N/A }
3387N/A
3387N/A /**
3387N/A * Returns item at index i.
3387N/A */
3387N/A final E itemAt(int i) {
3387N/A return this.<E>cast(items[i]);
3387N/A }
3387N/A
3387N/A /**
3387N/A * Throws NullPointerException if argument is null.
3387N/A *
3387N/A * @param v the element
3387N/A */
3387N/A private static void checkNotNull(Object v) {
3387N/A if (v == null)
3387N/A throw new NullPointerException();
0N/A }
0N/A
0N/A /**
0N/A * Inserts element at current put position, advances, and signals.
0N/A * Call only when holding lock.
0N/A */
0N/A private void insert(E x) {
0N/A items[putIndex] = x;
0N/A putIndex = inc(putIndex);
0N/A ++count;
0N/A notEmpty.signal();
0N/A }
0N/A
0N/A /**
0N/A * Extracts element at current take position, advances, and signals.
0N/A * Call only when holding lock.
0N/A */
0N/A private E extract() {
3387N/A final Object[] items = this.items;
3387N/A E x = this.<E>cast(items[takeIndex]);
0N/A items[takeIndex] = null;
0N/A takeIndex = inc(takeIndex);
0N/A --count;
0N/A notFull.signal();
0N/A return x;
0N/A }
0N/A
0N/A /**
3387N/A * Deletes item at position i.
3387N/A * Utility for remove and iterator.remove.
0N/A * Call only when holding lock.
0N/A */
0N/A void removeAt(int i) {
3387N/A final Object[] items = this.items;
0N/A // if removing front item, just advance
0N/A if (i == takeIndex) {
0N/A items[takeIndex] = null;
0N/A takeIndex = inc(takeIndex);
0N/A } else {
0N/A // slide over all others up through putIndex.
0N/A for (;;) {
0N/A int nexti = inc(i);
0N/A if (nexti != putIndex) {
0N/A items[i] = items[nexti];
0N/A i = nexti;
0N/A } else {
0N/A items[i] = null;
0N/A putIndex = i;
0N/A break;
0N/A }
0N/A }
0N/A }
0N/A --count;
0N/A notFull.signal();
0N/A }
0N/A
0N/A /**
3387N/A * Creates an {@code ArrayBlockingQueue} with the given (fixed)
0N/A * capacity and default access policy.
0N/A *
0N/A * @param capacity the capacity of this queue
3387N/A * @throws IllegalArgumentException if {@code capacity < 1}
0N/A */
0N/A public ArrayBlockingQueue(int capacity) {
0N/A this(capacity, false);
0N/A }
0N/A
0N/A /**
3387N/A * Creates an {@code ArrayBlockingQueue} with the given (fixed)
0N/A * capacity and the specified access policy.
0N/A *
0N/A * @param capacity the capacity of this queue
3387N/A * @param fair if {@code true} then queue accesses for threads blocked
0N/A * on insertion or removal, are processed in FIFO order;
3387N/A * if {@code false} the access order is unspecified.
3387N/A * @throws IllegalArgumentException if {@code capacity < 1}
0N/A */
0N/A public ArrayBlockingQueue(int capacity, boolean fair) {
0N/A if (capacity <= 0)
0N/A throw new IllegalArgumentException();
3387N/A this.items = new Object[capacity];
0N/A lock = new ReentrantLock(fair);
0N/A notEmpty = lock.newCondition();
0N/A notFull = lock.newCondition();
0N/A }
0N/A
0N/A /**
3387N/A * Creates an {@code ArrayBlockingQueue} with the given (fixed)
0N/A * capacity, the specified access policy and initially containing the
0N/A * elements of the given collection,
0N/A * added in traversal order of the collection's iterator.
0N/A *
0N/A * @param capacity the capacity of this queue
3387N/A * @param fair if {@code true} then queue accesses for threads blocked
0N/A * on insertion or removal, are processed in FIFO order;
3387N/A * if {@code false} the access order is unspecified.
0N/A * @param c the collection of elements to initially contain
3387N/A * @throws IllegalArgumentException if {@code capacity} is less than
3387N/A * {@code c.size()}, or less than 1.
0N/A * @throws NullPointerException if the specified collection or any
0N/A * of its elements are null
0N/A */
0N/A public ArrayBlockingQueue(int capacity, boolean fair,
0N/A Collection<? extends E> c) {
0N/A this(capacity, fair);
0N/A
3387N/A final ReentrantLock lock = this.lock;
3387N/A lock.lock(); // Lock only for visibility, not mutual exclusion
3387N/A try {
3387N/A int i = 0;
3387N/A try {
3387N/A for (E e : c) {
3387N/A checkNotNull(e);
3387N/A items[i++] = e;
3387N/A }
3387N/A } catch (ArrayIndexOutOfBoundsException ex) {
3387N/A throw new IllegalArgumentException();
3387N/A }
3387N/A count = i;
3387N/A putIndex = (i == capacity) ? 0 : i;
3387N/A } finally {
3387N/A lock.unlock();
3387N/A }
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element at the tail of this queue if it is
0N/A * possible to do so immediately without exceeding the queue's capacity,
3387N/A * returning {@code true} upon success and throwing an
3387N/A * {@code IllegalStateException} if this queue is full.
0N/A *
0N/A * @param e the element to add
3387N/A * @return {@code true} (as specified by {@link Collection#add})
0N/A * @throws IllegalStateException if this queue is full
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean add(E e) {
0N/A return super.add(e);
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element at the tail of this queue if it is
0N/A * possible to do so immediately without exceeding the queue's capacity,
3387N/A * returning {@code true} upon success and {@code false} if this queue
0N/A * is full. This method is generally preferable to method {@link #add},
0N/A * which can fail to insert an element only by throwing an exception.
0N/A *
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean offer(E e) {
3387N/A checkNotNull(e);
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A if (count == items.length)
0N/A return false;
0N/A else {
0N/A insert(e);
0N/A return true;
0N/A }
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element at the tail of this queue, waiting
0N/A * for space to become available if the queue is full.
0N/A *
0N/A * @throws InterruptedException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public void put(E e) throws InterruptedException {
3387N/A checkNotNull(e);
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3387N/A while (count == items.length)
3387N/A notFull.await();
0N/A insert(e);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element at the tail of this queue, waiting
0N/A * up to the specified wait time for space to become available if
0N/A * the queue is full.
0N/A *
0N/A * @throws InterruptedException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public boolean offer(E e, long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A
3387N/A checkNotNull(e);
0N/A long nanos = unit.toNanos(timeout);
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3387N/A while (count == items.length) {
0N/A if (nanos <= 0)
0N/A return false;
3387N/A nanos = notFull.awaitNanos(nanos);
0N/A }
3387N/A insert(e);
3387N/A return true;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E poll() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A return (count == 0) ? null : extract();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E take() throws InterruptedException {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3387N/A while (count == 0)
3387N/A notEmpty.await();
3387N/A return extract();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E poll(long timeout, TimeUnit unit) throws InterruptedException {
0N/A long nanos = unit.toNanos(timeout);
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3387N/A while (count == 0) {
0N/A if (nanos <= 0)
0N/A return null;
3387N/A nanos = notEmpty.awaitNanos(nanos);
0N/A }
3387N/A return extract();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E peek() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A return (count == 0) ? null : itemAt(takeIndex);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A // this doc comment is overridden to remove the reference to collections
0N/A // greater in size than Integer.MAX_VALUE
0N/A /**
0N/A * Returns the number of elements in this queue.
0N/A *
0N/A * @return the number of elements in this queue
0N/A */
0N/A public int size() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return count;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A // this doc comment is a modified copy of the inherited doc comment,
0N/A // without the reference to unlimited queues.
0N/A /**
0N/A * Returns the number of additional elements that this queue can ideally
0N/A * (in the absence of memory or resource constraints) accept without
0N/A * blocking. This is always equal to the initial capacity of this queue
3387N/A * less the current {@code size} of this queue.
0N/A *
0N/A * <p>Note that you <em>cannot</em> always tell if an attempt to insert
3387N/A * an element will succeed by inspecting {@code remainingCapacity}
0N/A * because it may be the case that another thread is about to
0N/A * insert or remove an element.
0N/A */
0N/A public int remainingCapacity() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return items.length - count;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Removes a single instance of the specified element from this queue,
3387N/A * if it is present. More formally, removes an element {@code e} such
3387N/A * that {@code o.equals(e)}, if this queue contains one or more such
0N/A * elements.
3387N/A * Returns {@code true} if this queue contained the specified element
0N/A * (or equivalently, if this queue changed as a result of the call).
0N/A *
3387N/A * <p>Removal of interior elements in circular array based queues
3387N/A * is an intrinsically slow and disruptive operation, so should
3387N/A * be undertaken only in exceptional circumstances, ideally
3387N/A * only when the queue is known not to be accessible by other
3387N/A * threads.
3387N/A *
0N/A * @param o element to be removed from this queue, if present
3387N/A * @return {@code true} if this queue changed as a result of the call
0N/A */
0N/A public boolean remove(Object o) {
0N/A if (o == null) return false;
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A for (int i = takeIndex, k = count; k > 0; i = inc(i), k--) {
0N/A if (o.equals(items[i])) {
0N/A removeAt(i);
0N/A return true;
0N/A }
0N/A }
3387N/A return false;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
3387N/A * Returns {@code true} if this queue contains the specified element.
3387N/A * More formally, returns {@code true} if and only if this queue contains
3387N/A * at least one element {@code e} such that {@code o.equals(e)}.
0N/A *
0N/A * @param o object to be checked for containment in this queue
3387N/A * @return {@code true} if this queue contains the specified element
0N/A */
0N/A public boolean contains(Object o) {
0N/A if (o == null) return false;
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
0N/A if (o.equals(items[i]))
0N/A return true;
0N/A return false;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this queue, in
0N/A * proper sequence.
0N/A *
0N/A * <p>The returned array will be "safe" in that no references to it are
0N/A * maintained by this queue. (In other words, this method must allocate
0N/A * a new array). The caller is thus free to modify the returned array.
0N/A *
0N/A * <p>This method acts as bridge between array-based and collection-based
0N/A * APIs.
0N/A *
0N/A * @return an array containing all of the elements in this queue
0N/A */
0N/A public Object[] toArray() {
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A final int count = this.count;
0N/A Object[] a = new Object[count];
3387N/A for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
3387N/A a[k] = items[i];
0N/A return a;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this queue, in
0N/A * proper sequence; the runtime type of the returned array is that of
0N/A * the specified array. If the queue fits in the specified array, it
0N/A * is returned therein. Otherwise, a new array is allocated with the
0N/A * runtime type of the specified array and the size of this queue.
0N/A *
0N/A * <p>If this queue fits in the specified array with room to spare
0N/A * (i.e., the array has more elements than this queue), the element in
0N/A * the array immediately following the end of the queue is set to
3387N/A * {@code null}.
0N/A *
0N/A * <p>Like the {@link #toArray()} method, this method acts as bridge between
0N/A * array-based and collection-based APIs. Further, this method allows
0N/A * precise control over the runtime type of the output array, and may,
0N/A * under certain circumstances, be used to save allocation costs.
0N/A *
3387N/A * <p>Suppose {@code x} is a queue known to contain only strings.
0N/A * The following code can be used to dump the queue into a newly
3387N/A * allocated array of {@code String}:
0N/A *
0N/A * <pre>
0N/A * String[] y = x.toArray(new String[0]);</pre>
0N/A *
3387N/A * Note that {@code toArray(new Object[0])} is identical in function to
3387N/A * {@code toArray()}.
0N/A *
0N/A * @param a the array into which the elements of the queue are to
0N/A * be stored, if it is big enough; otherwise, a new array of the
0N/A * same runtime type is allocated for this purpose
0N/A * @return an array containing all of the elements in this queue
0N/A * @throws ArrayStoreException if the runtime type of the specified array
0N/A * is not a supertype of the runtime type of every element in
0N/A * this queue
0N/A * @throws NullPointerException if the specified array is null
0N/A */
3387N/A @SuppressWarnings("unchecked")
0N/A public <T> T[] toArray(T[] a) {
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A final int count = this.count;
3387N/A final int len = a.length;
3387N/A if (len < count)
0N/A a = (T[])java.lang.reflect.Array.newInstance(
3387N/A a.getClass().getComponentType(), count);
3387N/A for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
3387N/A a[k] = (T) items[i];
3387N/A if (len > count)
0N/A a[count] = null;
0N/A return a;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public String toString() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A int k = count;
3387N/A if (k == 0)
3387N/A return "[]";
3387N/A
3387N/A StringBuilder sb = new StringBuilder();
3387N/A sb.append('[');
3387N/A for (int i = takeIndex; ; i = inc(i)) {
3387N/A Object e = items[i];
3387N/A sb.append(e == this ? "(this Collection)" : e);
3387N/A if (--k == 0)
3387N/A return sb.append(']').toString();
3387N/A sb.append(',').append(' ');
3387N/A }
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Atomically removes all of the elements from this queue.
0N/A * The queue will be empty after this call returns.
0N/A */
0N/A public void clear() {
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3387N/A for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
0N/A items[i] = null;
0N/A count = 0;
0N/A putIndex = 0;
0N/A takeIndex = 0;
0N/A notFull.signalAll();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c) {
3387N/A checkNotNull(c);
0N/A if (c == this)
0N/A throw new IllegalArgumentException();
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A int i = takeIndex;
0N/A int n = 0;
0N/A int max = count;
0N/A while (n < max) {
3387N/A c.add(this.<E>cast(items[i]));
0N/A items[i] = null;
0N/A i = inc(i);
0N/A ++n;
0N/A }
0N/A if (n > 0) {
0N/A count = 0;
0N/A putIndex = 0;
0N/A takeIndex = 0;
0N/A notFull.signalAll();
0N/A }
0N/A return n;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c, int maxElements) {
3387N/A checkNotNull(c);
0N/A if (c == this)
0N/A throw new IllegalArgumentException();
0N/A if (maxElements <= 0)
0N/A return 0;
3387N/A final Object[] items = this.items;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A int i = takeIndex;
0N/A int n = 0;
3387N/A int max = (maxElements < count) ? maxElements : count;
0N/A while (n < max) {
3387N/A c.add(this.<E>cast(items[i]));
0N/A items[i] = null;
0N/A i = inc(i);
0N/A ++n;
0N/A }
0N/A if (n > 0) {
0N/A count -= n;
0N/A takeIndex = i;
0N/A notFull.signalAll();
0N/A }
0N/A return n;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an iterator over the elements in this queue in proper sequence.
3387N/A * The elements will be returned in order from first (head) to last (tail).
3387N/A *
3387N/A * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
3387N/A * will never throw {@link java.util.ConcurrentModificationException
3387N/A * ConcurrentModificationException},
0N/A * and guarantees to traverse elements as they existed upon
0N/A * construction of the iterator, and may (but is not guaranteed to)
0N/A * reflect any modifications subsequent to construction.
0N/A *
0N/A * @return an iterator over the elements in this queue in proper sequence
0N/A */
0N/A public Iterator<E> iterator() {
3387N/A return new Itr();
0N/A }
0N/A
0N/A /**
3387N/A * Iterator for ArrayBlockingQueue. To maintain weak consistency
3387N/A * with respect to puts and takes, we (1) read ahead one slot, so
3387N/A * as to not report hasNext true but then not have an element to
3387N/A * return -- however we later recheck this slot to use the most
3387N/A * current value; (2) ensure that each array slot is traversed at
3387N/A * most once (by tracking "remaining" elements); (3) skip over
3387N/A * null slots, which can occur if takes race ahead of iterators.
3387N/A * However, for circular array-based queues, we cannot rely on any
3387N/A * well established definition of what it means to be weakly
3387N/A * consistent with respect to interior removes since these may
3387N/A * require slot overwrites in the process of sliding elements to
3387N/A * cover gaps. So we settle for resiliency, operating on
3387N/A * established apparent nexts, which may miss some elements that
3387N/A * have moved between calls to next.
0N/A */
0N/A private class Itr implements Iterator<E> {
3387N/A private int remaining; // Number of elements yet to be returned
3387N/A private int nextIndex; // Index of element to be returned by next
3387N/A private E nextItem; // Element to be returned by next call to next
3387N/A private E lastItem; // Element returned by last call to next
3387N/A private int lastRet; // Index of last element returned, or -1 if none
0N/A
0N/A Itr() {
3387N/A final ReentrantLock lock = ArrayBlockingQueue.this.lock;
3387N/A lock.lock();
3387N/A try {
3387N/A lastRet = -1;
3387N/A if ((remaining = count) > 0)
3387N/A nextItem = itemAt(nextIndex = takeIndex);
3387N/A } finally {
3387N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public boolean hasNext() {
3387N/A return remaining > 0;
0N/A }
0N/A
0N/A public E next() {
0N/A final ReentrantLock lock = ArrayBlockingQueue.this.lock;
0N/A lock.lock();
0N/A try {
3387N/A if (remaining <= 0)
0N/A throw new NoSuchElementException();
0N/A lastRet = nextIndex;
3387N/A E x = itemAt(nextIndex); // check for fresher value
3387N/A if (x == null) {
3387N/A x = nextItem; // we are forced to report old value
3387N/A lastItem = null; // but ensure remove fails
3387N/A }
3387N/A else
3387N/A lastItem = x;
3387N/A while (--remaining > 0 && // skip over nulls
3387N/A (nextItem = itemAt(nextIndex = inc(nextIndex))) == null)
3387N/A ;
0N/A return x;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public void remove() {
0N/A final ReentrantLock lock = ArrayBlockingQueue.this.lock;
0N/A lock.lock();
0N/A try {
0N/A int i = lastRet;
0N/A if (i == -1)
0N/A throw new IllegalStateException();
0N/A lastRet = -1;
3387N/A E x = lastItem;
3387N/A lastItem = null;
3387N/A // only remove if item still at index
3387N/A if (x != null && x == items[i]) {
3387N/A boolean removingHead = (i == takeIndex);
3387N/A removeAt(i);
3387N/A if (!removingHead)
3387N/A nextIndex = dec(nextIndex);
3387N/A }
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A }
3387N/A
0N/A}