ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.111
Committed: Wed Dec 31 09:37:20 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.110: +0 -2 lines
Log Message:
remove unused/redundant imports

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