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

File Contents

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