2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
37 import java.util.concurrent.locks.*;
41 * A bounded {@linkplain BlockingQueue blocking queue} backed by an
42 * array. This queue orders elements FIFO (first-in-first-out). The
43 * <em>head</em> of the queue is that element that has been on the
44 * queue the longest time. The <em>tail</em> of the queue is that
45 * element that has been on the queue the shortest time. New elements
46 * are inserted at the tail of the queue, and the queue retrieval
47 * operations obtain elements at the head of the queue.
49 * <p>This is a classic "bounded buffer", in which a
50 * fixed-sized array holds elements inserted by producers and
51 * extracted by consumers. Once created, the capacity cannot be
52 * changed. Attempts to {@code put} an element into a full queue
53 * will result in the operation blocking; attempts to {@code take} an
54 * element from an empty queue will similarly block.
56 * <p>This class supports an optional fairness policy for ordering
57 * waiting producer and consumer threads. By default, this ordering
58 * is not guaranteed. However, a queue constructed with fairness set
59 * to {@code true} grants threads access in FIFO order. Fairness
60 * generally decreases throughput but reduces variability and avoids
63 * <p>This class and its iterator implement all of the
64 * <em>optional</em> methods of the {@link Collection} and {@link
65 * Iterator} interfaces.
67 * <p>This class is a member of the
68 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
69 * Java Collections Framework</a>.
73 * @param <E> the type of elements held in this collection
75 public class ArrayBlockingQueue<E> extends AbstractQueue<E>
76 implements BlockingQueue<E>, java.io.Serializable {
79 * Serialization ID. This class relies on default serialization
80 * even for the items array, which is default-serialized, even if
81 * it is empty. Otherwise it could not be declared final, which is
84 private static final long serialVersionUID = -817911632652898426L;
86 /** The queued items */
89 /** items index for next take, poll, peek or remove */
92 /** items index for next put, offer, or add */
95 /** Number of elements in the queue */
99 * Concurrency control uses the classic two-condition algorithm
100 * found in any textbook.
103 /** Main lock guarding all access */
104 final ReentrantLock lock;
105 /** Condition for waiting takes */
106 private final Condition notEmpty;
107 /** Condition for waiting puts */
108 private final Condition notFull;
110 // Internal helper methods
113 * Circularly increment i.
115 final int inc(int i) {
116 return (++i == items.length) ? 0 : i;
120 * Circularly decrement i.
122 final int dec(int i) {
123 return ((i == 0) ? items.length : i) - 1;
126 @SuppressWarnings("unchecked")
127 static <E> E cast(Object item) {
132 * Returns item at index i.
134 final E itemAt(int i) {
135 return this.<E>cast(items[i]);
139 * Throws NullPointerException if argument is null.
141 * @param v the element
143 private static void checkNotNull(Object v) {
145 throw new NullPointerException();
149 * Inserts element at current put position, advances, and signals.
150 * Call only when holding lock.
152 private void insert(E x) {
154 putIndex = inc(putIndex);
160 * Extracts element at current take position, advances, and signals.
161 * Call only when holding lock.
163 private E extract() {
164 final Object[] items = this.items;
165 E x = this.<E>cast(items[takeIndex]);
166 items[takeIndex] = null;
167 takeIndex = inc(takeIndex);
174 * Deletes item at position i.
175 * Utility for remove and iterator.remove.
176 * Call only when holding lock.
178 void removeAt(int i) {
179 final Object[] items = this.items;
180 // if removing front item, just advance
181 if (i == takeIndex) {
182 items[takeIndex] = null;
183 takeIndex = inc(takeIndex);
185 // slide over all others up through putIndex.
188 if (nexti != putIndex) {
189 items[i] = items[nexti];
203 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
204 * capacity and default access policy.
206 * @param capacity the capacity of this queue
207 * @throws IllegalArgumentException if {@code capacity < 1}
209 public ArrayBlockingQueue(int capacity) {
210 this(capacity, false);
214 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
215 * capacity and the specified access policy.
217 * @param capacity the capacity of this queue
218 * @param fair if {@code true} then queue accesses for threads blocked
219 * on insertion or removal, are processed in FIFO order;
220 * if {@code false} the access order is unspecified.
221 * @throws IllegalArgumentException if {@code capacity < 1}
223 public ArrayBlockingQueue(int capacity, boolean fair) {
225 throw new IllegalArgumentException();
226 this.items = new Object[capacity];
227 lock = new ReentrantLock(fair);
228 notEmpty = lock.newCondition();
229 notFull = lock.newCondition();
233 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
234 * capacity, the specified access policy and initially containing the
235 * elements of the given collection,
236 * added in traversal order of the collection's iterator.
238 * @param capacity the capacity of this queue
239 * @param fair if {@code true} then queue accesses for threads blocked
240 * on insertion or removal, are processed in FIFO order;
241 * if {@code false} the access order is unspecified.
242 * @param c the collection of elements to initially contain
243 * @throws IllegalArgumentException if {@code capacity} is less than
244 * {@code c.size()}, or less than 1.
245 * @throws NullPointerException if the specified collection or any
246 * of its elements are null
248 public ArrayBlockingQueue(int capacity, boolean fair,
249 Collection<? extends E> c) {
250 this(capacity, fair);
252 final ReentrantLock lock = this.lock;
253 lock.lock(); // Lock only for visibility, not mutual exclusion
261 } catch (ArrayIndexOutOfBoundsException ex) {
262 throw new IllegalArgumentException();
265 putIndex = (i == capacity) ? 0 : i;
272 * Inserts the specified element at the tail of this queue if it is
273 * possible to do so immediately without exceeding the queue's capacity,
274 * returning {@code true} upon success and throwing an
275 * {@code IllegalStateException} if this queue is full.
277 * @param e the element to add
278 * @return {@code true} (as specified by {@link Collection#add})
279 * @throws IllegalStateException if this queue is full
280 * @throws NullPointerException if the specified element is null
282 public boolean add(E e) {
287 * Inserts the specified element at the tail of this queue if it is
288 * possible to do so immediately without exceeding the queue's capacity,
289 * returning {@code true} upon success and {@code false} if this queue
290 * is full. This method is generally preferable to method {@link #add},
291 * which can fail to insert an element only by throwing an exception.
293 * @throws NullPointerException if the specified element is null
295 public boolean offer(E e) {
297 final ReentrantLock lock = this.lock;
300 if (count == items.length)
312 * Inserts the specified element at the tail of this queue, waiting
313 * for space to become available if the queue is full.
315 * @throws InterruptedException {@inheritDoc}
316 * @throws NullPointerException {@inheritDoc}
318 public void put(E e) throws InterruptedException {
320 final ReentrantLock lock = this.lock;
321 lock.lockInterruptibly();
323 while (count == items.length)
332 * Inserts the specified element at the tail of this queue, waiting
333 * up to the specified wait time for space to become available if
336 * @throws InterruptedException {@inheritDoc}
337 * @throws NullPointerException {@inheritDoc}
339 public boolean offer(E e, long timeout, TimeUnit unit)
340 throws InterruptedException {
343 long nanos = unit.toNanos(timeout);
344 final ReentrantLock lock = this.lock;
345 lock.lockInterruptibly();
347 while (count == items.length) {
350 nanos = notFull.awaitNanos(nanos);
360 final ReentrantLock lock = this.lock;
363 return (count == 0) ? null : extract();
369 public E take() throws InterruptedException {
370 final ReentrantLock lock = this.lock;
371 lock.lockInterruptibly();
381 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
382 long nanos = unit.toNanos(timeout);
383 final ReentrantLock lock = this.lock;
384 lock.lockInterruptibly();
389 nanos = notEmpty.awaitNanos(nanos);
398 final ReentrantLock lock = this.lock;
401 return (count == 0) ? null : itemAt(takeIndex);
407 // this doc comment is overridden to remove the reference to collections
408 // greater in size than Integer.MAX_VALUE
410 * Returns the number of elements in this queue.
412 * @return the number of elements in this queue
415 final ReentrantLock lock = this.lock;
424 // this doc comment is a modified copy of the inherited doc comment,
425 // without the reference to unlimited queues.
427 * Returns the number of additional elements that this queue can ideally
428 * (in the absence of memory or resource constraints) accept without
429 * blocking. This is always equal to the initial capacity of this queue
430 * less the current {@code size} of this queue.
432 * <p>Note that you <em>cannot</em> always tell if an attempt to insert
433 * an element will succeed by inspecting {@code remainingCapacity}
434 * because it may be the case that another thread is about to
435 * insert or remove an element.
437 public int remainingCapacity() {
438 final ReentrantLock lock = this.lock;
441 return items.length - count;
448 * Removes a single instance of the specified element from this queue,
449 * if it is present. More formally, removes an element {@code e} such
450 * that {@code o.equals(e)}, if this queue contains one or more such
452 * Returns {@code true} if this queue contained the specified element
453 * (or equivalently, if this queue changed as a result of the call).
455 * <p>Removal of interior elements in circular array based queues
456 * is an intrinsically slow and disruptive operation, so should
457 * be undertaken only in exceptional circumstances, ideally
458 * only when the queue is known not to be accessible by other
461 * @param o element to be removed from this queue, if present
462 * @return {@code true} if this queue changed as a result of the call
464 public boolean remove(Object o) {
465 if (o == null) return false;
466 final Object[] items = this.items;
467 final ReentrantLock lock = this.lock;
470 for (int i = takeIndex, k = count; k > 0; i = inc(i), k--) {
471 if (o.equals(items[i])) {
483 * Returns {@code true} if this queue contains the specified element.
484 * More formally, returns {@code true} if and only if this queue contains
485 * at least one element {@code e} such that {@code o.equals(e)}.
487 * @param o object to be checked for containment in this queue
488 * @return {@code true} if this queue contains the specified element
490 public boolean contains(Object o) {
491 if (o == null) return false;
492 final Object[] items = this.items;
493 final ReentrantLock lock = this.lock;
496 for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
497 if (o.equals(items[i]))
506 * Returns an array containing all of the elements in this queue, in
509 * <p>The returned array will be "safe" in that no references to it are
510 * maintained by this queue. (In other words, this method must allocate
511 * a new array). The caller is thus free to modify the returned array.
513 * <p>This method acts as bridge between array-based and collection-based
516 * @return an array containing all of the elements in this queue
518 public Object[] toArray() {
519 final Object[] items = this.items;
520 final ReentrantLock lock = this.lock;
523 final int count = this.count;
524 Object[] a = new Object[count];
525 for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
534 * Returns an array containing all of the elements in this queue, in
535 * proper sequence; the runtime type of the returned array is that of
536 * the specified array. If the queue fits in the specified array, it
537 * is returned therein. Otherwise, a new array is allocated with the
538 * runtime type of the specified array and the size of this queue.
540 * <p>If this queue fits in the specified array with room to spare
541 * (i.e., the array has more elements than this queue), the element in
542 * the array immediately following the end of the queue is set to
545 * <p>Like the {@link #toArray()} method, this method acts as bridge between
546 * array-based and collection-based APIs. Further, this method allows
547 * precise control over the runtime type of the output array, and may,
548 * under certain circumstances, be used to save allocation costs.
550 * <p>Suppose {@code x} is a queue known to contain only strings.
551 * The following code can be used to dump the queue into a newly
552 * allocated array of {@code String}:
555 * String[] y = x.toArray(new String[0]);</pre>
557 * Note that {@code toArray(new Object[0])} is identical in function to
560 * @param a the array into which the elements of the queue are to
561 * be stored, if it is big enough; otherwise, a new array of the
562 * same runtime type is allocated for this purpose
563 * @return an array containing all of the elements in this queue
564 * @throws ArrayStoreException if the runtime type of the specified array
565 * is not a supertype of the runtime type of every element in
567 * @throws NullPointerException if the specified array is null
569 @SuppressWarnings("unchecked")
570 public <T> T[] toArray(T[] a) {
571 final Object[] items = this.items;
572 final ReentrantLock lock = this.lock;
575 final int count = this.count;
576 final int len = a.length;
578 a = (T[])java.lang.reflect.Array.newInstance(
579 a.getClass().getComponentType(), count);
580 for (int i = takeIndex, k = 0; k < count; i = inc(i), k++)
590 public String toString() {
591 final ReentrantLock lock = this.lock;
598 StringBuilder sb = new StringBuilder();
600 for (int i = takeIndex; ; i = inc(i)) {
602 sb.append(e == this ? "(this Collection)" : e);
604 return sb.append(']').toString();
605 sb.append(',').append(' ');
613 * Atomically removes all of the elements from this queue.
614 * The queue will be empty after this call returns.
616 public void clear() {
617 final Object[] items = this.items;
618 final ReentrantLock lock = this.lock;
621 for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
633 * @throws UnsupportedOperationException {@inheritDoc}
634 * @throws ClassCastException {@inheritDoc}
635 * @throws NullPointerException {@inheritDoc}
636 * @throws IllegalArgumentException {@inheritDoc}
638 public int drainTo(Collection<? super E> c) {
641 throw new IllegalArgumentException();
642 final Object[] items = this.items;
643 final ReentrantLock lock = this.lock;
650 c.add(this.<E>cast(items[i]));
668 * @throws UnsupportedOperationException {@inheritDoc}
669 * @throws ClassCastException {@inheritDoc}
670 * @throws NullPointerException {@inheritDoc}
671 * @throws IllegalArgumentException {@inheritDoc}
673 public int drainTo(Collection<? super E> c, int maxElements) {
676 throw new IllegalArgumentException();
677 if (maxElements <= 0)
679 final Object[] items = this.items;
680 final ReentrantLock lock = this.lock;
685 int max = (maxElements < count) ? maxElements : count;
687 c.add(this.<E>cast(items[i]));
704 * Returns an iterator over the elements in this queue in proper sequence.
705 * The elements will be returned in order from first (head) to last (tail).
707 * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
708 * will never throw {@link java.util.ConcurrentModificationException
709 * ConcurrentModificationException},
710 * and guarantees to traverse elements as they existed upon
711 * construction of the iterator, and may (but is not guaranteed to)
712 * reflect any modifications subsequent to construction.
714 * @return an iterator over the elements in this queue in proper sequence
716 public Iterator<E> iterator() {
721 * Iterator for ArrayBlockingQueue. To maintain weak consistency
722 * with respect to puts and takes, we (1) read ahead one slot, so
723 * as to not report hasNext true but then not have an element to
724 * return -- however we later recheck this slot to use the most
725 * current value; (2) ensure that each array slot is traversed at
726 * most once (by tracking "remaining" elements); (3) skip over
727 * null slots, which can occur if takes race ahead of iterators.
728 * However, for circular array-based queues, we cannot rely on any
729 * well established definition of what it means to be weakly
730 * consistent with respect to interior removes since these may
731 * require slot overwrites in the process of sliding elements to
732 * cover gaps. So we settle for resiliency, operating on
733 * established apparent nexts, which may miss some elements that
734 * have moved between calls to next.
736 private class Itr implements Iterator<E> {
737 private int remaining; // Number of elements yet to be returned
738 private int nextIndex; // Index of element to be returned by next
739 private E nextItem; // Element to be returned by next call to next
740 private E lastItem; // Element returned by last call to next
741 private int lastRet; // Index of last element returned, or -1 if none
744 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
748 if ((remaining = count) > 0)
749 nextItem = itemAt(nextIndex = takeIndex);
755 public boolean hasNext() {
756 return remaining > 0;
760 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
764 throw new NoSuchElementException();
766 E x = itemAt(nextIndex); // check for fresher value
768 x = nextItem; // we are forced to report old value
769 lastItem = null; // but ensure remove fails
773 while (--remaining > 0 && // skip over nulls
774 (nextItem = itemAt(nextIndex = inc(nextIndex))) == null)
782 public void remove() {
783 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
788 throw new IllegalStateException();
792 // only remove if item still at index
793 if (x != null && x == items[i]) {
794 boolean removingHead = (i == takeIndex);
797 nextIndex = dec(nextIndex);