ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.151
Committed: Sat Jan 7 21:17:45 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.150: +2 -2 lines
Log Message:
skipDeadNodes: improve asserts

File Contents

# Content
1 /*
2 * Written by Doug Lea and Martin Buchholz with assistance from members of
3 * JCP JSR-166 Expert Group and released to the public domain, as explained
4 * at http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.util.AbstractQueue;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Iterator;
15 import java.util.NoSuchElementException;
16 import java.util.Objects;
17 import java.util.Queue;
18 import java.util.Spliterator;
19 import java.util.Spliterators;
20 import java.util.function.Consumer;
21 import java.util.function.Predicate;
22
23 /**
24 * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
25 * This queue orders elements FIFO (first-in-first-out).
26 * The <em>head</em> of the queue is that element that has been on the
27 * queue the longest time.
28 * The <em>tail</em> of the queue is that element that has been on the
29 * queue the shortest time. New elements
30 * are inserted at the tail of the queue, and the queue retrieval
31 * operations obtain elements at the head of the queue.
32 * A {@code ConcurrentLinkedQueue} is an appropriate choice when
33 * many threads will share access to a common collection.
34 * Like most other concurrent collection implementations, this class
35 * does not permit the use of {@code null} elements.
36 *
37 * <p>This implementation employs an efficient <em>non-blocking</em>
38 * algorithm based on one described in
39 * <a href="http://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf">
40 * Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue
41 * Algorithms</a> by Maged M. Michael and Michael L. Scott.
42 *
43 * <p>Iterators are <i>weakly consistent</i>, returning elements
44 * reflecting the state of the queue at some point at or since the
45 * creation of the iterator. They do <em>not</em> throw {@link
46 * java.util.ConcurrentModificationException}, and may proceed concurrently
47 * with other operations. Elements contained in the queue since the creation
48 * of the iterator will be returned exactly once.
49 *
50 * <p>Beware that, unlike in most collections, the {@code size} method
51 * is <em>NOT</em> a constant-time operation. Because of the
52 * asynchronous nature of these queues, determining the current number
53 * of elements requires a traversal of the elements, and so may report
54 * inaccurate results if this collection is modified during traversal.
55 *
56 * <p>Bulk operations that add, remove, or examine multiple elements,
57 * such as {@link #addAll}, {@link #removeIf} or {@link #forEach},
58 * are <em>not</em> guaranteed to be performed atomically.
59 * For example, a {@code forEach} traversal concurrent with an {@code
60 * addAll} operation might observe only some of the added elements.
61 *
62 * <p>This class and its iterator implement all of the <em>optional</em>
63 * methods of the {@link Queue} and {@link Iterator} interfaces.
64 *
65 * <p>Memory consistency effects: As with other concurrent
66 * collections, actions in a thread prior to placing an object into a
67 * {@code ConcurrentLinkedQueue}
68 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
69 * actions subsequent to the access or removal of that element from
70 * the {@code ConcurrentLinkedQueue} in another thread.
71 *
72 * <p>This class is a member of the
73 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
74 * Java Collections Framework</a>.
75 *
76 * @since 1.5
77 * @author Doug Lea
78 * @param <E> the type of elements held in this queue
79 */
80 public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
81 implements Queue<E>, java.io.Serializable {
82 private static final long serialVersionUID = 196745693267521676L;
83
84 /*
85 * This is a modification of the Michael & Scott algorithm,
86 * adapted for a garbage-collected environment, with support for
87 * interior node deletion (to support e.g. remove(Object)). For
88 * explanation, read the paper.
89 *
90 * Note that like most non-blocking algorithms in this package,
91 * this implementation relies on the fact that in garbage
92 * collected systems, there is no possibility of ABA problems due
93 * to recycled nodes, so there is no need to use "counted
94 * pointers" or related techniques seen in versions used in
95 * non-GC'ed settings.
96 *
97 * The fundamental invariants are:
98 * - There is exactly one (last) Node with a null next reference,
99 * which is CASed when enqueueing. This last Node can be
100 * reached in O(1) time from tail, but tail is merely an
101 * optimization - it can always be reached in O(N) time from
102 * head as well.
103 * - The elements contained in the queue are the non-null items in
104 * Nodes that are reachable from head. CASing the item
105 * reference of a Node to null atomically removes it from the
106 * queue. Reachability of all elements from head must remain
107 * true even in the case of concurrent modifications that cause
108 * head to advance. A dequeued Node may remain in use
109 * indefinitely due to creation of an Iterator or simply a
110 * poll() that has lost its time slice.
111 *
112 * The above might appear to imply that all Nodes are GC-reachable
113 * from a predecessor dequeued Node. That would cause two problems:
114 * - allow a rogue Iterator to cause unbounded memory retention
115 * - cause cross-generational linking of old Nodes to new Nodes if
116 * a Node was tenured while live, which generational GCs have a
117 * hard time dealing with, causing repeated major collections.
118 * However, only non-deleted Nodes need to be reachable from
119 * dequeued Nodes, and reachability does not necessarily have to
120 * be of the kind understood by the GC. We use the trick of
121 * linking a Node that has just been dequeued to itself. Such a
122 * self-link implicitly means to advance to head.
123 *
124 * Both head and tail are permitted to lag. In fact, failing to
125 * update them every time one could is a significant optimization
126 * (fewer CASes). As with LinkedTransferQueue (see the internal
127 * documentation for that class), we use a slack threshold of two;
128 * that is, we update head/tail when the current pointer appears
129 * to be two or more steps away from the first/last node.
130 *
131 * Since head and tail are updated concurrently and independently,
132 * it is possible for tail to lag behind head (why not)?
133 *
134 * CASing a Node's item reference to null atomically removes the
135 * element from the queue, leaving a "dead" node that should later
136 * be unlinked (but unlinking is merely an optimization).
137 * Interior element removal methods (other than Iterator.remove())
138 * keep track of the predecessor node during traversal so that the
139 * node can be CAS-unlinked. Some traversal methods try to unlink
140 * any deleted nodes encountered during traversal. See comments
141 * in bulkRemove.
142 *
143 * When constructing a Node (before enqueuing it) we avoid paying
144 * for a volatile write to item. This allows the cost of enqueue
145 * to be "one-and-a-half" CASes.
146 *
147 * Both head and tail may or may not point to a Node with a
148 * non-null item. If the queue is empty, all items must of course
149 * be null. Upon creation, both head and tail refer to a dummy
150 * Node with null item. Both head and tail are only updated using
151 * CAS, so they never regress, although again this is merely an
152 * optimization.
153 */
154
155 static final class Node<E> {
156 volatile E item;
157 volatile Node<E> next;
158 }
159
160 /**
161 * Returns a new node holding item. Uses relaxed write because item
162 * can only be seen after piggy-backing publication via CAS.
163 */
164 static <E> Node<E> newNode(E item) {
165 Node<E> node = new Node<E>();
166 ITEM.set(node, item);
167 return node;
168 }
169
170 /**
171 * A node from which the first live (non-deleted) node (if any)
172 * can be reached in O(1) time.
173 * Invariants:
174 * - all live nodes are reachable from head via succ()
175 * - head != null
176 * - (tmp = head).next != tmp || tmp != head
177 * Non-invariants:
178 * - head.item may or may not be null.
179 * - it is permitted for tail to lag behind head, that is, for tail
180 * to not be reachable from head!
181 */
182 transient volatile Node<E> head;
183
184 /**
185 * A node from which the last node on list (that is, the unique
186 * node with node.next == null) can be reached in O(1) time.
187 * Invariants:
188 * - the last node is always reachable from tail via succ()
189 * - tail != null
190 * Non-invariants:
191 * - tail.item may or may not be null.
192 * - it is permitted for tail to lag behind head, that is, for tail
193 * to not be reachable from head!
194 * - tail.next may or may not be self-pointing to tail.
195 */
196 private transient volatile Node<E> tail;
197
198 /**
199 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
200 */
201 public ConcurrentLinkedQueue() {
202 head = tail = newNode(null);
203 }
204
205 /**
206 * Creates a {@code ConcurrentLinkedQueue}
207 * initially containing the elements of the given collection,
208 * added in traversal order of the collection's iterator.
209 *
210 * @param c the collection of elements to initially contain
211 * @throws NullPointerException if the specified collection or any
212 * of its elements are null
213 */
214 public ConcurrentLinkedQueue(Collection<? extends E> c) {
215 Node<E> h = null, t = null;
216 for (E e : c) {
217 Node<E> newNode = newNode(Objects.requireNonNull(e));
218 if (h == null)
219 h = t = newNode;
220 else {
221 NEXT.set(t, newNode);
222 t = newNode;
223 }
224 }
225 if (h == null)
226 h = t = newNode(null);
227 head = h;
228 tail = t;
229 }
230
231 // Have to override just to update the javadoc
232
233 /**
234 * Inserts the specified element at the tail of this queue.
235 * As the queue is unbounded, this method will never throw
236 * {@link IllegalStateException} or return {@code false}.
237 *
238 * @return {@code true} (as specified by {@link Collection#add})
239 * @throws NullPointerException if the specified element is null
240 */
241 public boolean add(E e) {
242 return offer(e);
243 }
244
245 /**
246 * Tries to CAS head to p. If successful, repoint old head to itself
247 * as sentinel for succ(), below.
248 */
249 final void updateHead(Node<E> h, Node<E> p) {
250 // assert h != null && p != null && (h == p || h.item == null);
251 if (h != p && HEAD.compareAndSet(this, h, p))
252 NEXT.setRelease(h, h);
253 }
254
255 /**
256 * Returns the successor of p, or the head node if p.next has been
257 * linked to self, which will only be true if traversing with a
258 * stale pointer that is now off the list.
259 */
260 final Node<E> succ(Node<E> p) {
261 if (p == (p = p.next))
262 p = head;
263 return p;
264 }
265
266 /**
267 * Tries to CAS pred.next (or head, if pred is null) from c to p.
268 * Caller must ensure that we're not unlinking the trailing node.
269 */
270 private boolean tryCasSuccessor(Node<E> pred, Node<E> c, Node<E> p) {
271 // assert p != null;
272 // assert c.item == null;
273 // assert c != p;
274 if (pred != null)
275 return NEXT.compareAndSet(pred, c, p);
276 if (HEAD.compareAndSet(this, c, p)) {
277 NEXT.setRelease(c, c);
278 return true;
279 }
280 return false;
281 }
282
283 /**
284 * Collapse dead nodes between pred and q.
285 * @param pred the last known live node, or null if none
286 * @param c the first dead node
287 * @param p the last dead node
288 * @param q p.next: the next live node, or null if at end
289 * @return either old pred or p if pred dead or CAS failed
290 */
291 private Node<E> skipDeadNodes(Node<E> pred, Node<E> c, Node<E> p, Node<E> q) {
292 // assert pred != c;
293 // assert p != q;
294 // assert c.item == null;
295 // assert p.item == null;
296 if (q == null) {
297 // Never unlink trailing node.
298 if (c == p) return pred;
299 q = p;
300 }
301 return (tryCasSuccessor(pred, c, q)
302 && (pred == null || ITEM.get(pred) != null))
303 ? pred : p;
304 }
305
306 /**
307 * Inserts the specified element at the tail of this queue.
308 * As the queue is unbounded, this method will never return {@code false}.
309 *
310 * @return {@code true} (as specified by {@link Queue#offer})
311 * @throws NullPointerException if the specified element is null
312 */
313 public boolean offer(E e) {
314 final Node<E> newNode = newNode(Objects.requireNonNull(e));
315
316 for (Node<E> t = tail, p = t;;) {
317 Node<E> q = p.next;
318 if (q == null) {
319 // p is last node
320 if (NEXT.compareAndSet(p, null, newNode)) {
321 // Successful CAS is the linearization point
322 // for e to become an element of this queue,
323 // and for newNode to become "live".
324 if (p != t) // hop two nodes at a time; failure is OK
325 TAIL.weakCompareAndSet(this, t, newNode);
326 return true;
327 }
328 // Lost CAS race to another thread; re-read next
329 }
330 else if (p == q)
331 // We have fallen off list. If tail is unchanged, it
332 // will also be off-list, in which case we need to
333 // jump to head, from which all live nodes are always
334 // reachable. Else the new tail is a better bet.
335 p = (t != (t = tail)) ? t : head;
336 else
337 // Check for tail updates after two hops.
338 p = (p != t && t != (t = tail)) ? t : q;
339 }
340 }
341
342 public E poll() {
343 restartFromHead: for (;;) {
344 for (Node<E> h = head, p = h, q;; p = q) {
345 final E item;
346 if ((item = p.item) != null
347 && ITEM.compareAndSet(p, item, null)) {
348 // Successful CAS is the linearization point
349 // for item to be removed from this queue.
350 if (p != h) // hop two nodes at a time
351 updateHead(h, ((q = p.next) != null) ? q : p);
352 return item;
353 }
354 else if ((q = p.next) == null) {
355 updateHead(h, p);
356 return null;
357 }
358 else if (p == q)
359 continue restartFromHead;
360 }
361 }
362 }
363
364 public E peek() {
365 restartFromHead: for (;;) {
366 for (Node<E> h = head, p = h, q;; p = q) {
367 final E item;
368 if ((item = p.item) != null
369 || (q = p.next) == null) {
370 updateHead(h, p);
371 return item;
372 }
373 else if (p == q)
374 continue restartFromHead;
375 }
376 }
377 }
378
379 /**
380 * Returns the first live (non-deleted) node on list, or null if none.
381 * This is yet another variant of poll/peek; here returning the
382 * first node, not element. We could make peek() a wrapper around
383 * first(), but that would cost an extra volatile read of item,
384 * and the need to add a retry loop to deal with the possibility
385 * of losing a race to a concurrent poll().
386 */
387 Node<E> first() {
388 restartFromHead: for (;;) {
389 for (Node<E> h = head, p = h, q;; p = q) {
390 boolean hasItem = (p.item != null);
391 if (hasItem || (q = p.next) == null) {
392 updateHead(h, p);
393 return hasItem ? p : null;
394 }
395 else if (p == q)
396 continue restartFromHead;
397 }
398 }
399 }
400
401 /**
402 * Returns {@code true} if this queue contains no elements.
403 *
404 * @return {@code true} if this queue contains no elements
405 */
406 public boolean isEmpty() {
407 return first() == null;
408 }
409
410 /**
411 * Returns the number of elements in this queue. If this queue
412 * contains more than {@code Integer.MAX_VALUE} elements, returns
413 * {@code Integer.MAX_VALUE}.
414 *
415 * <p>Beware that, unlike in most collections, this method is
416 * <em>NOT</em> a constant-time operation. Because of the
417 * asynchronous nature of these queues, determining the current
418 * number of elements requires an O(n) traversal.
419 * Additionally, if elements are added or removed during execution
420 * of this method, the returned result may be inaccurate. Thus,
421 * this method is typically not very useful in concurrent
422 * applications.
423 *
424 * @return the number of elements in this queue
425 */
426 public int size() {
427 restartFromHead: for (;;) {
428 int count = 0;
429 for (Node<E> p = first(); p != null;) {
430 if (p.item != null)
431 if (++count == Integer.MAX_VALUE)
432 break; // @see Collection.size()
433 if (p == (p = p.next))
434 continue restartFromHead;
435 }
436 return count;
437 }
438 }
439
440 /**
441 * Returns {@code true} if this queue contains the specified element.
442 * More formally, returns {@code true} if and only if this queue contains
443 * at least one element {@code e} such that {@code o.equals(e)}.
444 *
445 * @param o object to be checked for containment in this queue
446 * @return {@code true} if this queue contains the specified element
447 */
448 public boolean contains(Object o) {
449 if (o == null) return false;
450 restartFromHead: for (;;) {
451 for (Node<E> p = head, pred = null; p != null; ) {
452 Node<E> q = p.next;
453 final E item;
454 if ((item = p.item) != null) {
455 if (o.equals(item))
456 return true;
457 pred = p; p = q; continue;
458 }
459 for (Node<E> c = p;;) {
460 if ((q = p.next) == null || q.item != null) {
461 pred = skipDeadNodes(pred, c, p, q); p = q; break;
462 }
463 if (p == (p = q)) continue restartFromHead;
464 }
465 }
466 return false;
467 }
468 }
469
470 /**
471 * Removes a single instance of the specified element from this queue,
472 * if it is present. More formally, removes an element {@code e} such
473 * that {@code o.equals(e)}, if this queue contains one or more such
474 * elements.
475 * Returns {@code true} if this queue contained the specified element
476 * (or equivalently, if this queue changed as a result of the call).
477 *
478 * @param o element to be removed from this queue, if present
479 * @return {@code true} if this queue changed as a result of the call
480 */
481 public boolean remove(Object o) {
482 if (o == null) return false;
483 restartFromHead: for (;;) {
484 for (Node<E> p = head, pred = null; p != null; ) {
485 Node<E> q = p.next;
486 final E item;
487 if ((item = p.item) != null) {
488 if (o.equals(item)
489 && ITEM.compareAndSet(p, item, null)) {
490 skipDeadNodes(pred, p, p, q);
491 return true;
492 }
493 pred = p; p = q; continue;
494 }
495 for (Node<E> c = p;;) {
496 if ((q = p.next) == null || q.item != null) {
497 pred = skipDeadNodes(pred, c, p, q); p = q; break;
498 }
499 if (p == (p = q)) continue restartFromHead;
500 }
501 }
502 return false;
503 }
504 }
505
506 /**
507 * Appends all of the elements in the specified collection to the end of
508 * this queue, in the order that they are returned by the specified
509 * collection's iterator. Attempts to {@code addAll} of a queue to
510 * itself result in {@code IllegalArgumentException}.
511 *
512 * @param c the elements to be inserted into this queue
513 * @return {@code true} if this queue changed as a result of the call
514 * @throws NullPointerException if the specified collection or any
515 * of its elements are null
516 * @throws IllegalArgumentException if the collection is this queue
517 */
518 public boolean addAll(Collection<? extends E> c) {
519 if (c == this)
520 // As historically specified in AbstractQueue#addAll
521 throw new IllegalArgumentException();
522
523 // Copy c into a private chain of Nodes
524 Node<E> beginningOfTheEnd = null, last = null;
525 for (E e : c) {
526 Node<E> newNode = newNode(Objects.requireNonNull(e));
527 if (beginningOfTheEnd == null)
528 beginningOfTheEnd = last = newNode;
529 else {
530 NEXT.set(last, newNode);
531 last = newNode;
532 }
533 }
534 if (beginningOfTheEnd == null)
535 return false;
536
537 // Atomically append the chain at the tail of this collection
538 for (Node<E> t = tail, p = t;;) {
539 Node<E> q = p.next;
540 if (q == null) {
541 // p is last node
542 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
543 // Successful CAS is the linearization point
544 // for all elements to be added to this queue.
545 if (!TAIL.weakCompareAndSet(this, t, last)) {
546 // Try a little harder to update tail,
547 // since we may be adding many elements.
548 t = tail;
549 if (last.next == null)
550 TAIL.weakCompareAndSet(this, t, last);
551 }
552 return true;
553 }
554 // Lost CAS race to another thread; re-read next
555 }
556 else if (p == q)
557 // We have fallen off list. If tail is unchanged, it
558 // will also be off-list, in which case we need to
559 // jump to head, from which all live nodes are always
560 // reachable. Else the new tail is a better bet.
561 p = (t != (t = tail)) ? t : head;
562 else
563 // Check for tail updates after two hops.
564 p = (p != t && t != (t = tail)) ? t : q;
565 }
566 }
567
568 public String toString() {
569 String[] a = null;
570 restartFromHead: for (;;) {
571 int charLength = 0;
572 int size = 0;
573 for (Node<E> p = first(); p != null;) {
574 final E item;
575 if ((item = p.item) != null) {
576 if (a == null)
577 a = new String[4];
578 else if (size == a.length)
579 a = Arrays.copyOf(a, 2 * size);
580 String s = item.toString();
581 a[size++] = s;
582 charLength += s.length();
583 }
584 if (p == (p = p.next))
585 continue restartFromHead;
586 }
587
588 if (size == 0)
589 return "[]";
590
591 return Helpers.toString(a, size, charLength);
592 }
593 }
594
595 private Object[] toArrayInternal(Object[] a) {
596 Object[] x = a;
597 restartFromHead: for (;;) {
598 int size = 0;
599 for (Node<E> p = first(); p != null;) {
600 final E item;
601 if ((item = p.item) != null) {
602 if (x == null)
603 x = new Object[4];
604 else if (size == x.length)
605 x = Arrays.copyOf(x, 2 * (size + 4));
606 x[size++] = item;
607 }
608 if (p == (p = p.next))
609 continue restartFromHead;
610 }
611 if (x == null)
612 return new Object[0];
613 else if (a != null && size <= a.length) {
614 if (a != x)
615 System.arraycopy(x, 0, a, 0, size);
616 if (size < a.length)
617 a[size] = null;
618 return a;
619 }
620 return (size == x.length) ? x : Arrays.copyOf(x, size);
621 }
622 }
623
624 /**
625 * Returns an array containing all of the elements in this queue, in
626 * proper sequence.
627 *
628 * <p>The returned array will be "safe" in that no references to it are
629 * maintained by this queue. (In other words, this method must allocate
630 * a new array). The caller is thus free to modify the returned array.
631 *
632 * <p>This method acts as bridge between array-based and collection-based
633 * APIs.
634 *
635 * @return an array containing all of the elements in this queue
636 */
637 public Object[] toArray() {
638 return toArrayInternal(null);
639 }
640
641 /**
642 * Returns an array containing all of the elements in this queue, in
643 * proper sequence; the runtime type of the returned array is that of
644 * the specified array. If the queue fits in the specified array, it
645 * is returned therein. Otherwise, a new array is allocated with the
646 * runtime type of the specified array and the size of this queue.
647 *
648 * <p>If this queue fits in the specified array with room to spare
649 * (i.e., the array has more elements than this queue), the element in
650 * the array immediately following the end of the queue is set to
651 * {@code null}.
652 *
653 * <p>Like the {@link #toArray()} method, this method acts as bridge between
654 * array-based and collection-based APIs. Further, this method allows
655 * precise control over the runtime type of the output array, and may,
656 * under certain circumstances, be used to save allocation costs.
657 *
658 * <p>Suppose {@code x} is a queue known to contain only strings.
659 * The following code can be used to dump the queue into a newly
660 * allocated array of {@code String}:
661 *
662 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
663 *
664 * Note that {@code toArray(new Object[0])} is identical in function to
665 * {@code toArray()}.
666 *
667 * @param a the array into which the elements of the queue are to
668 * be stored, if it is big enough; otherwise, a new array of the
669 * same runtime type is allocated for this purpose
670 * @return an array containing all of the elements in this queue
671 * @throws ArrayStoreException if the runtime type of the specified array
672 * is not a supertype of the runtime type of every element in
673 * this queue
674 * @throws NullPointerException if the specified array is null
675 */
676 @SuppressWarnings("unchecked")
677 public <T> T[] toArray(T[] a) {
678 Objects.requireNonNull(a);
679 return (T[]) toArrayInternal(a);
680 }
681
682 /**
683 * Returns an iterator over the elements in this queue in proper sequence.
684 * The elements will be returned in order from first (head) to last (tail).
685 *
686 * <p>The returned iterator is
687 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
688 *
689 * @return an iterator over the elements in this queue in proper sequence
690 */
691 public Iterator<E> iterator() {
692 return new Itr();
693 }
694
695 private class Itr implements Iterator<E> {
696 /**
697 * Next node to return item for.
698 */
699 private Node<E> nextNode;
700
701 /**
702 * nextItem holds on to item fields because once we claim
703 * that an element exists in hasNext(), we must return it in
704 * the following next() call even if it was in the process of
705 * being removed when hasNext() was called.
706 */
707 private E nextItem;
708
709 /**
710 * Node of the last returned item, to support remove.
711 */
712 private Node<E> lastRet;
713
714 Itr() {
715 restartFromHead: for (;;) {
716 Node<E> h, p, q;
717 for (p = h = head;; p = q) {
718 final E item;
719 if ((item = p.item) != null) {
720 nextNode = p;
721 nextItem = item;
722 break;
723 }
724 else if ((q = p.next) == null)
725 break;
726 else if (p == q)
727 continue restartFromHead;
728 }
729 updateHead(h, p);
730 return;
731 }
732 }
733
734 public boolean hasNext() {
735 return nextItem != null;
736 }
737
738 public E next() {
739 final Node<E> pred = nextNode;
740 if (pred == null) throw new NoSuchElementException();
741 // assert nextItem != null;
742 lastRet = pred;
743 E item = null;
744
745 for (Node<E> p = succ(pred), q;; p = q) {
746 if (p == null || (item = p.item) != null) {
747 nextNode = p;
748 E x = nextItem;
749 nextItem = item;
750 return x;
751 }
752 // unlink deleted nodes
753 if ((q = succ(p)) != null)
754 NEXT.compareAndSet(pred, p, q);
755 }
756 }
757
758 // Default implementation of forEachRemaining is "good enough".
759
760 public void remove() {
761 Node<E> l = lastRet;
762 if (l == null) throw new IllegalStateException();
763 // rely on a future traversal to relink.
764 l.item = null;
765 lastRet = null;
766 }
767 }
768
769 /**
770 * Saves this queue to a stream (that is, serializes it).
771 *
772 * @param s the stream
773 * @throws java.io.IOException if an I/O error occurs
774 * @serialData All of the elements (each an {@code E}) in
775 * the proper order, followed by a null
776 */
777 private void writeObject(java.io.ObjectOutputStream s)
778 throws java.io.IOException {
779
780 // Write out any hidden stuff
781 s.defaultWriteObject();
782
783 // Write out all elements in the proper order.
784 for (Node<E> p = first(); p != null; p = succ(p)) {
785 final E item;
786 if ((item = p.item) != null)
787 s.writeObject(item);
788 }
789
790 // Use trailing null as sentinel
791 s.writeObject(null);
792 }
793
794 /**
795 * Reconstitutes this queue from a stream (that is, deserializes it).
796 * @param s the stream
797 * @throws ClassNotFoundException if the class of a serialized object
798 * could not be found
799 * @throws java.io.IOException if an I/O error occurs
800 */
801 private void readObject(java.io.ObjectInputStream s)
802 throws java.io.IOException, ClassNotFoundException {
803 s.defaultReadObject();
804
805 // Read in elements until trailing null sentinel found
806 Node<E> h = null, t = null;
807 for (Object item; (item = s.readObject()) != null; ) {
808 @SuppressWarnings("unchecked")
809 Node<E> newNode = newNode((E) item);
810 if (h == null)
811 h = t = newNode;
812 else {
813 NEXT.set(t, newNode);
814 t = newNode;
815 }
816 }
817 if (h == null)
818 h = t = newNode(null);
819 head = h;
820 tail = t;
821 }
822
823 /** A customized variant of Spliterators.IteratorSpliterator */
824 final class CLQSpliterator implements Spliterator<E> {
825 static final int MAX_BATCH = 1 << 25; // max batch array size;
826 Node<E> current; // current node; null until initialized
827 int batch; // batch size for splits
828 boolean exhausted; // true when no more nodes
829
830 public Spliterator<E> trySplit() {
831 Node<E> p, q;
832 if ((p = current()) == null || (q = p.next) == null)
833 return null;
834 int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
835 Object[] a = null;
836 do {
837 final E e;
838 if ((e = p.item) != null)
839 ((a != null) ? a : (a = new Object[n]))[i++] = e;
840 if (p == (p = q))
841 p = first();
842 } while (p != null && (q = p.next) != null && i < n);
843 setCurrent(p);
844 return (i == 0) ? null :
845 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
846 Spliterator.NONNULL |
847 Spliterator.CONCURRENT));
848 }
849
850 public void forEachRemaining(Consumer<? super E> action) {
851 Objects.requireNonNull(action);
852 final Node<E> p;
853 if ((p = current()) != null) {
854 current = null;
855 exhausted = true;
856 forEachFrom(action, p);
857 }
858 }
859
860 public boolean tryAdvance(Consumer<? super E> action) {
861 Objects.requireNonNull(action);
862 Node<E> p;
863 if ((p = current()) != null) {
864 E e;
865 do {
866 e = p.item;
867 if (p == (p = p.next))
868 p = first();
869 } while (e == null && p != null);
870 setCurrent(p);
871 if (e != null) {
872 action.accept(e);
873 return true;
874 }
875 }
876 return false;
877 }
878
879 private void setCurrent(Node<E> p) {
880 if ((current = p) == null)
881 exhausted = true;
882 }
883
884 private Node<E> current() {
885 Node<E> p;
886 if ((p = current) == null && !exhausted)
887 setCurrent(p = first());
888 return p;
889 }
890
891 public long estimateSize() { return Long.MAX_VALUE; }
892
893 public int characteristics() {
894 return (Spliterator.ORDERED |
895 Spliterator.NONNULL |
896 Spliterator.CONCURRENT);
897 }
898 }
899
900 /**
901 * Returns a {@link Spliterator} over the elements in this queue.
902 *
903 * <p>The returned spliterator is
904 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
905 *
906 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
907 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
908 *
909 * @implNote
910 * The {@code Spliterator} implements {@code trySplit} to permit limited
911 * parallelism.
912 *
913 * @return a {@code Spliterator} over the elements in this queue
914 * @since 1.8
915 */
916 @Override
917 public Spliterator<E> spliterator() {
918 return new CLQSpliterator();
919 }
920
921 /**
922 * @throws NullPointerException {@inheritDoc}
923 */
924 public boolean removeIf(Predicate<? super E> filter) {
925 Objects.requireNonNull(filter);
926 return bulkRemove(filter);
927 }
928
929 /**
930 * @throws NullPointerException {@inheritDoc}
931 */
932 public boolean removeAll(Collection<?> c) {
933 Objects.requireNonNull(c);
934 return bulkRemove(e -> c.contains(e));
935 }
936
937 /**
938 * @throws NullPointerException {@inheritDoc}
939 */
940 public boolean retainAll(Collection<?> c) {
941 Objects.requireNonNull(c);
942 return bulkRemove(e -> !c.contains(e));
943 }
944
945 public void clear() {
946 bulkRemove(e -> true);
947 }
948
949 /**
950 * Tolerate this many consecutive dead nodes before CAS-collapsing.
951 * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
952 */
953 private static final int MAX_HOPS = 8;
954
955 /** Implementation of bulk remove methods. */
956 private boolean bulkRemove(Predicate<? super E> filter) {
957 boolean removed = false;
958 restartFromHead: for (;;) {
959 int hops = MAX_HOPS;
960 // c will be CASed to collapse intervening dead nodes between
961 // pred (or head if null) and p.
962 for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
963 final E item; boolean pAlive;
964 if (pAlive = ((item = p.item) != null)) {
965 if (filter.test(item)) {
966 if (ITEM.compareAndSet(p, item, null))
967 removed = true;
968 pAlive = false;
969 }
970 }
971 if ((q = p.next) == null || pAlive || --hops == 0) {
972 // p might already be self-linked here, but if so:
973 // - CASing head will surely fail
974 // - CASing pred's next will be useless but harmless.
975 if ((c != p && !tryCasSuccessor(pred, c, c = p))
976 || pAlive) {
977 // if CAS failed or alive, abandon old pred
978 hops = MAX_HOPS;
979 pred = p;
980 c = q;
981 }
982 } else if (p == q)
983 continue restartFromHead;
984 }
985 return removed;
986 }
987 }
988
989 /**
990 * Runs action on each element found during a traversal starting at p.
991 * If p is null, the action is not run.
992 */
993 void forEachFrom(Consumer<? super E> action, Node<E> p) {
994 for (Node<E> pred = null; p != null; ) {
995 Node<E> q = p.next;
996 final E item;
997 if ((item = p.item) != null) {
998 action.accept(item);
999 pred = p; p = q; continue;
1000 }
1001 for (Node<E> c = p;;) {
1002 if ((q = p.next) == null || q.item != null) {
1003 pred = skipDeadNodes(pred, c, p, q); p = q; break;
1004 }
1005 if (p == (p = q)) { pred = null; p = head; break; }
1006 }
1007 }
1008 }
1009
1010 /**
1011 * @throws NullPointerException {@inheritDoc}
1012 */
1013 public void forEach(Consumer<? super E> action) {
1014 Objects.requireNonNull(action);
1015 forEachFrom(action, head);
1016 }
1017
1018 // VarHandle mechanics
1019 private static final VarHandle HEAD;
1020 private static final VarHandle TAIL;
1021 private static final VarHandle ITEM;
1022 private static final VarHandle NEXT;
1023 static {
1024 try {
1025 MethodHandles.Lookup l = MethodHandles.lookup();
1026 HEAD = l.findVarHandle(ConcurrentLinkedQueue.class, "head",
1027 Node.class);
1028 TAIL = l.findVarHandle(ConcurrentLinkedQueue.class, "tail",
1029 Node.class);
1030 ITEM = l.findVarHandle(Node.class, "item", Object.class);
1031 NEXT = l.findVarHandle(Node.class, "next", Node.class);
1032 } catch (ReflectiveOperationException e) {
1033 throw new Error(e);
1034 }
1035 }
1036 }