ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.100
Committed: Sun Feb 17 23:36:34 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.99: +51 -21 lines
Log Message:
Spliterator sync

File Contents

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