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