ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.140
Committed: Wed Dec 28 04:57:36 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.139: +3 -2 lines
Log Message:
succ: bytecode golf

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 * Additionally, the bulk operations {@code addAll},
56 * {@code removeAll}, {@code retainAll}, {@code containsAll},
57 * and {@code toArray} are <em>not</em> guaranteed
58 * to be performed atomically. For example, an iterator operating
59 * concurrently with an {@code addAll} operation might view only some
60 * 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 */
269 private boolean tryCasSuccessor(Node<E> pred, Node<E> c, Node<E> p) {
270 // assert c.item == null;
271 // assert c != p;
272 if (pred != null)
273 return NEXT.compareAndSet(pred, c, p);
274 if (HEAD.compareAndSet(this, c, p)) {
275 NEXT.setRelease(c, c);
276 return true;
277 }
278 return false;
279 }
280
281 /**
282 * Inserts the specified element at the tail of this queue.
283 * As the queue is unbounded, this method will never return {@code false}.
284 *
285 * @return {@code true} (as specified by {@link Queue#offer})
286 * @throws NullPointerException if the specified element is null
287 */
288 public boolean offer(E e) {
289 final Node<E> newNode = newNode(Objects.requireNonNull(e));
290
291 for (Node<E> t = tail, p = t;;) {
292 Node<E> q = p.next;
293 if (q == null) {
294 // p is last node
295 if (NEXT.compareAndSet(p, null, newNode)) {
296 // Successful CAS is the linearization point
297 // for e to become an element of this queue,
298 // and for newNode to become "live".
299 if (p != t) // hop two nodes at a time; failure is OK
300 TAIL.weakCompareAndSet(this, t, newNode);
301 return true;
302 }
303 // Lost CAS race to another thread; re-read next
304 }
305 else if (p == q)
306 // We have fallen off list. If tail is unchanged, it
307 // will also be off-list, in which case we need to
308 // jump to head, from which all live nodes are always
309 // reachable. Else the new tail is a better bet.
310 p = (t != (t = tail)) ? t : head;
311 else
312 // Check for tail updates after two hops.
313 p = (p != t && t != (t = tail)) ? t : q;
314 }
315 }
316
317 public E poll() {
318 restartFromHead: for (;;) {
319 for (Node<E> h = head, p = h, q;; p = q) {
320 final E item;
321 if ((item = p.item) != null
322 && ITEM.compareAndSet(p, item, null)) {
323 // Successful CAS is the linearization point
324 // for item to be removed from this queue.
325 if (p != h) // hop two nodes at a time
326 updateHead(h, ((q = p.next) != null) ? q : p);
327 return item;
328 }
329 else if ((q = p.next) == null) {
330 updateHead(h, p);
331 return null;
332 }
333 else if (p == q)
334 continue restartFromHead;
335 }
336 }
337 }
338
339 public E peek() {
340 restartFromHead: for (;;) {
341 for (Node<E> h = head, p = h, q;; p = q) {
342 final E item;
343 if ((item = p.item) != null
344 || (q = p.next) == null) {
345 updateHead(h, p);
346 return item;
347 }
348 else if (p == q)
349 continue restartFromHead;
350 }
351 }
352 }
353
354 /**
355 * Returns the first live (non-deleted) node on list, or null if none.
356 * This is yet another variant of poll/peek; here returning the
357 * first node, not element. We could make peek() a wrapper around
358 * first(), but that would cost an extra volatile read of item,
359 * and the need to add a retry loop to deal with the possibility
360 * of losing a race to a concurrent poll().
361 */
362 Node<E> first() {
363 restartFromHead: for (;;) {
364 for (Node<E> h = head, p = h, q;; p = q) {
365 boolean hasItem = (p.item != null);
366 if (hasItem || (q = p.next) == null) {
367 updateHead(h, p);
368 return hasItem ? p : null;
369 }
370 else if (p == q)
371 continue restartFromHead;
372 }
373 }
374 }
375
376 /**
377 * Returns {@code true} if this queue contains no elements.
378 *
379 * @return {@code true} if this queue contains no elements
380 */
381 public boolean isEmpty() {
382 return first() == null;
383 }
384
385 /**
386 * Returns the number of elements in this queue. If this queue
387 * contains more than {@code Integer.MAX_VALUE} elements, returns
388 * {@code Integer.MAX_VALUE}.
389 *
390 * <p>Beware that, unlike in most collections, this method is
391 * <em>NOT</em> a constant-time operation. Because of the
392 * asynchronous nature of these queues, determining the current
393 * number of elements requires an O(n) traversal.
394 * Additionally, if elements are added or removed during execution
395 * of this method, the returned result may be inaccurate. Thus,
396 * this method is typically not very useful in concurrent
397 * applications.
398 *
399 * @return the number of elements in this queue
400 */
401 public int size() {
402 restartFromHead: for (;;) {
403 int count = 0;
404 for (Node<E> p = first(); p != null;) {
405 if (p.item != null)
406 if (++count == Integer.MAX_VALUE)
407 break; // @see Collection.size()
408 if (p == (p = p.next))
409 continue restartFromHead;
410 }
411 return count;
412 }
413 }
414
415 /**
416 * Returns {@code true} if this queue contains the specified element.
417 * More formally, returns {@code true} if and only if this queue contains
418 * at least one element {@code e} such that {@code o.equals(e)}.
419 *
420 * @param o object to be checked for containment in this queue
421 * @return {@code true} if this queue contains the specified element
422 */
423 public boolean contains(Object o) {
424 if (o == null) return false;
425 restartFromHead: for (;;) {
426 for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
427 final E item;
428 if ((item = p.item) != null && o.equals(item))
429 return true;
430 if (c != p && tryCasSuccessor(pred, c, p))
431 c = p;
432 q = p.next;
433 if (item != null || c != p) {
434 pred = p;
435 c = q;
436 }
437 else if (p == q)
438 continue restartFromHead;
439 }
440 return false;
441 }
442 }
443
444 /**
445 * Removes a single instance of the specified element from this queue,
446 * if it is present. More formally, removes an element {@code e} such
447 * that {@code o.equals(e)}, if this queue contains one or more such
448 * elements.
449 * Returns {@code true} if this queue contained the specified element
450 * (or equivalently, if this queue changed as a result of the call).
451 *
452 * @param o element to be removed from this queue, if present
453 * @return {@code true} if this queue changed as a result of the call
454 */
455 public boolean remove(Object o) {
456 if (o == null) return false;
457 restartFromHead: for (;;) {
458 for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
459 final E item;
460 final boolean removed =
461 (item = p.item) != null
462 && o.equals(item)
463 && ITEM.compareAndSet(p, item, null);
464 if (c != p && tryCasSuccessor(pred, c, p))
465 c = p;
466 if (removed)
467 return true;
468 q = p.next;
469 if (item != null || c != p) {
470 pred = p;
471 c = q;
472 }
473 else if (p == q)
474 continue restartFromHead;
475 }
476 return false;
477 }
478 }
479
480 /**
481 * Appends all of the elements in the specified collection to the end of
482 * this queue, in the order that they are returned by the specified
483 * collection's iterator. Attempts to {@code addAll} of a queue to
484 * itself result in {@code IllegalArgumentException}.
485 *
486 * @param c the elements to be inserted into this queue
487 * @return {@code true} if this queue changed as a result of the call
488 * @throws NullPointerException if the specified collection or any
489 * of its elements are null
490 * @throws IllegalArgumentException if the collection is this queue
491 */
492 public boolean addAll(Collection<? extends E> c) {
493 if (c == this)
494 // As historically specified in AbstractQueue#addAll
495 throw new IllegalArgumentException();
496
497 // Copy c into a private chain of Nodes
498 Node<E> beginningOfTheEnd = null, last = null;
499 for (E e : c) {
500 Node<E> newNode = newNode(Objects.requireNonNull(e));
501 if (beginningOfTheEnd == null)
502 beginningOfTheEnd = last = newNode;
503 else {
504 NEXT.set(last, newNode);
505 last = newNode;
506 }
507 }
508 if (beginningOfTheEnd == null)
509 return false;
510
511 // Atomically append the chain at the tail of this collection
512 for (Node<E> t = tail, p = t;;) {
513 Node<E> q = p.next;
514 if (q == null) {
515 // p is last node
516 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
517 // Successful CAS is the linearization point
518 // for all elements to be added to this queue.
519 if (!TAIL.weakCompareAndSet(this, t, last)) {
520 // Try a little harder to update tail,
521 // since we may be adding many elements.
522 t = tail;
523 if (last.next == null)
524 TAIL.weakCompareAndSet(this, t, last);
525 }
526 return true;
527 }
528 // Lost CAS race to another thread; re-read next
529 }
530 else if (p == q)
531 // We have fallen off list. If tail is unchanged, it
532 // will also be off-list, in which case we need to
533 // jump to head, from which all live nodes are always
534 // reachable. Else the new tail is a better bet.
535 p = (t != (t = tail)) ? t : head;
536 else
537 // Check for tail updates after two hops.
538 p = (p != t && t != (t = tail)) ? t : q;
539 }
540 }
541
542 public String toString() {
543 String[] a = null;
544 restartFromHead: for (;;) {
545 int charLength = 0;
546 int size = 0;
547 for (Node<E> p = first(); p != null;) {
548 final E item;
549 if ((item = p.item) != null) {
550 if (a == null)
551 a = new String[4];
552 else if (size == a.length)
553 a = Arrays.copyOf(a, 2 * size);
554 String s = item.toString();
555 a[size++] = s;
556 charLength += s.length();
557 }
558 if (p == (p = p.next))
559 continue restartFromHead;
560 }
561
562 if (size == 0)
563 return "[]";
564
565 return Helpers.toString(a, size, charLength);
566 }
567 }
568
569 private Object[] toArrayInternal(Object[] a) {
570 Object[] x = a;
571 restartFromHead: for (;;) {
572 int size = 0;
573 for (Node<E> p = first(); p != null;) {
574 final E item;
575 if ((item = p.item) != null) {
576 if (x == null)
577 x = new Object[4];
578 else if (size == x.length)
579 x = Arrays.copyOf(x, 2 * (size + 4));
580 x[size++] = item;
581 }
582 if (p == (p = p.next))
583 continue restartFromHead;
584 }
585 if (x == null)
586 return new Object[0];
587 else if (a != null && size <= a.length) {
588 if (a != x)
589 System.arraycopy(x, 0, a, 0, size);
590 if (size < a.length)
591 a[size] = null;
592 return a;
593 }
594 return (size == x.length) ? x : Arrays.copyOf(x, size);
595 }
596 }
597
598 /**
599 * Returns an array containing all of the elements in this queue, in
600 * proper sequence.
601 *
602 * <p>The returned array will be "safe" in that no references to it are
603 * maintained by this queue. (In other words, this method must allocate
604 * a new array). The caller is thus free to modify the returned array.
605 *
606 * <p>This method acts as bridge between array-based and collection-based
607 * APIs.
608 *
609 * @return an array containing all of the elements in this queue
610 */
611 public Object[] toArray() {
612 return toArrayInternal(null);
613 }
614
615 /**
616 * Returns an array containing all of the elements in this queue, in
617 * proper sequence; the runtime type of the returned array is that of
618 * the specified array. If the queue fits in the specified array, it
619 * is returned therein. Otherwise, a new array is allocated with the
620 * runtime type of the specified array and the size of this queue.
621 *
622 * <p>If this queue fits in the specified array with room to spare
623 * (i.e., the array has more elements than this queue), the element in
624 * the array immediately following the end of the queue is set to
625 * {@code null}.
626 *
627 * <p>Like the {@link #toArray()} method, this method acts as bridge between
628 * array-based and collection-based APIs. Further, this method allows
629 * precise control over the runtime type of the output array, and may,
630 * under certain circumstances, be used to save allocation costs.
631 *
632 * <p>Suppose {@code x} is a queue known to contain only strings.
633 * The following code can be used to dump the queue into a newly
634 * allocated array of {@code String}:
635 *
636 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
637 *
638 * Note that {@code toArray(new Object[0])} is identical in function to
639 * {@code toArray()}.
640 *
641 * @param a the array into which the elements of the queue are to
642 * be stored, if it is big enough; otherwise, a new array of the
643 * same runtime type is allocated for this purpose
644 * @return an array containing all of the elements in this queue
645 * @throws ArrayStoreException if the runtime type of the specified array
646 * is not a supertype of the runtime type of every element in
647 * this queue
648 * @throws NullPointerException if the specified array is null
649 */
650 @SuppressWarnings("unchecked")
651 public <T> T[] toArray(T[] a) {
652 Objects.requireNonNull(a);
653 return (T[]) toArrayInternal(a);
654 }
655
656 /**
657 * Returns an iterator over the elements in this queue in proper sequence.
658 * The elements will be returned in order from first (head) to last (tail).
659 *
660 * <p>The returned iterator is
661 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
662 *
663 * @return an iterator over the elements in this queue in proper sequence
664 */
665 public Iterator<E> iterator() {
666 return new Itr();
667 }
668
669 private class Itr implements Iterator<E> {
670 /**
671 * Next node to return item for.
672 */
673 private Node<E> nextNode;
674
675 /**
676 * nextItem holds on to item fields because once we claim
677 * that an element exists in hasNext(), we must return it in
678 * the following next() call even if it was in the process of
679 * being removed when hasNext() was called.
680 */
681 private E nextItem;
682
683 /**
684 * Node of the last returned item, to support remove.
685 */
686 private Node<E> lastRet;
687
688 Itr() {
689 restartFromHead: for (;;) {
690 Node<E> h, p, q;
691 for (p = h = head;; p = q) {
692 final E item;
693 if ((item = p.item) != null) {
694 nextNode = p;
695 nextItem = item;
696 break;
697 }
698 else if ((q = p.next) == null)
699 break;
700 else if (p == q)
701 continue restartFromHead;
702 }
703 updateHead(h, p);
704 return;
705 }
706 }
707
708 public boolean hasNext() {
709 return nextItem != null;
710 }
711
712 public E next() {
713 final Node<E> pred = nextNode;
714 if (pred == null) throw new NoSuchElementException();
715 // assert nextItem != null;
716 lastRet = pred;
717 E item = null;
718
719 for (Node<E> p = succ(pred), q;; p = q) {
720 if (p == null || (item = p.item) != null) {
721 nextNode = p;
722 E x = nextItem;
723 nextItem = item;
724 return x;
725 }
726 // unlink deleted nodes
727 if ((q = succ(p)) != null)
728 NEXT.compareAndSet(pred, p, q);
729 }
730 }
731
732 public void remove() {
733 Node<E> l = lastRet;
734 if (l == null) throw new IllegalStateException();
735 // rely on a future traversal to relink.
736 l.item = null;
737 lastRet = null;
738 }
739 }
740
741 /**
742 * Saves this queue to a stream (that is, serializes it).
743 *
744 * @param s the stream
745 * @throws java.io.IOException if an I/O error occurs
746 * @serialData All of the elements (each an {@code E}) in
747 * the proper order, followed by a null
748 */
749 private void writeObject(java.io.ObjectOutputStream s)
750 throws java.io.IOException {
751
752 // Write out any hidden stuff
753 s.defaultWriteObject();
754
755 // Write out all elements in the proper order.
756 for (Node<E> p = first(); p != null; p = succ(p)) {
757 final E item;
758 if ((item = p.item) != null)
759 s.writeObject(item);
760 }
761
762 // Use trailing null as sentinel
763 s.writeObject(null);
764 }
765
766 /**
767 * Reconstitutes this queue from a stream (that is, deserializes it).
768 * @param s the stream
769 * @throws ClassNotFoundException if the class of a serialized object
770 * could not be found
771 * @throws java.io.IOException if an I/O error occurs
772 */
773 private void readObject(java.io.ObjectInputStream s)
774 throws java.io.IOException, ClassNotFoundException {
775 s.defaultReadObject();
776
777 // Read in elements until trailing null sentinel found
778 Node<E> h = null, t = null;
779 for (Object item; (item = s.readObject()) != null; ) {
780 @SuppressWarnings("unchecked")
781 Node<E> newNode = newNode((E) item);
782 if (h == null)
783 h = t = newNode;
784 else {
785 NEXT.set(t, newNode);
786 t = newNode;
787 }
788 }
789 if (h == null)
790 h = t = newNode(null);
791 head = h;
792 tail = t;
793 }
794
795 /** A customized variant of Spliterators.IteratorSpliterator */
796 final class CLQSpliterator implements Spliterator<E> {
797 static final int MAX_BATCH = 1 << 25; // max batch array size;
798 Node<E> current; // current node; null until initialized
799 int batch; // batch size for splits
800 boolean exhausted; // true when no more nodes
801
802 public Spliterator<E> trySplit() {
803 Node<E> p, q;
804 if ((p = current()) == null || (q = p.next) == null)
805 return null;
806 int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
807 Object[] a = null;
808 do {
809 final E e;
810 if ((e = p.item) != null)
811 ((a != null) ? a : (a = new Object[n]))[i++] = e;
812 if (p == (p = q))
813 p = first();
814 } while (p != null && (q = p.next) != null && i < n);
815 setCurrent(p);
816 return (i == 0) ? null :
817 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
818 Spliterator.NONNULL |
819 Spliterator.CONCURRENT));
820 }
821
822 public void forEachRemaining(Consumer<? super E> action) {
823 Objects.requireNonNull(action);
824 Node<E> p;
825 if ((p = current()) != null) {
826 current = null;
827 exhausted = true;
828 do {
829 final E e;
830 if ((e = p.item) != null)
831 action.accept(e);
832 if (p == (p = p.next))
833 p = first();
834 } while (p != null);
835 }
836 }
837
838 public boolean tryAdvance(Consumer<? super E> action) {
839 Objects.requireNonNull(action);
840 Node<E> p;
841 if ((p = current()) != null) {
842 E e;
843 do {
844 e = p.item;
845 if (p == (p = p.next))
846 p = first();
847 } while (e == null && p != null);
848 setCurrent(p);
849 if (e != null) {
850 action.accept(e);
851 return true;
852 }
853 }
854 return false;
855 }
856
857 private void setCurrent(Node<E> p) {
858 if ((current = p) == null)
859 exhausted = true;
860 }
861
862 private Node<E> current() {
863 Node<E> p;
864 if ((p = current) == null && !exhausted)
865 setCurrent(p = first());
866 return p;
867 }
868
869 public long estimateSize() { return Long.MAX_VALUE; }
870
871 public int characteristics() {
872 return (Spliterator.ORDERED |
873 Spliterator.NONNULL |
874 Spliterator.CONCURRENT);
875 }
876 }
877
878 /**
879 * Returns a {@link Spliterator} over the elements in this queue.
880 *
881 * <p>The returned spliterator is
882 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
883 *
884 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
885 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
886 *
887 * @implNote
888 * The {@code Spliterator} implements {@code trySplit} to permit limited
889 * parallelism.
890 *
891 * @return a {@code Spliterator} over the elements in this queue
892 * @since 1.8
893 */
894 @Override
895 public Spliterator<E> spliterator() {
896 return new CLQSpliterator();
897 }
898
899 /**
900 * @throws NullPointerException {@inheritDoc}
901 */
902 public boolean removeIf(Predicate<? super E> filter) {
903 Objects.requireNonNull(filter);
904 return bulkRemove(filter);
905 }
906
907 /**
908 * @throws NullPointerException {@inheritDoc}
909 */
910 public boolean removeAll(Collection<?> c) {
911 Objects.requireNonNull(c);
912 return bulkRemove(e -> c.contains(e));
913 }
914
915 /**
916 * @throws NullPointerException {@inheritDoc}
917 */
918 public boolean retainAll(Collection<?> c) {
919 Objects.requireNonNull(c);
920 return bulkRemove(e -> !c.contains(e));
921 }
922
923 public void clear() {
924 bulkRemove(e -> true);
925 }
926
927 /**
928 * Tolerate this many consecutive dead nodes before CAS-collapsing.
929 * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
930 */
931 private static final int MAX_HOPS = 8;
932
933 /** Implementation of bulk remove methods. */
934 private boolean bulkRemove(Predicate<? super E> filter) {
935 boolean removed = false;
936 restartFromHead: for (;;) {
937 int hops = MAX_HOPS;
938 // c will be CASed to collapse intervening dead nodes between
939 // pred (or head if null) and p.
940 for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
941 final E item; boolean pAlive;
942 if (pAlive = ((item = p.item) != null)) {
943 if (filter.test(item)) {
944 if (ITEM.compareAndSet(p, item, null))
945 removed = true;
946 pAlive = false;
947 }
948 }
949 if ((q = p.next) == null || pAlive || --hops == 0) {
950 // p might already be self-linked here, but if so:
951 // - CASing head will surely fail
952 // - CASing pred's next will be useless but harmless.
953 if (c != p && tryCasSuccessor(pred, c, p))
954 c = p;
955 // if c != p, CAS failed, so abandon old pred
956 if (pAlive || c != p) {
957 hops = MAX_HOPS;
958 pred = p;
959 c = q;
960 }
961 } else if (p == q)
962 continue restartFromHead;
963 }
964 return removed;
965 }
966 }
967
968 /**
969 * @throws NullPointerException {@inheritDoc}
970 */
971 public void forEach(Consumer<? super E> action) {
972 Objects.requireNonNull(action);
973 restartFromHead: for (;;) {
974 for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
975 final E item;
976 if ((item = p.item) != null)
977 action.accept(item);
978 if (c != p && tryCasSuccessor(pred, c, p))
979 c = p;
980 q = p.next;
981 if (item != null || c != p) {
982 pred = p;
983 c = q;
984 }
985 else if (p == q)
986 continue restartFromHead;
987 }
988 return;
989 }
990 }
991
992 // VarHandle mechanics
993 private static final VarHandle HEAD;
994 private static final VarHandle TAIL;
995 private static final VarHandle ITEM;
996 private static final VarHandle NEXT;
997 static {
998 try {
999 MethodHandles.Lookup l = MethodHandles.lookup();
1000 HEAD = l.findVarHandle(ConcurrentLinkedQueue.class, "head",
1001 Node.class);
1002 TAIL = l.findVarHandle(ConcurrentLinkedQueue.class, "tail",
1003 Node.class);
1004 ITEM = l.findVarHandle(Node.class, "item", Object.class);
1005 NEXT = l.findVarHandle(Node.class, "next", Node.class);
1006 } catch (ReflectiveOperationException e) {
1007 throw new Error(e);
1008 }
1009 }
1010 }