ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.128
Committed: Sat Nov 5 22:24:57 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.127: +54 -6 lines
Log Message:
Optimize forEach using nested loop trick, as in ArrayDeque

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