ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.154
Committed: Sat Jan 14 03:27:16 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.153: +43 -34 lines
Log Message:
introduce methods into Node class

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