ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.130
Committed: Sun Nov 6 05:57:19 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.129: +10 -9 lines
Log Message:
Optimize remove(Object) 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.130 for (int i = takeIndex, end = putIndex,
482     to = (i < end) ? end : items.length;
483     ; i = 0, to = end) {
484     for (; i < to; i++)
485     if (o.equals(items[i])) {
486     removeAt(i);
487     return true;
488     }
489     if (to == end) break;
490     }
491 jsr166 1.50 }
492 jsr166 1.68 return false;
493 jsr166 1.50 } finally {
494     lock.unlock();
495     }
496     }
497 dholmes 1.13
498 jsr166 1.50 /**
499 jsr166 1.69 * Returns {@code true} if this queue contains the specified element.
500     * More formally, returns {@code true} if and only if this queue contains
501     * at least one element {@code e} such that {@code o.equals(e)}.
502 jsr166 1.50 *
503     * @param o object to be checked for containment in this queue
504 jsr166 1.69 * @return {@code true} if this queue contains the specified element
505 jsr166 1.50 */
506 dholmes 1.21 public boolean contains(Object o) {
507     if (o == null) return false;
508 dl 1.36 final ReentrantLock lock = this.lock;
509 dl 1.5 lock.lock();
510     try {
511 jsr166 1.86 if (count > 0) {
512 jsr166 1.114 final Object[] items = this.items;
513 jsr166 1.129 for (int i = takeIndex, end = putIndex,
514     to = (i < end) ? end : items.length;
515     ; i = 0, to = end) {
516     for (; i < to; i++)
517     if (o.equals(items[i]))
518     return true;
519     if (to == end) break;
520     }
521 jsr166 1.86 }
522 dl 1.2 return false;
523 tim 1.23 } finally {
524 dl 1.5 lock.unlock();
525     }
526     }
527 brian 1.7
528 jsr166 1.50 /**
529     * Returns an array containing all of the elements in this queue, in
530     * proper sequence.
531     *
532     * <p>The returned array will be "safe" in that no references to it are
533     * maintained by this queue. (In other words, this method must allocate
534     * a new array). The caller is thus free to modify the returned array.
535 jsr166 1.51 *
536 jsr166 1.50 * <p>This method acts as bridge between array-based and collection-based
537     * APIs.
538     *
539     * @return an array containing all of the elements in this queue
540     */
541 dl 1.5 public Object[] toArray() {
542 dl 1.36 final ReentrantLock lock = this.lock;
543 dl 1.5 lock.lock();
544     try {
545 jsr166 1.120 final Object[] items = this.items;
546     final int end = takeIndex + count;
547     final Object[] a = Arrays.copyOfRange(items, takeIndex, end);
548     if (end != putIndex)
549     System.arraycopy(items, 0, a, items.length - takeIndex, putIndex);
550     return a;
551 tim 1.23 } finally {
552 dl 1.5 lock.unlock();
553     }
554     }
555 brian 1.7
556 jsr166 1.50 /**
557     * Returns an array containing all of the elements in this queue, in
558     * proper sequence; the runtime type of the returned array is that of
559     * the specified array. If the queue fits in the specified array, it
560     * is returned therein. Otherwise, a new array is allocated with the
561     * runtime type of the specified array and the size of this queue.
562     *
563     * <p>If this queue fits in the specified array with room to spare
564     * (i.e., the array has more elements than this queue), the element in
565     * the array immediately following the end of the queue is set to
566 jsr166 1.69 * {@code null}.
567 jsr166 1.50 *
568     * <p>Like the {@link #toArray()} method, this method acts as bridge between
569     * array-based and collection-based APIs. Further, this method allows
570     * precise control over the runtime type of the output array, and may,
571     * under certain circumstances, be used to save allocation costs.
572     *
573 jsr166 1.69 * <p>Suppose {@code x} is a queue known to contain only strings.
574 jsr166 1.50 * The following code can be used to dump the queue into a newly
575 jsr166 1.69 * allocated array of {@code String}:
576 jsr166 1.50 *
577 jsr166 1.117 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
578 jsr166 1.50 *
579 jsr166 1.69 * Note that {@code toArray(new Object[0])} is identical in function to
580     * {@code toArray()}.
581 jsr166 1.50 *
582     * @param a the array into which the elements of the queue are to
583     * be stored, if it is big enough; otherwise, a new array of the
584     * same runtime type is allocated for this purpose
585     * @return an array containing all of the elements in this queue
586     * @throws ArrayStoreException if the runtime type of the specified array
587     * is not a supertype of the runtime type of every element in
588     * this queue
589     * @throws NullPointerException if the specified array is null
590     */
591 jsr166 1.68 @SuppressWarnings("unchecked")
592 dl 1.5 public <T> T[] toArray(T[] a) {
593 dl 1.36 final ReentrantLock lock = this.lock;
594 dl 1.5 lock.lock();
595     try {
596 jsr166 1.120 final Object[] items = this.items;
597 jsr166 1.68 final int count = this.count;
598 jsr166 1.120 final int firstLeg = Math.min(items.length - takeIndex, count);
599     if (a.length < count) {
600     a = (T[]) Arrays.copyOfRange(items, takeIndex, takeIndex + count,
601     a.getClass());
602     } else {
603     System.arraycopy(items, takeIndex, a, 0, firstLeg);
604     if (a.length > count)
605     a[count] = null;
606     }
607     if (firstLeg < count)
608     System.arraycopy(items, 0, a, firstLeg, putIndex);
609     return a;
610 tim 1.23 } finally {
611 dl 1.5 lock.unlock();
612     }
613     }
614 dl 1.6
615     public String toString() {
616 jsr166 1.122 return Helpers.collectionToString(this);
617 dl 1.6 }
618 tim 1.12
619 dl 1.44 /**
620     * Atomically removes all of the elements from this queue.
621     * The queue will be empty after this call returns.
622     */
623 dl 1.30 public void clear() {
624 dl 1.36 final ReentrantLock lock = this.lock;
625 dl 1.30 lock.lock();
626     try {
627 jsr166 1.86 int k = count;
628     if (k > 0) {
629 jsr166 1.123 final Object[] items = this.items;
630 jsr166 1.86 final int putIndex = this.putIndex;
631     int i = takeIndex;
632     do {
633     items[i] = null;
634 jsr166 1.116 if (++i == items.length) i = 0;
635 dl 1.100 } while (i != putIndex);
636 jsr166 1.86 takeIndex = putIndex;
637     count = 0;
638 jsr166 1.89 if (itrs != null)
639     itrs.queueIsEmpty();
640 jsr166 1.86 for (; k > 0 && lock.hasWaiters(notFull); k--)
641     notFull.signal();
642     }
643 dl 1.30 } finally {
644     lock.unlock();
645     }
646     }
647    
648 jsr166 1.50 /**
649     * @throws UnsupportedOperationException {@inheritDoc}
650     * @throws ClassCastException {@inheritDoc}
651     * @throws NullPointerException {@inheritDoc}
652     * @throws IllegalArgumentException {@inheritDoc}
653     */
654 dl 1.30 public int drainTo(Collection<? super E> c) {
655 jsr166 1.81 return drainTo(c, Integer.MAX_VALUE);
656 dl 1.30 }
657    
658 jsr166 1.50 /**
659     * @throws UnsupportedOperationException {@inheritDoc}
660     * @throws ClassCastException {@inheritDoc}
661     * @throws NullPointerException {@inheritDoc}
662     * @throws IllegalArgumentException {@inheritDoc}
663     */
664 dl 1.30 public int drainTo(Collection<? super E> c, int maxElements) {
665 jsr166 1.119 Objects.requireNonNull(c);
666 dl 1.30 if (c == this)
667     throw new IllegalArgumentException();
668     if (maxElements <= 0)
669     return 0;
670 jsr166 1.68 final Object[] items = this.items;
671 dl 1.36 final ReentrantLock lock = this.lock;
672 dl 1.30 lock.lock();
673     try {
674 jsr166 1.82 int n = Math.min(maxElements, count);
675     int take = takeIndex;
676     int i = 0;
677     try {
678     while (i < n) {
679 jsr166 1.97 @SuppressWarnings("unchecked")
680     E x = (E) items[take];
681 jsr166 1.84 c.add(x);
682 jsr166 1.82 items[take] = null;
683 jsr166 1.116 if (++take == items.length) take = 0;
684 jsr166 1.86 i++;
685 jsr166 1.82 }
686     return n;
687     } finally {
688     // Restore invariants even if c.add() threw
689 jsr166 1.89 if (i > 0) {
690     count -= i;
691     takeIndex = take;
692     if (itrs != null) {
693     if (count == 0)
694     itrs.queueIsEmpty();
695     else if (i > take)
696     itrs.takeIndexWrapped();
697     }
698     for (; i > 0 && lock.hasWaiters(notFull); i--)
699     notFull.signal();
700     }
701 dl 1.30 }
702     } finally {
703     lock.unlock();
704     }
705     }
706    
707 brian 1.7 /**
708 dl 1.75 * Returns an iterator over the elements in this queue in proper sequence.
709 jsr166 1.77 * The elements will be returned in order from first (head) to last (tail).
710     *
711 jsr166 1.106 * <p>The returned iterator is
712     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
713 brian 1.7 *
714 jsr166 1.50 * @return an iterator over the elements in this queue in proper sequence
715 brian 1.7 */
716 dl 1.5 public Iterator<E> iterator() {
717 jsr166 1.68 return new Itr();
718 dl 1.5 }
719 dl 1.8
720     /**
721 jsr166 1.94 * Shared data between iterators and their queue, allowing queue
722 jsr166 1.89 * modifications to update iterators when elements are removed.
723     *
724 jsr166 1.94 * This adds a lot of complexity for the sake of correctly
725     * handling some uncommon operations, but the combination of
726     * circular-arrays and supporting interior removes (i.e., those
727     * not at head) would cause iterators to sometimes lose their
728     * places and/or (re)report elements they shouldn't. To avoid
729     * this, when a queue has one or more iterators, it keeps iterator
730     * state consistent by:
731     *
732     * (1) keeping track of the number of "cycles", that is, the
733     * number of times takeIndex has wrapped around to 0.
734     * (2) notifying all iterators via the callback removedAt whenever
735     * an interior element is removed (and thus other elements may
736     * be shifted).
737     *
738     * These suffice to eliminate iterator inconsistencies, but
739     * unfortunately add the secondary responsibility of maintaining
740     * the list of iterators. We track all active iterators in a
741     * simple linked list (accessed only when the queue's lock is
742     * held) of weak references to Itr. The list is cleaned up using
743     * 3 different mechanisms:
744 jsr166 1.89 *
745     * (1) Whenever a new iterator is created, do some O(1) checking for
746     * stale list elements.
747     *
748     * (2) Whenever takeIndex wraps around to 0, check for iterators
749     * that have been unused for more than one wrap-around cycle.
750     *
751     * (3) Whenever the queue becomes empty, all iterators are notified
752     * and this entire data structure is discarded.
753     *
754 jsr166 1.94 * So in addition to the removedAt callback that is necessary for
755     * correctness, iterators have the shutdown and takeIndexWrapped
756     * callbacks that help remove stale iterators from the list.
757     *
758     * Whenever a list element is examined, it is expunged if either
759     * the GC has determined that the iterator is discarded, or if the
760     * iterator reports that it is "detached" (does not need any
761     * further state updates). Overhead is maximal when takeIndex
762     * never advances, iterators are discarded before they are
763     * exhausted, and all removals are interior removes, in which case
764     * all stale iterators are discovered by the GC. But even in this
765     * case we don't increase the amortized complexity.
766     *
767     * Care must be taken to keep list sweeping methods from
768     * reentrantly invoking another such method, causing subtle
769     * corruption bugs.
770 jsr166 1.89 */
771     class Itrs {
772    
773     /**
774     * Node in a linked list of weak iterator references.
775     */
776     private class Node extends WeakReference<Itr> {
777     Node next;
778    
779     Node(Itr iterator, Node next) {
780     super(iterator);
781     this.next = next;
782     }
783     }
784    
785     /** Incremented whenever takeIndex wraps around to 0 */
786 jsr166 1.108 int cycles;
787 jsr166 1.89
788     /** Linked list of weak iterator references */
789 jsr166 1.93 private Node head;
790 jsr166 1.89
791     /** Used to expunge stale iterators */
792 jsr166 1.108 private Node sweeper;
793 jsr166 1.89
794     private static final int SHORT_SWEEP_PROBES = 4;
795     private static final int LONG_SWEEP_PROBES = 16;
796    
797 jsr166 1.93 Itrs(Itr initial) {
798     register(initial);
799     }
800    
801 jsr166 1.89 /**
802     * Sweeps itrs, looking for and expunging stale iterators.
803     * If at least one was found, tries harder to find more.
804 jsr166 1.94 * Called only from iterating thread.
805 jsr166 1.89 *
806     * @param tryHarder whether to start in try-harder mode, because
807     * there is known to be at least one iterator to collect
808     */
809     void doSomeSweeping(boolean tryHarder) {
810 jsr166 1.95 // assert lock.getHoldCount() == 1;
811     // assert head != null;
812 jsr166 1.89 int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
813     Node o, p;
814     final Node sweeper = this.sweeper;
815 jsr166 1.93 boolean passedGo; // to limit search to one full sweep
816 jsr166 1.89
817 jsr166 1.93 if (sweeper == null) {
818     o = null;
819     p = head;
820     passedGo = true;
821     } else {
822 jsr166 1.89 o = sweeper;
823     p = o.next;
824 jsr166 1.93 passedGo = false;
825 jsr166 1.89 }
826    
827 jsr166 1.93 for (; probes > 0; probes--) {
828     if (p == null) {
829     if (passedGo)
830     break;
831     o = null;
832     p = head;
833     passedGo = true;
834     }
835 jsr166 1.89 final Itr it = p.get();
836     final Node next = p.next;
837     if (it == null || it.isDetached()) {
838     // found a discarded/exhausted iterator
839     probes = LONG_SWEEP_PROBES; // "try harder"
840     // unlink p
841     p.clear();
842     p.next = null;
843 jsr166 1.93 if (o == null) {
844 jsr166 1.89 head = next;
845 jsr166 1.93 if (next == null) {
846     // We've run out of iterators to track; retire
847     itrs = null;
848     return;
849     }
850     }
851 jsr166 1.89 else
852     o.next = next;
853     } else {
854     o = p;
855     }
856     p = next;
857     }
858    
859     this.sweeper = (p == null) ? null : o;
860     }
861    
862     /**
863     * Adds a new iterator to the linked list of tracked iterators.
864     */
865     void register(Itr itr) {
866 jsr166 1.95 // assert lock.getHoldCount() == 1;
867 jsr166 1.89 head = new Node(itr, head);
868     }
869    
870     /**
871     * Called whenever takeIndex wraps around to 0.
872     *
873     * Notifies all iterators, and expunges any that are now stale.
874     */
875     void takeIndexWrapped() {
876 jsr166 1.95 // assert lock.getHoldCount() == 1;
877 jsr166 1.89 cycles++;
878     for (Node o = null, p = head; p != null;) {
879     final Itr it = p.get();
880     final Node next = p.next;
881     if (it == null || it.takeIndexWrapped()) {
882     // unlink p
883 jsr166 1.95 // assert it == null || it.isDetached();
884 jsr166 1.89 p.clear();
885     p.next = null;
886     if (o == null)
887     head = next;
888     else
889     o.next = next;
890     } else {
891     o = p;
892     }
893     p = next;
894     }
895     if (head == null) // no more iterators to track
896     itrs = null;
897     }
898    
899     /**
900 jsr166 1.107 * Called whenever an interior remove (not at takeIndex) occurred.
901 jsr166 1.93 *
902     * Notifies all iterators, and expunges any that are now stale.
903 jsr166 1.89 */
904 jsr166 1.90 void removedAt(int removedIndex) {
905 jsr166 1.89 for (Node o = null, p = head; p != null;) {
906     final Itr it = p.get();
907     final Node next = p.next;
908 jsr166 1.90 if (it == null || it.removedAt(removedIndex)) {
909 jsr166 1.89 // 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     * Called whenever the queue becomes empty.
928     *
929     * Notifies all active iterators that the queue is empty,
930     * clears all weak refs, and unlinks the itrs datastructure.
931     */
932     void queueIsEmpty() {
933 jsr166 1.95 // assert lock.getHoldCount() == 1;
934 jsr166 1.89 for (Node p = head; p != null; p = p.next) {
935     Itr it = p.get();
936     if (it != null) {
937     p.clear();
938     it.shutdown();
939     }
940     }
941     head = null;
942     itrs = null;
943     }
944    
945     /**
946 jsr166 1.90 * Called whenever an element has been dequeued (at takeIndex).
947 jsr166 1.89 */
948     void elementDequeued() {
949 jsr166 1.95 // assert lock.getHoldCount() == 1;
950 jsr166 1.89 if (count == 0)
951     queueIsEmpty();
952     else if (takeIndex == 0)
953     takeIndexWrapped();
954     }
955     }
956    
957     /**
958     * Iterator for ArrayBlockingQueue.
959     *
960     * To maintain weak consistency with respect to puts and takes, we
961     * read ahead one slot, so as to not report hasNext true but then
962     * not have an element to return.
963     *
964     * We switch into "detached" mode (allowing prompt unlinking from
965     * itrs without help from the GC) when all indices are negative, or
966     * when hasNext returns false for the first time. This allows the
967     * iterator to track concurrent updates completely accurately,
968     * except for the corner case of the user calling Iterator.remove()
969     * after hasNext() returned false. Even in this case, we ensure
970     * that we don't remove the wrong element by keeping track of the
971     * expected element to remove, in lastItem. Yes, we may fail to
972     * remove lastItem from the queue if it moved due to an interleaved
973     * interior remove while in detached mode.
974 dl 1.8 */
975 dl 1.5 private class Itr implements Iterator<E> {
976 jsr166 1.91 /** Index to look for new nextItem; NONE at end */
977 jsr166 1.89 private int cursor;
978    
979     /** Element to be returned by next call to next(); null if none */
980     private E nextItem;
981    
982 jsr166 1.91 /** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
983 jsr166 1.89 private int nextIndex;
984    
985     /** Last element returned; null if none or not detached. */
986     private E lastItem;
987    
988 jsr166 1.91 /** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
989 jsr166 1.89 private int lastRet;
990    
991 jsr166 1.91 /** Previous value of takeIndex, or DETACHED when detached */
992 jsr166 1.89 private int prevTakeIndex;
993    
994     /** Previous value of iters.cycles */
995     private int prevCycles;
996 tim 1.12
997 jsr166 1.91 /** Special index value indicating "not available" or "undefined" */
998     private static final int NONE = -1;
999    
1000     /**
1001     * Special index value indicating "removed elsewhere", that is,
1002     * removed by some operation other than a call to this.remove().
1003     */
1004     private static final int REMOVED = -2;
1005    
1006     /** Special value for prevTakeIndex indicating "detached mode" */
1007     private static final int DETACHED = -3;
1008    
1009 dl 1.66 Itr() {
1010 jsr166 1.95 // assert lock.getHoldCount() == 0;
1011 jsr166 1.91 lastRet = NONE;
1012 jsr166 1.68 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1013     lock.lock();
1014     try {
1015 jsr166 1.89 if (count == 0) {
1016 jsr166 1.95 // assert itrs == null;
1017 jsr166 1.91 cursor = NONE;
1018     nextIndex = NONE;
1019     prevTakeIndex = DETACHED;
1020 jsr166 1.89 } else {
1021     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1022     prevTakeIndex = takeIndex;
1023 jsr166 1.68 nextItem = itemAt(nextIndex = takeIndex);
1024 jsr166 1.89 cursor = incCursor(takeIndex);
1025     if (itrs == null) {
1026 jsr166 1.93 itrs = new Itrs(this);
1027 jsr166 1.89 } else {
1028     itrs.register(this); // in this order
1029     itrs.doSomeSweeping(false);
1030     }
1031     prevCycles = itrs.cycles;
1032 jsr166 1.95 // assert takeIndex >= 0;
1033     // assert prevTakeIndex == takeIndex;
1034     // assert nextIndex >= 0;
1035     // assert nextItem != null;
1036 jsr166 1.89 }
1037 jsr166 1.68 } finally {
1038     lock.unlock();
1039     }
1040 dl 1.5 }
1041 tim 1.12
1042 jsr166 1.89 boolean isDetached() {
1043 jsr166 1.95 // assert lock.getHoldCount() == 1;
1044 jsr166 1.89 return prevTakeIndex < 0;
1045     }
1046    
1047     private int incCursor(int index) {
1048 jsr166 1.95 // assert lock.getHoldCount() == 1;
1049 jsr166 1.116 if (++index == items.length) index = 0;
1050     if (index == putIndex) index = NONE;
1051 jsr166 1.89 return index;
1052     }
1053    
1054     /**
1055     * Returns true if index is invalidated by the given number of
1056     * dequeues, starting from prevTakeIndex.
1057     */
1058     private boolean invalidated(int index, int prevTakeIndex,
1059     long dequeues, int length) {
1060     if (index < 0)
1061     return false;
1062     int distance = index - prevTakeIndex;
1063     if (distance < 0)
1064     distance += length;
1065     return dequeues > distance;
1066     }
1067    
1068     /**
1069     * Adjusts indices to incorporate all dequeues since the last
1070     * operation on this iterator. Call only from iterating thread.
1071     */
1072     private void incorporateDequeues() {
1073 jsr166 1.95 // assert lock.getHoldCount() == 1;
1074     // assert itrs != null;
1075     // assert !isDetached();
1076     // assert count > 0;
1077 jsr166 1.89
1078     final int cycles = itrs.cycles;
1079     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1080     final int prevCycles = this.prevCycles;
1081     final int prevTakeIndex = this.prevTakeIndex;
1082    
1083     if (cycles != prevCycles || takeIndex != prevTakeIndex) {
1084     final int len = items.length;
1085     // how far takeIndex has advanced since the previous
1086     // operation of this iterator
1087     long dequeues = (cycles - prevCycles) * len
1088     + (takeIndex - prevTakeIndex);
1089    
1090     // Check indices for invalidation
1091     if (invalidated(lastRet, prevTakeIndex, dequeues, len))
1092 jsr166 1.91 lastRet = REMOVED;
1093 jsr166 1.89 if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
1094 jsr166 1.91 nextIndex = REMOVED;
1095 jsr166 1.89 if (invalidated(cursor, prevTakeIndex, dequeues, len))
1096     cursor = takeIndex;
1097    
1098     if (cursor < 0 && nextIndex < 0 && lastRet < 0)
1099     detach();
1100     else {
1101     this.prevCycles = cycles;
1102     this.prevTakeIndex = takeIndex;
1103     }
1104     }
1105     }
1106    
1107     /**
1108     * Called when itrs should stop tracking this iterator, either
1109     * because there are no more indices to update (cursor < 0 &&
1110     * nextIndex < 0 && lastRet < 0) or as a special exception, when
1111     * lastRet >= 0, because hasNext() is about to return false for the
1112     * first time. Call only from iterating thread.
1113     */
1114     private void detach() {
1115     // Switch to detached mode
1116 jsr166 1.95 // assert lock.getHoldCount() == 1;
1117     // assert cursor == NONE;
1118     // assert nextIndex < 0;
1119     // assert lastRet < 0 || nextItem == null;
1120     // assert lastRet < 0 ^ lastItem != null;
1121 jsr166 1.89 if (prevTakeIndex >= 0) {
1122 jsr166 1.95 // assert itrs != null;
1123 jsr166 1.91 prevTakeIndex = DETACHED;
1124 jsr166 1.89 // try to unlink from itrs (but not too hard)
1125     itrs.doSomeSweeping(true);
1126     }
1127     }
1128    
1129     /**
1130     * For performance reasons, we would like not to acquire a lock in
1131     * hasNext in the common case. To allow for this, we only access
1132     * fields (i.e. nextItem) that are not modified by update operations
1133     * triggered by queue modifications.
1134     */
1135 dl 1.5 public boolean hasNext() {
1136 jsr166 1.95 // assert lock.getHoldCount() == 0;
1137 jsr166 1.89 if (nextItem != null)
1138     return true;
1139     noNext();
1140     return false;
1141     }
1142    
1143     private void noNext() {
1144     final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1145     lock.lock();
1146     try {
1147 jsr166 1.95 // assert cursor == NONE;
1148     // assert nextIndex == NONE;
1149 jsr166 1.89 if (!isDetached()) {
1150 jsr166 1.95 // assert lastRet >= 0;
1151 jsr166 1.89 incorporateDequeues(); // might update lastRet
1152     if (lastRet >= 0) {
1153     lastItem = itemAt(lastRet);
1154 jsr166 1.95 // assert lastItem != null;
1155 jsr166 1.89 detach();
1156     }
1157     }
1158 jsr166 1.95 // assert isDetached();
1159     // assert lastRet < 0 ^ lastItem != null;
1160 jsr166 1.89 } finally {
1161     lock.unlock();
1162     }
1163 dl 1.5 }
1164 tim 1.12
1165 dl 1.5 public E next() {
1166 jsr166 1.95 // assert lock.getHoldCount() == 0;
1167 jsr166 1.89 final E x = nextItem;
1168     if (x == null)
1169     throw new NoSuchElementException();
1170 dl 1.66 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1171     lock.lock();
1172     try {
1173 jsr166 1.92 if (!isDetached())
1174 jsr166 1.89 incorporateDequeues();
1175 jsr166 1.95 // assert nextIndex != NONE;
1176     // assert lastItem == null;
1177 dl 1.66 lastRet = nextIndex;
1178 jsr166 1.89 final int cursor = this.cursor;
1179     if (cursor >= 0) {
1180     nextItem = itemAt(nextIndex = cursor);
1181 jsr166 1.95 // assert nextItem != null;
1182 jsr166 1.89 this.cursor = incCursor(cursor);
1183     } else {
1184 jsr166 1.91 nextIndex = NONE;
1185 jsr166 1.89 nextItem = null;
1186     }
1187 dl 1.66 } finally {
1188     lock.unlock();
1189 dl 1.2 }
1190 jsr166 1.89 return x;
1191 dl 1.5 }
1192 tim 1.12
1193 dl 1.5 public void remove() {
1194 jsr166 1.95 // assert lock.getHoldCount() == 0;
1195 dl 1.36 final ReentrantLock lock = ArrayBlockingQueue.this.lock;
1196 dl 1.5 lock.lock();
1197     try {
1198 jsr166 1.92 if (!isDetached())
1199     incorporateDequeues(); // might update lastRet or detach
1200     final int lastRet = this.lastRet;
1201     this.lastRet = NONE;
1202 jsr166 1.89 if (lastRet >= 0) {
1203 jsr166 1.92 if (!isDetached())
1204     removeAt(lastRet);
1205     else {
1206     final E lastItem = this.lastItem;
1207 jsr166 1.95 // assert lastItem != null;
1208 jsr166 1.92 this.lastItem = null;
1209 jsr166 1.89 if (itemAt(lastRet) == lastItem)
1210     removeAt(lastRet);
1211     }
1212 jsr166 1.91 } else if (lastRet == NONE)
1213 dl 1.66 throw new IllegalStateException();
1214 jsr166 1.91 // else lastRet == REMOVED and the last returned element was
1215 jsr166 1.89 // previously asynchronously removed via an operation other
1216     // than this.remove(), so nothing to do.
1217    
1218     if (cursor < 0 && nextIndex < 0)
1219     detach();
1220     } finally {
1221     lock.unlock();
1222 jsr166 1.95 // assert lastRet == NONE;
1223     // assert lastItem == null;
1224 jsr166 1.89 }
1225     }
1226    
1227     /**
1228     * Called to notify the iterator that the queue is empty, or that it
1229     * has fallen hopelessly behind, so that it should abandon any
1230     * further iteration, except possibly to return one more element
1231     * from next(), as promised by returning true from hasNext().
1232     */
1233     void shutdown() {
1234 jsr166 1.95 // assert lock.getHoldCount() == 1;
1235 jsr166 1.91 cursor = NONE;
1236 jsr166 1.89 if (nextIndex >= 0)
1237 jsr166 1.91 nextIndex = REMOVED;
1238 jsr166 1.89 if (lastRet >= 0) {
1239 jsr166 1.91 lastRet = REMOVED;
1240 jsr166 1.61 lastItem = null;
1241 jsr166 1.89 }
1242 jsr166 1.91 prevTakeIndex = DETACHED;
1243 jsr166 1.89 // Don't set nextItem to null because we must continue to be
1244     // able to return it on next().
1245     //
1246     // Caller will unlink from itrs when convenient.
1247     }
1248    
1249     private int distance(int index, int prevTakeIndex, int length) {
1250     int distance = index - prevTakeIndex;
1251     if (distance < 0)
1252     distance += length;
1253     return distance;
1254     }
1255    
1256     /**
1257 jsr166 1.107 * Called whenever an interior remove (not at takeIndex) occurred.
1258 jsr166 1.89 *
1259 jsr166 1.90 * @return true if this iterator should be unlinked from itrs
1260 jsr166 1.89 */
1261 jsr166 1.90 boolean removedAt(int removedIndex) {
1262 jsr166 1.95 // assert lock.getHoldCount() == 1;
1263 jsr166 1.89 if (isDetached())
1264     return true;
1265    
1266     final int takeIndex = ArrayBlockingQueue.this.takeIndex;
1267     final int prevTakeIndex = this.prevTakeIndex;
1268     final int len = items.length;
1269 jsr166 1.112 // distance from prevTakeIndex to removedIndex
1270 jsr166 1.89 final int removedDistance =
1271 jsr166 1.112 len * (itrs.cycles - this.prevCycles
1272     + ((removedIndex < takeIndex) ? 1 : 0))
1273     + (removedIndex - prevTakeIndex);
1274     // assert itrs.cycles - this.prevCycles >= 0;
1275     // assert itrs.cycles - this.prevCycles <= 1;
1276     // assert removedDistance > 0;
1277     // assert removedIndex != takeIndex;
1278 jsr166 1.89 int cursor = this.cursor;
1279     if (cursor >= 0) {
1280     int x = distance(cursor, prevTakeIndex, len);
1281     if (x == removedDistance) {
1282 jsr166 1.90 if (cursor == putIndex)
1283 jsr166 1.91 this.cursor = cursor = NONE;
1284 jsr166 1.89 }
1285     else if (x > removedDistance) {
1286 jsr166 1.95 // assert cursor != prevTakeIndex;
1287 jsr166 1.89 this.cursor = cursor = dec(cursor);
1288 jsr166 1.71 }
1289 dl 1.5 }
1290 jsr166 1.89 int lastRet = this.lastRet;
1291     if (lastRet >= 0) {
1292     int x = distance(lastRet, prevTakeIndex, len);
1293     if (x == removedDistance)
1294 jsr166 1.91 this.lastRet = lastRet = REMOVED;
1295 jsr166 1.89 else if (x > removedDistance)
1296     this.lastRet = lastRet = dec(lastRet);
1297     }
1298     int nextIndex = this.nextIndex;
1299     if (nextIndex >= 0) {
1300     int x = distance(nextIndex, prevTakeIndex, len);
1301     if (x == removedDistance)
1302 jsr166 1.91 this.nextIndex = nextIndex = REMOVED;
1303 jsr166 1.89 else if (x > removedDistance)
1304     this.nextIndex = nextIndex = dec(nextIndex);
1305     }
1306 jsr166 1.112 if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
1307 jsr166 1.91 this.prevTakeIndex = DETACHED;
1308 jsr166 1.89 return true;
1309     }
1310     return false;
1311     }
1312    
1313     /**
1314     * Called whenever takeIndex wraps around to zero.
1315     *
1316 jsr166 1.90 * @return true if this iterator should be unlinked from itrs
1317 jsr166 1.89 */
1318     boolean takeIndexWrapped() {
1319 jsr166 1.95 // assert lock.getHoldCount() == 1;
1320 jsr166 1.89 if (isDetached())
1321     return true;
1322     if (itrs.cycles - prevCycles > 1) {
1323     // All the elements that existed at the time of the last
1324     // operation are gone, so abandon further iteration.
1325     shutdown();
1326     return true;
1327     }
1328     return false;
1329 dl 1.5 }
1330 jsr166 1.89
1331     // /** Uncomment for debugging. */
1332     // public String toString() {
1333     // return ("cursor=" + cursor + " " +
1334     // "nextIndex=" + nextIndex + " " +
1335     // "lastRet=" + lastRet + " " +
1336     // "nextItem=" + nextItem + " " +
1337     // "lastItem=" + lastItem + " " +
1338     // "prevCycles=" + prevCycles + " " +
1339     // "prevTakeIndex=" + prevTakeIndex + " " +
1340     // "size()=" + size() + " " +
1341     // "remainingCapacity()=" + remainingCapacity());
1342     // }
1343 tim 1.1 }
1344 dl 1.100
1345 jsr166 1.105 /**
1346     * Returns a {@link Spliterator} over the elements in this queue.
1347     *
1348 jsr166 1.106 * <p>The returned spliterator is
1349     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1350     *
1351 jsr166 1.105 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1352     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1353     *
1354     * @implNote
1355     * The {@code Spliterator} implements {@code trySplit} to permit limited
1356     * parallelism.
1357     *
1358     * @return a {@code Spliterator} over the elements in this queue
1359     * @since 1.8
1360     */
1361 dl 1.103 public Spliterator<E> spliterator() {
1362 dl 1.102 return Spliterators.spliterator
1363 jsr166 1.124 (this, (Spliterator.ORDERED |
1364     Spliterator.NONNULL |
1365     Spliterator.CONCURRENT));
1366 dl 1.100 }
1367    
1368 jsr166 1.127 public void forEach(Consumer<? super E> action) {
1369     Objects.requireNonNull(action);
1370     final ReentrantLock lock = this.lock;
1371     lock.lock();
1372     try {
1373     if (count > 0) {
1374     final Object[] items = this.items;
1375 jsr166 1.128 for (int i = takeIndex, end = putIndex,
1376     to = (i < end) ? end : items.length;
1377     ; i = 0, to = end) {
1378     for (; i < to; i++)
1379     action.accept(itemAt(items, i));
1380     if (to == end) break;
1381     }
1382 jsr166 1.127 }
1383     } finally {
1384     lock.unlock();
1385     }
1386     }
1387    
1388 jsr166 1.128 /** debugging */
1389     void checkInvariants() {
1390     // meta-assertion
1391     // assert lock.isHeldByCurrentThread();
1392     try {
1393     int capacity = items.length;
1394     // assert capacity > 0;
1395     // assert takeIndex >= 0 && takeIndex < capacity;
1396     // assert putIndex >= 0 && putIndex < capacity;
1397     // assert count <= capacity;
1398     // assert takeIndex == putIndex || items[takeIndex] != null;
1399     // assert count == capacity || items[putIndex] == null;
1400     // assert takeIndex == putIndex || items[dec(putIndex, capacity)] != null;
1401     } catch (Throwable t) {
1402     System.err.printf("takeIndex=%d putIndex=%d capacity=%d%n",
1403     takeIndex, putIndex, items.length);
1404     System.err.printf("items=%s%n",
1405     Arrays.toString(items));
1406     throw t;
1407     }
1408     }
1409    
1410 tim 1.1 }