ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.156
Committed: Sat Jan 14 06:50:52 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.155: +1 -1 lines
Log Message:
internal docs

File Contents

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