ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.109
Committed: Tue Dec 2 05:48:28 2014 UTC (9 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.108: +1 -1 lines
Log Message:
this collection => this XXX

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