ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.135
Committed: Sat Dec 24 04:28:27 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.134: +3 -2 lines
Log Message:
coding style

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