ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.114
Committed: Mon Feb 9 05:29:53 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.113: +4 -5 lines
Log Message:
small improvement in bytecode quality

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