ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.100
Committed: Sun Feb 17 23:36:34 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.99: +51 -21 lines
Log Message:
Spliterator sync

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.38 * Expert Group and released to the public domain, as explained at
4 jsr166 1.78 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 jsr166 1.85 import java.util.concurrent.locks.Condition;
9     import java.util.concurrent.locks.ReentrantLock;
10     import java.util.AbstractQueue;
11     import java.util.Collection;
12 dl 1.100 import java.util.Collections;
13 jsr166 1.85 import java.util.Iterator;
14     import java.util.NoSuchElementException;
15 jsr166 1.89 import java.lang.ref.WeakReference;
16 dl 1.100 import java.util.Spliterator;
17     import java.util.stream.Stream;
18     import java.util.stream.Streams;
19     import java.util.function.Consumer;
20 tim 1.1
21     /**
22 dl 1.25 * A bounded {@linkplain BlockingQueue blocking queue} backed by an
23     * array. This queue orders elements FIFO (first-in-first-out). The
24     * <em>head</em> of the queue is that element that has been on the
25     * queue the longest time. The <em>tail</em> of the queue is that
26     * element that has been on the queue the shortest time. New elements
27     * are inserted at the tail of the queue, and the queue retrieval
28     * operations obtain elements at the head of the queue.
29 dholmes 1.13 *
30 dl 1.40 * <p>This is a classic &quot;bounded buffer&quot;, in which a
31     * fixed-sized array holds elements inserted by producers and
32     * extracted by consumers. Once created, the capacity cannot be
33 jsr166 1.69 * changed. Attempts to {@code put} an element into a full queue
34     * will result in the operation blocking; attempts to {@code take} an
35 dl 1.40 * element from an empty queue will similarly block.
36 dl 1.11 *
37 jsr166 1.72 * <p>This class supports an optional fairness policy for ordering
38 dl 1.42 * waiting producer and consumer threads. By default, this ordering
39     * is not guaranteed. However, a queue constructed with fairness set
40 jsr166 1.69 * to {@code true} grants threads access in FIFO order. Fairness
41 dl 1.42 * generally decreases throughput but reduces variability and avoids
42     * starvation.
43 brian 1.7 *
44 dl 1.43 * <p>This class and its iterator implement all of the
45     * <em>optional</em> methods of the {@link Collection} and {@link
46 jsr166 1.47 * Iterator} interfaces.
47 dl 1.26 *
48 dl 1.41 * <p>This class is a member of the
49 jsr166 1.54 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
50 dl 1.41 * Java Collections Framework</a>.
51     *
52 dl 1.8 * @since 1.5
53     * @author Doug Lea
54 dl 1.33 * @param <E> the type of elements held in this collection
55 dl 1.8 */
56 dl 1.5 public class ArrayBlockingQueue<E> extends AbstractQueue<E>
57 tim 1.1 implements BlockingQueue<E>, java.io.Serializable {
58    
59 dl 1.36 /**
60 dl 1.42 * Serialization ID. This class relies on default serialization
61     * even for the items array, which is default-serialized, even if
62     * it is empty. Otherwise it could not be declared final, which is
63 dl 1.36 * necessary here.
64     */
65     private static final long serialVersionUID = -817911632652898426L;
66    
67 jsr166 1.73 /** The queued items */
68 jsr166 1.68 final Object[] items;
69 jsr166 1.73
70     /** items index for next take, poll, peek or remove */
71 jsr166 1.58 int takeIndex;
72 jsr166 1.73
73     /** items index for next put, offer, or add */
74 jsr166 1.58 int putIndex;
75 jsr166 1.73
76     /** Number of elements in the queue */
77 jsr166 1.59 int count;
78 tim 1.12
79 dl 1.5 /*
80 dl 1.36 * Concurrency control uses the classic two-condition algorithm
81 dl 1.5 * found in any textbook.
82     */
83    
84 dl 1.11 /** Main lock guarding all access */
85 jsr166 1.58 final ReentrantLock lock;
86 jsr166 1.85
87 dholmes 1.13 /** Condition for waiting takes */
88 dl 1.37 private final Condition notEmpty;
89 jsr166 1.85
90 dl 1.35 /** Condition for waiting puts */
91 dl 1.37 private final Condition notFull;
92 dl 1.5
93 jsr166 1.89 /**
94     * Shared state for currently active iterators, or null if there
95     * are known not to be any. Allows queue operations to update
96     * iterator state.
97     */
98     transient Itrs itrs = null;
99    
100 dl 1.5 // Internal helper methods
101    
102     /**
103 jsr166 1.71 * Circularly decrement i.
104     */
105     final int dec(int i) {
106     return ((i == 0) ? items.length : i) - 1;
107     }
108    
109 jsr166 1.68 /**
110     * Returns item at index i.
111     */
112 jsr166 1.96 @SuppressWarnings("unchecked")
113 jsr166 1.68 final E itemAt(int i) {
114 jsr166 1.96 return (E) items[i];
115 jsr166 1.68 }
116    
117     /**
118     * Throws NullPointerException if argument is null.
119     *
120     * @param v the element
121     */
122     private static void checkNotNull(Object v) {
123     if (v == null)
124     throw new NullPointerException();
125     }
126    
127 dl 1.5 /**
128 jsr166 1.47 * Inserts element at current put position, advances, and signals.
129 dl 1.9 * Call only when holding lock.
130 dl 1.5 */
131 jsr166 1.88 private void enqueue(E x) {
132 jsr166 1.95 // assert lock.getHoldCount() == 1;
133     // assert items[putIndex] == null;
134 dl 1.100 final Object[] items = this.items;
135 dl 1.5 items[putIndex] = x;
136 dl 1.100 if (++putIndex == items.length)
137     putIndex = 0;
138 jsr166 1.89 count++;
139 dl 1.9 notEmpty.signal();
140 tim 1.1 }
141 tim 1.12
142 dl 1.5 /**
143 jsr166 1.47 * Extracts element at current take position, advances, and signals.
144 dl 1.9 * Call only when holding lock.
145 dl 1.5 */
146 jsr166 1.88 private E dequeue() {
147 jsr166 1.95 // assert lock.getHoldCount() == 1;
148     // assert items[takeIndex] != null;
149 jsr166 1.68 final Object[] items = this.items;
150 jsr166 1.97 @SuppressWarnings("unchecked")
151     E x = (E) items[takeIndex];
152 dl 1.5 items[takeIndex] = null;
153 dl 1.100 if (++takeIndex == items.length)
154     takeIndex = 0;
155 jsr166 1.89 count--;
156     if (itrs != null)
157     itrs.elementDequeued();
158 dl 1.9 notFull.signal();
159 dl 1.5 return x;
160     }
161    
162     /**
163 jsr166 1.90 * Deletes item at array index removeIndex.
164 jsr166 1.89 * Utility for remove(Object) and iterator.remove.
165 dl 1.9 * Call only when holding lock.
166 dl 1.5 */
167 jsr166 1.90 void removeAt(final int removeIndex) {
168 jsr166 1.95 // assert lock.getHoldCount() == 1;
169     // assert items[removeIndex] != null;
170     // assert removeIndex >= 0 && removeIndex < items.length;
171 jsr166 1.68 final Object[] items = this.items;
172 jsr166 1.90 if (removeIndex == takeIndex) {
173 jsr166 1.89 // removing front item; just advance
174 dl 1.9 items[takeIndex] = null;
175 dl 1.100 if (++takeIndex == items.length)
176     takeIndex = 0;
177 jsr166 1.90 count--;
178 jsr166 1.89 if (itrs != null)
179     itrs.elementDequeued();
180 tim 1.23 } else {
181 jsr166 1.89 // an "interior" remove
182 jsr166 1.90
183 dl 1.9 // slide over all others up through putIndex.
184 jsr166 1.90 final int putIndex = this.putIndex;
185     for (int i = removeIndex;;) {
186 dl 1.100 int next = i + 1;
187     if (next == items.length)
188     next = 0;
189 jsr166 1.90 if (next != putIndex) {
190     items[i] = items[next];
191     i = next;
192 tim 1.23 } else {
193 dl 1.9 items[i] = null;
194 jsr166 1.90 this.putIndex = i;
195 dl 1.9 break;
196     }
197 dl 1.5 }
198 jsr166 1.90 count--;
199     if (itrs != null)
200     itrs.removedAt(removeIndex);
201 dl 1.5 }
202 dl 1.9 notFull.signal();
203 tim 1.1 }
204    
205     /**
206 jsr166 1.69 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
207 dholmes 1.13 * capacity and default access policy.
208 jsr166 1.50 *
209 dholmes 1.13 * @param capacity the capacity of this queue
210 jsr166 1.69 * @throws IllegalArgumentException if {@code capacity < 1}
211 dl 1.5 */
212 dholmes 1.13 public ArrayBlockingQueue(int capacity) {
213 dl 1.36 this(capacity, false);
214 dl 1.5 }
215 dl 1.2
216 dl 1.5 /**
217 jsr166 1.69 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
218 dholmes 1.13 * capacity and the specified access policy.
219 jsr166 1.50 *
220 dholmes 1.13 * @param capacity the capacity of this queue
221 jsr166 1.69 * @param fair if {@code true} then queue accesses for threads blocked
222 jsr166 1.50 * on insertion or removal, are processed in FIFO order;
223 jsr166 1.69 * if {@code false} the access order is unspecified.
224     * @throws IllegalArgumentException if {@code capacity < 1}
225 dl 1.11 */
226 dholmes 1.13 public ArrayBlockingQueue(int capacity, boolean fair) {
227 dl 1.36 if (capacity <= 0)
228     throw new IllegalArgumentException();
229 jsr166 1.68 this.items = new Object[capacity];
230 dl 1.36 lock = new ReentrantLock(fair);
231     notEmpty = lock.newCondition();
232     notFull = lock.newCondition();
233 dl 1.5 }
234    
235 dholmes 1.16 /**
236 jsr166 1.69 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
237 dholmes 1.21 * capacity, the specified access policy and initially containing the
238 tim 1.17 * elements of the given collection,
239 dholmes 1.16 * added in traversal order of the collection's iterator.
240 jsr166 1.50 *
241 dholmes 1.16 * @param capacity the capacity of this queue
242 jsr166 1.69 * @param fair if {@code true} then queue accesses for threads blocked
243 jsr166 1.50 * on insertion or removal, are processed in FIFO order;
244 jsr166 1.69 * if {@code false} the access order is unspecified.
245 dholmes 1.16 * @param c the collection of elements to initially contain
246 jsr166 1.69 * @throws IllegalArgumentException if {@code capacity} is less than
247     * {@code c.size()}, or less than 1.
248 jsr166 1.50 * @throws NullPointerException if the specified collection or any
249     * of its elements are null
250 dholmes 1.16 */
251 tim 1.20 public ArrayBlockingQueue(int capacity, boolean fair,
252 dholmes 1.18 Collection<? extends E> c) {
253 dl 1.36 this(capacity, fair);
254 dholmes 1.16
255 jsr166 1.68 final ReentrantLock lock = this.lock;
256     lock.lock(); // Lock only for visibility, not mutual exclusion
257     try {
258     int i = 0;
259     try {
260     for (E e : c) {
261     checkNotNull(e);
262     items[i++] = e;
263     }
264     } catch (ArrayIndexOutOfBoundsException ex) {
265     throw new IllegalArgumentException();
266     }
267     count = i;
268     putIndex = (i == capacity) ? 0 : i;
269     } finally {
270     lock.unlock();
271     }
272 dholmes 1.16 }
273 dl 1.2
274 dholmes 1.13 /**
275 jsr166 1.50 * Inserts the specified element at the tail of this queue if it is
276     * possible to do so immediately without exceeding the queue's capacity,
277 jsr166 1.69 * returning {@code true} upon success and throwing an
278     * {@code IllegalStateException} if this queue is full.
279 dl 1.25 *
280 jsr166 1.50 * @param e the element to add
281 jsr166 1.69 * @return {@code true} (as specified by {@link Collection#add})
282 jsr166 1.50 * @throws IllegalStateException if this queue is full
283     * @throws NullPointerException if the specified element is null
284     */
285     public boolean add(E e) {
286 jsr166 1.56 return super.add(e);
287 jsr166 1.50 }
288    
289     /**
290     * Inserts the specified element at the tail of this queue if it is
291     * possible to do so immediately without exceeding the queue's capacity,
292 jsr166 1.69 * returning {@code true} upon success and {@code false} if this queue
293 jsr166 1.50 * is full. This method is generally preferable to method {@link #add},
294     * which can fail to insert an element only by throwing an exception.
295     *
296     * @throws NullPointerException if the specified element is null
297 dholmes 1.13 */
298 jsr166 1.49 public boolean offer(E e) {
299 jsr166 1.68 checkNotNull(e);
300 dl 1.36 final ReentrantLock lock = this.lock;
301 dl 1.5 lock.lock();
302     try {
303 jsr166 1.59 if (count == items.length)
304 dl 1.2 return false;
305 dl 1.5 else {
306 jsr166 1.88 enqueue(e);
307 dl 1.5 return true;
308     }
309 tim 1.23 } finally {
310 tim 1.12 lock.unlock();
311 dl 1.2 }
312 dl 1.5 }
313 dl 1.2
314 dholmes 1.13 /**
315 jsr166 1.50 * Inserts the specified element at the tail of this queue, waiting
316     * for space to become available if the queue is full.
317     *
318     * @throws InterruptedException {@inheritDoc}
319     * @throws NullPointerException {@inheritDoc}
320     */
321     public void put(E e) throws InterruptedException {
322 jsr166 1.68 checkNotNull(e);
323 jsr166 1.50 final ReentrantLock lock = this.lock;
324     lock.lockInterruptibly();
325     try {
326 jsr166 1.59 while (count == items.length)
327 jsr166 1.58 notFull.await();
328 jsr166 1.88 enqueue(e);
329 jsr166 1.50 } finally {
330     lock.unlock();
331     }
332     }
333    
334     /**
335     * Inserts the specified element at the tail of this queue, waiting
336     * up to the specified wait time for space to become available if
337     * the queue is full.
338     *
339     * @throws InterruptedException {@inheritDoc}
340     * @throws NullPointerException {@inheritDoc}
341 brian 1.7 */
342 jsr166 1.49 public boolean offer(E e, long timeout, TimeUnit unit)
343 dholmes 1.13 throws InterruptedException {
344 dl 1.2
345 jsr166 1.68 checkNotNull(e);
346 jsr166 1.56 long nanos = unit.toNanos(timeout);
347 dl 1.36 final ReentrantLock lock = this.lock;
348 dl 1.5 lock.lockInterruptibly();
349     try {
350 jsr166 1.59 while (count == items.length) {
351 dl 1.5 if (nanos <= 0)
352     return false;
353 jsr166 1.58 nanos = notFull.awaitNanos(nanos);
354 dl 1.5 }
355 jsr166 1.88 enqueue(e);
356 jsr166 1.58 return true;
357 tim 1.23 } finally {
358 dl 1.5 lock.unlock();
359 dl 1.2 }
360 dl 1.5 }
361 dl 1.2
362 dholmes 1.13 public E poll() {
363 dl 1.36 final ReentrantLock lock = this.lock;
364 dholmes 1.13 lock.lock();
365     try {
366 jsr166 1.88 return (count == 0) ? null : dequeue();
367 tim 1.23 } finally {
368 tim 1.15 lock.unlock();
369 dholmes 1.13 }
370     }
371    
372 jsr166 1.50 public E take() throws InterruptedException {
373     final ReentrantLock lock = this.lock;
374     lock.lockInterruptibly();
375     try {
376 jsr166 1.59 while (count == 0)
377 jsr166 1.58 notEmpty.await();
378 jsr166 1.88 return dequeue();
379 jsr166 1.50 } finally {
380     lock.unlock();
381     }
382     }
383    
384 dl 1.5 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
385 jsr166 1.56 long nanos = unit.toNanos(timeout);
386 dl 1.36 final ReentrantLock lock = this.lock;
387 dl 1.5 lock.lockInterruptibly();
388     try {
389 jsr166 1.59 while (count == 0) {
390 dl 1.5 if (nanos <= 0)
391     return null;
392 jsr166 1.58 nanos = notEmpty.awaitNanos(nanos);
393 dl 1.2 }
394 jsr166 1.88 return dequeue();
395 tim 1.23 } finally {
396 dl 1.5 lock.unlock();
397     }
398     }
399 dl 1.2
400 dholmes 1.13 public E peek() {
401 dl 1.36 final ReentrantLock lock = this.lock;
402 dholmes 1.13 lock.lock();
403     try {
404 jsr166 1.99 return itemAt(takeIndex); // null when queue is empty
405 tim 1.23 } finally {
406 dholmes 1.13 lock.unlock();
407     }
408     }
409    
410     // this doc comment is overridden to remove the reference to collections
411     // greater in size than Integer.MAX_VALUE
412 tim 1.15 /**
413 dl 1.25 * Returns the number of elements in this queue.
414     *
415 jsr166 1.50 * @return the number of elements in this queue
416 dholmes 1.13 */
417     public int size() {
418 dl 1.36 final ReentrantLock lock = this.lock;
419 dholmes 1.13 lock.lock();
420     try {
421     return count;
422 tim 1.23 } finally {
423 dholmes 1.13 lock.unlock();
424     }
425     }
426    
427     // this doc comment is a modified copy of the inherited doc comment,
428     // without the reference to unlimited queues.
429 tim 1.15 /**
430 jsr166 1.48 * Returns the number of additional elements that this queue can ideally
431     * (in the absence of memory or resource constraints) accept without
432 dholmes 1.13 * blocking. This is always equal to the initial capacity of this queue
433 jsr166 1.69 * less the current {@code size} of this queue.
434 jsr166 1.48 *
435     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
436 jsr166 1.69 * an element will succeed by inspecting {@code remainingCapacity}
437 jsr166 1.48 * because it may be the case that another thread is about to
438 jsr166 1.50 * insert or remove an element.
439 dholmes 1.13 */
440     public int remainingCapacity() {
441 dl 1.36 final ReentrantLock lock = this.lock;
442 dholmes 1.13 lock.lock();
443     try {
444     return items.length - count;
445 tim 1.23 } finally {
446 dholmes 1.13 lock.unlock();
447     }
448     }
449    
450 jsr166 1.50 /**
451     * Removes a single instance of the specified element from this queue,
452 jsr166 1.69 * if it is present. More formally, removes an element {@code e} such
453     * that {@code o.equals(e)}, if this queue contains one or more such
454 jsr166 1.50 * elements.
455 jsr166 1.69 * Returns {@code true} if this queue contained the specified element
456 jsr166 1.50 * (or equivalently, if this queue changed as a result of the call).
457     *
458 jsr166 1.64 * <p>Removal of interior elements in circular array based queues
459 dl 1.60 * is an intrinsically slow and disruptive operation, so should
460     * be undertaken only in exceptional circumstances, ideally
461     * only when the queue is known not to be accessible by other
462     * threads.
463     *
464 jsr166 1.50 * @param o element to be removed from this queue, if present
465 jsr166 1.69 * @return {@code true} if this queue changed as a result of the call
466 jsr166 1.50 */
467     public boolean remove(Object o) {
468     if (o == null) return false;
469 jsr166 1.68 final Object[] items = this.items;
470 jsr166 1.50 final ReentrantLock lock = this.lock;
471     lock.lock();
472     try {
473 jsr166 1.86 if (count > 0) {
474     final int putIndex = this.putIndex;
475     int i = takeIndex;
476     do {
477     if (o.equals(items[i])) {
478     removeAt(i);
479     return true;
480     }
481 dl 1.100 if (++i == items.length)
482     i = 0;
483     } while (i != putIndex);
484 jsr166 1.50 }
485 jsr166 1.68 return false;
486 jsr166 1.50 } finally {
487     lock.unlock();
488     }
489     }
490 dholmes 1.13
491 jsr166 1.50 /**
492 jsr166 1.69 * Returns {@code true} if this queue contains the specified element.
493     * More formally, returns {@code true} if and only if this queue contains
494     * at least one element {@code e} such that {@code o.equals(e)}.
495 jsr166 1.50 *
496     * @param o object to be checked for containment in this queue
497 jsr166 1.69 * @return {@code true} if this queue contains the specified element
498 jsr166 1.50 */
499 dholmes 1.21 public boolean contains(Object o) {
500     if (o == null) return false;
501 jsr166 1.68 final Object[] items = this.items;
502 dl 1.36 final ReentrantLock lock = this.lock;
503 dl 1.5 lock.lock();
504     try {
505 jsr166 1.86 if (count > 0) {
506     final int putIndex = this.putIndex;
507     int i = takeIndex;
508     do {
509     if (o.equals(items[i]))
510     return true;
511 dl 1.100 if (++i == items.length)
512     i = 0;
513     } while (i != putIndex);
514 jsr166 1.86 }
515 dl 1.2 return false;
516 tim 1.23 } finally {
517 dl 1.5 lock.unlock();
518     }
519     }
520 brian 1.7
521 jsr166 1.50 /**
522     * Returns an array containing all of the elements in this queue, in
523     * proper sequence.
524     *
525     * <p>The returned array will be "safe" in that no references to it are
526     * maintained by this queue. (In other words, this method must allocate
527     * a new array). The caller is thus free to modify the returned array.
528 jsr166 1.51 *
529 jsr166 1.50 * <p>This method acts as bridge between array-based and collection-based
530     * APIs.
531     *
532     * @return an array containing all of the elements in this queue
533     */
534 dl 1.5 public Object[] toArray() {
535 dl 1.100 Object[] a;
536 dl 1.36 final ReentrantLock lock = this.lock;
537 dl 1.5 lock.lock();
538     try {
539 jsr166 1.68 final int count = this.count;
540 dl 1.100 a = new Object[count];
541 jsr166 1.98 int n = items.length - takeIndex;
542     if (count <= n)
543     System.arraycopy(items, takeIndex, a, 0, count);
544     else {
545     System.arraycopy(items, takeIndex, a, 0, n);
546     System.arraycopy(items, 0, a, n, count - n);
547     }
548 tim 1.23 } finally {
549 dl 1.5 lock.unlock();
550     }
551 dl 1.100 return a;
552 dl 1.5 }
553 brian 1.7
554 jsr166 1.50 /**
555     * Returns an array containing all of the elements in this queue, in
556     * proper sequence; the runtime type of the returned array is that of
557     * the specified array. If the queue fits in the specified array, it
558     * is returned therein. Otherwise, a new array is allocated with the
559     * runtime type of the specified array and the size of this queue.
560     *
561     * <p>If this queue fits in the specified array with room to spare
562     * (i.e., the array has more elements than this queue), the element in
563     * the array immediately following the end of the queue is set to
564 jsr166 1.69 * {@code null}.
565 jsr166 1.50 *
566     * <p>Like the {@link #toArray()} method, this method acts as bridge between
567     * array-based and collection-based APIs. Further, this method allows
568     * precise control over the runtime type of the output array, and may,
569     * under certain circumstances, be used to save allocation costs.
570     *
571 jsr166 1.69 * <p>Suppose {@code x} is a queue known to contain only strings.
572 jsr166 1.50 * The following code can be used to dump the queue into a newly
573 jsr166 1.69 * allocated array of {@code String}:
574 jsr166 1.50 *
575 jsr166 1.80 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
576 jsr166 1.50 *
577 jsr166 1.69 * Note that {@code toArray(new Object[0])} is identical in function to
578     * {@code toArray()}.
579 jsr166 1.50 *
580     * @param a the array into which the elements of the queue are to
581     * be stored, if it is big enough; otherwise, a new array of the
582     * same runtime type is allocated for this purpose
583     * @return an array containing all of the elements in this queue
584     * @throws ArrayStoreException if the runtime type of the specified array
585     * is not a supertype of the runtime type of every element in
586     * this queue
587     * @throws NullPointerException if the specified array is null
588     */
589 jsr166 1.68 @SuppressWarnings("unchecked")
590 dl 1.5 public <T> T[] toArray(T[] a) {
591 jsr166 1.68 final Object[] items = this.items;
592 dl 1.36 final ReentrantLock lock = this.lock;
593 dl 1.5 lock.lock();
594     try {
595 jsr166 1.68 final int count = this.count;
596     final int len = a.length;
597     if (len < count)
598 dholmes 1.16 a = (T[])java.lang.reflect.Array.newInstance(
599 jsr166 1.68 a.getClass().getComponentType(), count);
600 jsr166 1.98 int n = items.length - takeIndex;
601     if (count <= n)
602     System.arraycopy(items, takeIndex, a, 0, count);
603     else {
604     System.arraycopy(items, takeIndex, a, 0, n);
605     System.arraycopy(items, 0, a, n, count - n);
606     }
607 jsr166 1.68 if (len > count)
608 dl 1.5 a[count] = null;
609 tim 1.23 } finally {
610 dl 1.5 lock.unlock();
611     }
612 dl 1.100 return a;
613 dl 1.5 }
614 dl 1.6
615     public String toString() {
616 dl 1.36 final ReentrantLock lock = this.lock;
617 dl 1.6 lock.lock();
618     try {
619 jsr166 1.68 int k = count;
620     if (k == 0)
621     return "[]";
622    
623 dl 1.100 final Object[] items = this.items;
624 jsr166 1.68 StringBuilder sb = new StringBuilder();
625     sb.append('[');
626 dl 1.100 for (int i = takeIndex; ; ) {
627 jsr166 1.68 Object e = items[i];
628     sb.append(e == this ? "(this Collection)" : e);
629     if (--k == 0)
630     return sb.append(']').toString();
631     sb.append(',').append(' ');
632 dl 1.100 if (++i == items.length)
633     i = 0;
634 jsr166 1.68 }
635 tim 1.23 } finally {
636 dl 1.6 lock.unlock();
637     }
638     }
639 tim 1.12
640 dl 1.44 /**
641     * Atomically removes all of the elements from this queue.
642     * The queue will be empty after this call returns.
643     */
644 dl 1.30 public void clear() {
645 jsr166 1.68 final Object[] items = this.items;
646 dl 1.36 final ReentrantLock lock = this.lock;
647 dl 1.30 lock.lock();
648     try {
649 jsr166 1.86 int k = count;
650     if (k > 0) {
651     final int putIndex = this.putIndex;
652     int i = takeIndex;
653     do {
654     items[i] = null;
655 dl 1.100 if (++i == items.length)
656     i = 0;
657     } while (i != putIndex);
658 jsr166 1.86 takeIndex = putIndex;
659     count = 0;
660 jsr166 1.89 if (itrs != null)
661     itrs.queueIsEmpty();
662 jsr166 1.86 for (; k > 0 && lock.hasWaiters(notFull); k--)
663     notFull.signal();
664     }
665 dl 1.30 } finally {
666     lock.unlock();
667     }
668     }
669    
670 jsr166 1.50 /**
671     * @throws UnsupportedOperationException {@inheritDoc}
672     * @throws ClassCastException {@inheritDoc}
673     * @throws NullPointerException {@inheritDoc}
674     * @throws IllegalArgumentException {@inheritDoc}
675     */
676 dl 1.30 public int drainTo(Collection<? super E> c) {
677 jsr166 1.81 return drainTo(c, Integer.MAX_VALUE);
678 dl 1.30 }
679    
680 jsr166 1.50 /**
681     * @throws UnsupportedOperationException {@inheritDoc}
682     * @throws ClassCastException {@inheritDoc}
683     * @throws NullPointerException {@inheritDoc}
684     * @throws IllegalArgumentException {@inheritDoc}
685     */
686 dl 1.30 public int drainTo(Collection<? super E> c, int maxElements) {
687 jsr166 1.68 checkNotNull(c);
688 dl 1.30 if (c == this)
689     throw new IllegalArgumentException();
690     if (maxElements <= 0)
691     return 0;
692 jsr166 1.68 final Object[] items = this.items;
693 dl 1.36 final ReentrantLock lock = this.lock;
694 dl 1.30 lock.lock();
695     try {
696 jsr166 1.82 int n = Math.min(maxElements, count);
697     int take = takeIndex;
698     int i = 0;
699     try {
700     while (i < n) {
701 jsr166 1.97 @SuppressWarnings("unchecked")
702     E x = (E) items[take];
703 jsr166 1.84 c.add(x);
704 jsr166 1.82 items[take] = null;
705 dl 1.100 if (++take == items.length)
706     take = 0;
707 jsr166 1.86 i++;
708 jsr166 1.82 }
709     return n;
710     } finally {
711     // Restore invariants even if c.add() threw
712 jsr166 1.89 if (i > 0) {
713     count -= i;
714     takeIndex = take;
715     if (itrs != null) {
716     if (count == 0)
717     itrs.queueIsEmpty();
718     else if (i > take)
719     itrs.takeIndexWrapped();
720     }
721     for (; i > 0 && lock.hasWaiters(notFull); i--)
722     notFull.signal();
723     }
724 dl 1.30 }
725     } finally {
726     lock.unlock();
727     }
728     }
729    
730 brian 1.7 /**
731 dl 1.75 * Returns an iterator over the elements in this queue in proper sequence.
732 jsr166 1.77 * The elements will be returned in order from first (head) to last (tail).
733     *
734 jsr166 1.87 * <p>The returned iterator is a "weakly consistent" iterator that
735 jsr166 1.77 * will never throw {@link java.util.ConcurrentModificationException
736 jsr166 1.87 * ConcurrentModificationException}, and guarantees to traverse
737     * elements as they existed upon construction of the iterator, and
738     * may (but is not guaranteed to) reflect any modifications
739     * subsequent to construction.
740 brian 1.7 *
741 jsr166 1.50 * @return an iterator over the elements in this queue in proper sequence
742 brian 1.7 */
743 dl 1.5 public Iterator<E> iterator() {
744 jsr166 1.68 return new Itr();
745 dl 1.5 }
746 dl 1.8
747     /**
748 jsr166 1.94 * Shared data between iterators and their queue, allowing queue
749 jsr166 1.89 * modifications to update iterators when elements are removed.
750     *
751 jsr166 1.94 * This adds a lot of complexity for the sake of correctly
752     * handling some uncommon operations, but the combination of
753     * circular-arrays and supporting interior removes (i.e., those
754     * not at head) would cause iterators to sometimes lose their
755     * places and/or (re)report elements they shouldn't. To avoid
756     * this, when a queue has one or more iterators, it keeps iterator
757     * state consistent by:
758     *
759     * (1) keeping track of the number of "cycles", that is, the
760     * number of times takeIndex has wrapped around to 0.
761     * (2) notifying all iterators via the callback removedAt whenever
762     * an interior element is removed (and thus other elements may
763     * be shifted).
764     *
765     * These suffice to eliminate iterator inconsistencies, but
766     * unfortunately add the secondary responsibility of maintaining
767     * the list of iterators. We track all active iterators in a
768     * simple linked list (accessed only when the queue's lock is
769     * held) of weak references to Itr. The list is cleaned up using
770     * 3 different mechanisms:
771 jsr166 1.89 *
772     * (1) Whenever a new iterator is created, do some O(1) checking for
773     * stale list elements.
774     *
775     * (2) Whenever takeIndex wraps around to 0, check for iterators
776     * that have been unused for more than one wrap-around cycle.
777     *
778     * (3) Whenever the queue becomes empty, all iterators are notified
779     * and this entire data structure is discarded.
780     *
781 jsr166 1.94 * So in addition to the removedAt callback that is necessary for
782     * correctness, iterators have the shutdown and takeIndexWrapped
783     * callbacks that help remove stale iterators from the list.
784     *
785     * Whenever a list element is examined, it is expunged if either
786     * the GC has determined that the iterator is discarded, or if the
787     * iterator reports that it is "detached" (does not need any
788     * further state updates). Overhead is maximal when takeIndex
789     * never advances, iterators are discarded before they are
790     * exhausted, and all removals are interior removes, in which case
791     * all stale iterators are discovered by the GC. But even in this
792     * case we don't increase the amortized complexity.
793     *
794     * Care must be taken to keep list sweeping methods from
795     * reentrantly invoking another such method, causing subtle
796     * corruption bugs.
797 jsr166 1.89 */
798     class Itrs {
799    
800     /**
801     * Node in a linked list of weak iterator references.
802     */
803     private class Node extends WeakReference<Itr> {
804     Node next;
805    
806     Node(Itr iterator, Node next) {
807     super(iterator);
808     this.next = next;
809     }
810     }
811    
812     /** Incremented whenever takeIndex wraps around to 0 */
813     int cycles = 0;
814    
815     /** Linked list of weak iterator references */
816 jsr166 1.93 private Node head;
817 jsr166 1.89
818     /** Used to expunge stale iterators */
819     private Node sweeper = null;
820    
821     private static final int SHORT_SWEEP_PROBES = 4;
822     private static final int LONG_SWEEP_PROBES = 16;
823    
824 jsr166 1.93 Itrs(Itr initial) {
825     register(initial);
826     }
827    
828 jsr166 1.89 /**
829     * Sweeps itrs, looking for and expunging stale iterators.
830     * If at least one was found, tries harder to find more.
831 jsr166 1.94 * Called only from iterating thread.
832 jsr166 1.89 *
833     * @param tryHarder whether to start in try-harder mode, because
834     * there is known to be at least one iterator to collect
835     */
836     void doSomeSweeping(boolean tryHarder) {
837 jsr166 1.95 // assert lock.getHoldCount() == 1;
838     // assert head != null;
839 jsr166 1.89 int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
840     Node o, p;
841     final Node sweeper = this.sweeper;
842 jsr166 1.93 boolean passedGo; // to limit search to one full sweep
843 jsr166 1.89
844 jsr166 1.93 if (sweeper == null) {
845     o = null;
846     p = head;
847     passedGo = true;
848     } else {
849 jsr166 1.89 o = sweeper;
850     p = o.next;
851 jsr166 1.93 passedGo = false;
852 jsr166 1.89 }
853    
854 jsr166 1.93 for (; probes > 0; probes--) {
855     if (p == null) {
856     if (passedGo)
857     break;
858     o = null;
859     p = head;
860     passedGo = true;
861     }
862 jsr166 1.89 final Itr it = p.get();
863     final Node next = p.next;
864     if (it == null || it.isDetached()) {
865     // found a discarded/exhausted iterator
866     probes = LONG_SWEEP_PROBES; // "try harder"
867     // unlink p
868     p.clear();
869     p.next = null;
870 jsr166 1.93 if (o == null) {
871 jsr166 1.89 head = next;
872 jsr166 1.93 if (next == null) {
873     // We've run out of iterators to track; retire
874     itrs = null;
875     return;
876     }
877     }
878 jsr166 1.89 else
879     o.next = next;
880     } else {
881     o = p;
882     }
883     p = next;
884     }
885    
886     this.sweeper = (p == null) ? null : o;
887     }
888    
889     /**
890     * Adds a new iterator to the linked list of tracked iterators.
891     */
892     void register(Itr itr) {
893 jsr166 1.95 // assert lock.getHoldCount() == 1;
894 jsr166 1.89 head = new Node(itr, head);
895     }
896    
897     /**
898     * Called whenever takeIndex wraps around to 0.
899     *
900     * Notifies all iterators, and expunges any that are now stale.
901     */
902     void takeIndexWrapped() {
903 jsr166 1.95 // assert lock.getHoldCount() == 1;
904 jsr166 1.89 cycles++;
905     for (Node o = null, p = head; p != null;) {
906     final Itr it = p.get();
907     final Node next = p.next;
908     if (it == null || it.takeIndexWrapped()) {
909     // unlink p
910 jsr166 1.95 // assert it == null || it.isDetached();
911 jsr166 1.89 p.clear();
912     p.next = null;
913     if (o == null)
914     head = next;
915     else
916     o.next = next;
917     } else {
918     o = p;
919     }
920     p = next;
921     }
922     if (head == null) // no more iterators to track
923     itrs = null;
924     }
925    
926     /**
927 jsr166 1.90 * Called whenever an interior remove (not at takeIndex) occured.
928 jsr166 1.93 *
929     * Notifies all iterators, and expunges any that are now stale.
930 jsr166 1.89 */
931 jsr166 1.90 void removedAt(int removedIndex) {
932 jsr166 1.89 for (Node o = null, p = head; p != null;) {
933     final Itr it = p.get();
934     final Node next = p.next;
935 jsr166 1.90 if (it == null || it.removedAt(removedIndex)) {
936 jsr166 1.89 // unlink p
937 jsr166 1.95 // assert it == null || it.isDetached();
938 jsr166 1.89 p.clear();
939     p.next = null;
940     if (o == null)
941     head = next;
942     else
943     o.next = next;
944     } else {
945     o = p;
946     }
947     p = next;
948     }
949     if (head == null) // no more iterators to track
950     itrs = null;
951     }
952    
953     /**
954     * Called whenever the queue becomes empty.
955     *
956     * Notifies all active iterators that the queue is empty,
957     * clears all weak refs, and unlinks the itrs datastructure.
958     */
959     void queueIsEmpty() {
960 jsr166 1.95 // assert lock.getHoldCount() == 1;
961 jsr166 1.89 for (Node p = head; p != null; p = p.next) {
962     Itr it = p.get();
963     if (it != null) {
964     p.clear();
965     it.shutdown();
966     }
967     }
968     head = null;
969     itrs = null;
970     }
971    
972     /**
973 jsr166 1.90 * Called whenever an element has been dequeued (at takeIndex).
974 jsr166 1.89 */
975     void elementDequeued() {
976 jsr166 1.95 // assert lock.getHoldCount() == 1;
977 jsr166 1.89 if (count == 0)
978     queueIsEmpty();
979     else if (takeIndex == 0)
980     takeIndexWrapped();
981     }
982     }
983    
984     /**
985     * Iterator for ArrayBlockingQueue.
986     *
987     * To maintain weak consistency with respect to puts and takes, we
988     * read ahead one slot, so as to not report hasNext true but then
989     * not have an element to return.
990     *
991     * We switch into "detached" mode (allowing prompt unlinking from
992     * itrs without help from the GC) when all indices are negative, or
993     * when hasNext returns false for the first time. This allows the
994     * iterator to track concurrent updates completely accurately,
995     * except for the corner case of the user calling Iterator.remove()
996     * after hasNext() returned false. Even in this case, we ensure
997     * that we don't remove the wrong element by keeping track of the
998     * expected element to remove, in lastItem. Yes, we may fail to
999     * remove lastItem from the queue if it moved due to an interleaved
1000     * interior remove while in detached mode.
1001 dl 1.8 */
1002 dl 1.5 private class Itr implements Iterator<E> {
1003 jsr166 1.91 /** Index to look for new nextItem; NONE at end */
1004 jsr166 1.89 private int cursor;
1005    
1006     /** Element to be returned by next call to next(); null if none */
1007     private E nextItem;
1008    
1009 jsr166 1.91 /** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
1010 jsr166 1.89 private int nextIndex;
1011    
1012     /** Last element returned; null if none or not detached. */
1013     private E lastItem;
1014    
1015 jsr166 1.91 /** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
1016 jsr166 1.89 private int lastRet;
1017    
1018 jsr166 1.91 /** Previous value of takeIndex, or DETACHED when detached */
1019 jsr166 1.89 private int prevTakeIndex;
1020    
1021     /** Previous value of iters.cycles */
1022     private int prevCycles;
1023 tim 1.12
1024 jsr166 1.91 /** Special index value indicating "not available" or "undefined" */
1025     private static final int NONE = -1;
1026    
1027     /**
1028     * Special index value indicating "removed elsewhere", that is,
1029     * removed by some operation other than a call to this.remove().
1030     */
1031     private static final int REMOVED = -2;
1032    
1033     /** Special value for prevTakeIndex indicating "detached mode" */
1034     private static final int DETACHED = -3;
1035    
1036 dl 1.66 Itr() {
1037 jsr166 1.95 // assert lock.getHoldCount() == 0;
1038 jsr166 1.91 lastRet = NONE;
1039 jsr166 1.68 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1040     lock.lock();
1041     try {
1042 jsr166 1.89 if (count == 0) {
1043 jsr166 1.95 // assert itrs == null;
1044 jsr166 1.91 cursor = NONE;
1045     nextIndex = NONE;
1046     prevTakeIndex = DETACHED;
1047 jsr166 1.89 } else {
1048     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1049     prevTakeIndex = takeIndex;
1050 jsr166 1.68 nextItem = itemAt(nextIndex = takeIndex);
1051 jsr166 1.89 cursor = incCursor(takeIndex);
1052     if (itrs == null) {
1053 jsr166 1.93 itrs = new Itrs(this);
1054 jsr166 1.89 } else {
1055     itrs.register(this); // in this order
1056     itrs.doSomeSweeping(false);
1057     }
1058     prevCycles = itrs.cycles;
1059 jsr166 1.95 // assert takeIndex >= 0;
1060     // assert prevTakeIndex == takeIndex;
1061     // assert nextIndex >= 0;
1062     // assert nextItem != null;
1063 jsr166 1.89 }
1064 jsr166 1.68 } finally {
1065     lock.unlock();
1066     }
1067 dl 1.5 }
1068 tim 1.12
1069 jsr166 1.89 boolean isDetached() {
1070 jsr166 1.95 // assert lock.getHoldCount() == 1;
1071 jsr166 1.89 return prevTakeIndex < 0;
1072     }
1073    
1074     private int incCursor(int index) {
1075 jsr166 1.95 // assert lock.getHoldCount() == 1;
1076 dl 1.100 if (++index == items.length)
1077     index = 0;
1078 jsr166 1.89 if (index == putIndex)
1079 jsr166 1.91 index = NONE;
1080 jsr166 1.89 return index;
1081     }
1082    
1083     /**
1084     * Returns true if index is invalidated by the given number of
1085     * dequeues, starting from prevTakeIndex.
1086     */
1087     private boolean invalidated(int index, int prevTakeIndex,
1088     long dequeues, int length) {
1089     if (index < 0)
1090     return false;
1091     int distance = index - prevTakeIndex;
1092     if (distance < 0)
1093     distance += length;
1094     return dequeues > distance;
1095     }
1096    
1097     /**
1098     * Adjusts indices to incorporate all dequeues since the last
1099     * operation on this iterator. Call only from iterating thread.
1100     */
1101     private void incorporateDequeues() {
1102 jsr166 1.95 // assert lock.getHoldCount() == 1;
1103     // assert itrs != null;
1104     // assert !isDetached();
1105     // assert count > 0;
1106 jsr166 1.89
1107     final int cycles = itrs.cycles;
1108     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1109     final int prevCycles = this.prevCycles;
1110     final int prevTakeIndex = this.prevTakeIndex;
1111    
1112     if (cycles != prevCycles || takeIndex != prevTakeIndex) {
1113     final int len = items.length;
1114     // how far takeIndex has advanced since the previous
1115     // operation of this iterator
1116     long dequeues = (cycles - prevCycles) * len
1117     + (takeIndex - prevTakeIndex);
1118    
1119     // Check indices for invalidation
1120     if (invalidated(lastRet, prevTakeIndex, dequeues, len))
1121 jsr166 1.91 lastRet = REMOVED;
1122 jsr166 1.89 if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
1123 jsr166 1.91 nextIndex = REMOVED;
1124 jsr166 1.89 if (invalidated(cursor, prevTakeIndex, dequeues, len))
1125     cursor = takeIndex;
1126    
1127     if (cursor < 0 && nextIndex < 0 && lastRet < 0)
1128     detach();
1129     else {
1130     this.prevCycles = cycles;
1131     this.prevTakeIndex = takeIndex;
1132     }
1133     }
1134     }
1135    
1136     /**
1137     * Called when itrs should stop tracking this iterator, either
1138     * because there are no more indices to update (cursor < 0 &&
1139     * nextIndex < 0 && lastRet < 0) or as a special exception, when
1140     * lastRet >= 0, because hasNext() is about to return false for the
1141     * first time. Call only from iterating thread.
1142     */
1143     private void detach() {
1144     // Switch to detached mode
1145 jsr166 1.95 // assert lock.getHoldCount() == 1;
1146     // assert cursor == NONE;
1147     // assert nextIndex < 0;
1148     // assert lastRet < 0 || nextItem == null;
1149     // assert lastRet < 0 ^ lastItem != null;
1150 jsr166 1.89 if (prevTakeIndex >= 0) {
1151 jsr166 1.95 // assert itrs != null;
1152 jsr166 1.91 prevTakeIndex = DETACHED;
1153 jsr166 1.89 // try to unlink from itrs (but not too hard)
1154     itrs.doSomeSweeping(true);
1155     }
1156     }
1157    
1158     /**
1159     * For performance reasons, we would like not to acquire a lock in
1160     * hasNext in the common case. To allow for this, we only access
1161     * fields (i.e. nextItem) that are not modified by update operations
1162     * triggered by queue modifications.
1163     */
1164 dl 1.5 public boolean hasNext() {
1165 jsr166 1.95 // assert lock.getHoldCount() == 0;
1166 jsr166 1.89 if (nextItem != null)
1167     return true;
1168     noNext();
1169     return false;
1170     }
1171    
1172     private void noNext() {
1173     final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1174     lock.lock();
1175     try {
1176 jsr166 1.95 // assert cursor == NONE;
1177     // assert nextIndex == NONE;
1178 jsr166 1.89 if (!isDetached()) {
1179 jsr166 1.95 // assert lastRet >= 0;
1180 jsr166 1.89 incorporateDequeues(); // might update lastRet
1181     if (lastRet >= 0) {
1182     lastItem = itemAt(lastRet);
1183 jsr166 1.95 // assert lastItem != null;
1184 jsr166 1.89 detach();
1185     }
1186     }
1187 jsr166 1.95 // assert isDetached();
1188     // assert lastRet < 0 ^ lastItem != null;
1189 jsr166 1.89 } finally {
1190     lock.unlock();
1191     }
1192 dl 1.5 }
1193 tim 1.12
1194 dl 1.5 public E next() {
1195 jsr166 1.95 // assert lock.getHoldCount() == 0;
1196 jsr166 1.89 final E x = nextItem;
1197     if (x == null)
1198     throw new NoSuchElementException();
1199 dl 1.66 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1200     lock.lock();
1201     try {
1202 jsr166 1.92 if (!isDetached())
1203 jsr166 1.89 incorporateDequeues();
1204 jsr166 1.95 // assert nextIndex != NONE;
1205     // assert lastItem == null;
1206 dl 1.66 lastRet = nextIndex;
1207 jsr166 1.89 final int cursor = this.cursor;
1208     if (cursor >= 0) {
1209     nextItem = itemAt(nextIndex = cursor);
1210 jsr166 1.95 // assert nextItem != null;
1211 jsr166 1.89 this.cursor = incCursor(cursor);
1212     } else {
1213 jsr166 1.91 nextIndex = NONE;
1214 jsr166 1.89 nextItem = null;
1215     }
1216 dl 1.66 } finally {
1217     lock.unlock();
1218 dl 1.2 }
1219 jsr166 1.89 return x;
1220 dl 1.5 }
1221 tim 1.12
1222 dl 1.5 public void remove() {
1223 jsr166 1.95 // assert lock.getHoldCount() == 0;
1224 dl 1.36 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1225 dl 1.5 lock.lock();
1226     try {
1227 jsr166 1.92 if (!isDetached())
1228     incorporateDequeues(); // might update lastRet or detach
1229     final int lastRet = this.lastRet;
1230     this.lastRet = NONE;
1231 jsr166 1.89 if (lastRet >= 0) {
1232 jsr166 1.92 if (!isDetached())
1233     removeAt(lastRet);
1234     else {
1235     final E lastItem = this.lastItem;
1236 jsr166 1.95 // assert lastItem != null;
1237 jsr166 1.92 this.lastItem = null;
1238 jsr166 1.89 if (itemAt(lastRet) == lastItem)
1239     removeAt(lastRet);
1240     }
1241 jsr166 1.91 } else if (lastRet == NONE)
1242 dl 1.66 throw new IllegalStateException();
1243 jsr166 1.91 // else lastRet == REMOVED and the last returned element was
1244 jsr166 1.89 // previously asynchronously removed via an operation other
1245     // than this.remove(), so nothing to do.
1246    
1247     if (cursor < 0 && nextIndex < 0)
1248     detach();
1249     } finally {
1250     lock.unlock();
1251 jsr166 1.95 // assert lastRet == NONE;
1252     // assert lastItem == null;
1253 jsr166 1.89 }
1254     }
1255    
1256     /**
1257     * Called to notify the iterator that the queue is empty, or that it
1258     * has fallen hopelessly behind, so that it should abandon any
1259     * further iteration, except possibly to return one more element
1260     * from next(), as promised by returning true from hasNext().
1261     */
1262     void shutdown() {
1263 jsr166 1.95 // assert lock.getHoldCount() == 1;
1264 jsr166 1.91 cursor = NONE;
1265 jsr166 1.89 if (nextIndex >= 0)
1266 jsr166 1.91 nextIndex = REMOVED;
1267 jsr166 1.89 if (lastRet >= 0) {
1268 jsr166 1.91 lastRet = REMOVED;
1269 jsr166 1.61 lastItem = null;
1270 jsr166 1.89 }
1271 jsr166 1.91 prevTakeIndex = DETACHED;
1272 jsr166 1.89 // Don't set nextItem to null because we must continue to be
1273     // able to return it on next().
1274     //
1275     // Caller will unlink from itrs when convenient.
1276     }
1277    
1278     private int distance(int index, int prevTakeIndex, int length) {
1279     int distance = index - prevTakeIndex;
1280     if (distance < 0)
1281     distance += length;
1282     return distance;
1283     }
1284    
1285     /**
1286 jsr166 1.90 * Called whenever an interior remove (not at takeIndex) occured.
1287 jsr166 1.89 *
1288 jsr166 1.90 * @return true if this iterator should be unlinked from itrs
1289 jsr166 1.89 */
1290 jsr166 1.90 boolean removedAt(int removedIndex) {
1291 jsr166 1.95 // assert lock.getHoldCount() == 1;
1292 jsr166 1.89 if (isDetached())
1293     return true;
1294    
1295     final int cycles = itrs.cycles;
1296     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1297     final int prevCycles = this.prevCycles;
1298     final int prevTakeIndex = this.prevTakeIndex;
1299     final int len = items.length;
1300     int cycleDiff = cycles - prevCycles;
1301 jsr166 1.90 if (removedIndex < takeIndex)
1302 jsr166 1.89 cycleDiff++;
1303     final int removedDistance =
1304 jsr166 1.90 (cycleDiff * len) + (removedIndex - prevTakeIndex);
1305 jsr166 1.95 // assert removedDistance >= 0;
1306 jsr166 1.89 int cursor = this.cursor;
1307     if (cursor >= 0) {
1308     int x = distance(cursor, prevTakeIndex, len);
1309     if (x == removedDistance) {
1310 jsr166 1.90 if (cursor == putIndex)
1311 jsr166 1.91 this.cursor = cursor = NONE;
1312 jsr166 1.89 }
1313     else if (x > removedDistance) {
1314 jsr166 1.95 // assert cursor != prevTakeIndex;
1315 jsr166 1.89 this.cursor = cursor = dec(cursor);
1316 jsr166 1.71 }
1317 dl 1.5 }
1318 jsr166 1.89 int lastRet = this.lastRet;
1319     if (lastRet >= 0) {
1320     int x = distance(lastRet, prevTakeIndex, len);
1321     if (x == removedDistance)
1322 jsr166 1.91 this.lastRet = lastRet = REMOVED;
1323 jsr166 1.89 else if (x > removedDistance)
1324     this.lastRet = lastRet = dec(lastRet);
1325     }
1326     int nextIndex = this.nextIndex;
1327     if (nextIndex >= 0) {
1328     int x = distance(nextIndex, prevTakeIndex, len);
1329     if (x == removedDistance)
1330 jsr166 1.91 this.nextIndex = nextIndex = REMOVED;
1331 jsr166 1.89 else if (x > removedDistance)
1332     this.nextIndex = nextIndex = dec(nextIndex);
1333     }
1334     else if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
1335 jsr166 1.91 this.prevTakeIndex = DETACHED;
1336 jsr166 1.89 return true;
1337     }
1338     return false;
1339     }
1340    
1341     /**
1342     * Called whenever takeIndex wraps around to zero.
1343     *
1344 jsr166 1.90 * @return true if this iterator should be unlinked from itrs
1345 jsr166 1.89 */
1346     boolean takeIndexWrapped() {
1347 jsr166 1.95 // assert lock.getHoldCount() == 1;
1348 jsr166 1.89 if (isDetached())
1349     return true;
1350     if (itrs.cycles - prevCycles > 1) {
1351     // All the elements that existed at the time of the last
1352     // operation are gone, so abandon further iteration.
1353     shutdown();
1354     return true;
1355     }
1356     return false;
1357 dl 1.5 }
1358 jsr166 1.89
1359     // /** Uncomment for debugging. */
1360     // public String toString() {
1361     // return ("cursor=" + cursor + " " +
1362     // "nextIndex=" + nextIndex + " " +
1363     // "lastRet=" + lastRet + " " +
1364     // "nextItem=" + nextItem + " " +
1365     // "lastItem=" + lastItem + " " +
1366     // "prevCycles=" + prevCycles + " " +
1367     // "prevTakeIndex=" + prevTakeIndex + " " +
1368     // "size()=" + size() + " " +
1369     // "remainingCapacity()=" + remainingCapacity());
1370     // }
1371 tim 1.1 }
1372 dl 1.100
1373     Spliterator<E> spliterator() { // cheaper to use snapshot than track array
1374     return Collections.arraySnapshotSpliterator
1375     (this, Spliterator.ORDERED | Spliterator.NONNULL |
1376     Spliterator.CONCURRENT);
1377     }
1378    
1379     public Stream<E> stream() {
1380     return Streams.stream(spliterator());
1381     }
1382    
1383     public Stream<E> parallelStream() {
1384     return Streams.parallelStream(spliterator());
1385     }
1386    
1387 tim 1.1 }