ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.143
Committed: Thu Dec 8 05:05:37 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.142: +3 -0 lines
Log Message:
add javadoc for @inheritDoc

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