ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ArrayBlockingQueue.java
Revision: 1.135
Committed: Sun Nov 6 19:12:22 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.134: +104 -6 lines
Log Message:
Optimize removeIf/removeAll/retainAll, at least when no active iterators; code ported from ArrayDeque

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