ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.113
Committed: Mon Feb 9 04:49:25 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.112: +1 -1 lines
Log Message:
javadoc style

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