ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.134
Committed: Sat Dec 10 16:37:30 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.133: +7 -8 lines
Log Message:
improve implementation comment

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 dl 1.75 * Additionally, the bulk operations {@code addAll},
56     * {@code removeAll}, {@code retainAll}, {@code containsAll},
57 jsr166 1.126 * and {@code toArray} are <em>not</em> guaranteed
58 dl 1.74 * to be performed atomically. For example, an iterator operating
59 dl 1.75 * concurrently with an {@code addAll} operation might view only some
60 dl 1.74 * 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.102 }
159 jsr166 1.29
160 jsr166 1.102 /**
161     * Returns a new node holding item. Uses relaxed write because item
162 dl 1.123 * can only be seen after piggy-backing publication via CAS.
163 jsr166 1.102 */
164     static <E> Node<E> newNode(E item) {
165     Node<E> node = new Node<E>();
166 dl 1.123 ITEM.set(node, item);
167 jsr166 1.102 return node;
168     }
169 jsr166 1.29
170 tim 1.2 /**
171 jsr166 1.51 * 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 dl 1.1 */
182 jsr166 1.114 transient volatile Node<E> head;
183 dl 1.1
184 jsr166 1.51 /**
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 jsr166 1.55 private transient volatile Node<E> tail;
197 dl 1.1
198     /**
199 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
200 dl 1.1 */
201 jsr166 1.55 public ConcurrentLinkedQueue() {
202 jsr166 1.102 head = tail = newNode(null);
203 jsr166 1.55 }
204 dl 1.1
205     /**
206 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue}
207 dholmes 1.7 * initially containing the elements of the given collection,
208 dholmes 1.6 * added in traversal order of the collection's iterator.
209 jsr166 1.55 *
210 dholmes 1.6 * @param c the collection of elements to initially contain
211 jsr166 1.34 * @throws NullPointerException if the specified collection or any
212     * of its elements are null
213 dl 1.1 */
214 dholmes 1.6 public ConcurrentLinkedQueue(Collection<? extends E> c) {
215 jsr166 1.55 Node<E> h = null, t = null;
216     for (E e : c) {
217 jsr166 1.118 Node<E> newNode = newNode(Objects.requireNonNull(e));
218 jsr166 1.55 if (h == null)
219     h = t = newNode;
220     else {
221 jsr166 1.125 NEXT.set(t, newNode);
222 jsr166 1.55 t = newNode;
223     }
224     }
225     if (h == null)
226 jsr166 1.102 h = t = newNode(null);
227 jsr166 1.55 head = h;
228     tail = t;
229 dl 1.1 }
230    
231 jsr166 1.29 // Have to override just to update the javadoc
232 dholmes 1.6
233     /**
234 jsr166 1.35 * Inserts the specified element at the tail of this queue.
235 jsr166 1.67 * As the queue is unbounded, this method will never throw
236     * {@link IllegalStateException} or return {@code false}.
237 dholmes 1.7 *
238 jsr166 1.48 * @return {@code true} (as specified by {@link Collection#add})
239 jsr166 1.32 * @throws NullPointerException if the specified element is null
240 dholmes 1.6 */
241 jsr166 1.31 public boolean add(E e) {
242     return offer(e);
243 dholmes 1.6 }
244    
245     /**
246 jsr166 1.81 * Tries to CAS head to p. If successful, repoint old head to itself
247 jsr166 1.48 * as sentinel for succ(), below.
248     */
249     final void updateHead(Node<E> h, Node<E> p) {
250 jsr166 1.113 // assert h != null && p != null && (h == p || h.item == null);
251 dl 1.123 if (h != p && HEAD.compareAndSet(this, h, p))
252     NEXT.setRelease(h, h);
253 jsr166 1.48 }
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 jsr166 1.55 Node<E> next = p.next;
262 jsr166 1.48 return (p == next) ? head : next;
263     }
264    
265     /**
266 jsr166 1.133 * 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 jsr166 1.32 * Inserts the specified element at the tail of this queue.
282 jsr166 1.67 * As the queue is unbounded, this method will never return {@code false}.
283 dl 1.17 *
284 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
285 jsr166 1.32 * @throws NullPointerException if the specified element is null
286 dholmes 1.6 */
287 jsr166 1.31 public boolean offer(E e) {
288 jsr166 1.118 final Node<E> newNode = newNode(Objects.requireNonNull(e));
289 jsr166 1.58
290 jsr166 1.65 for (Node<E> t = tail, p = t;;) {
291     Node<E> q = p.next;
292     if (q == null) {
293     // p is last node
294 dl 1.123 if (NEXT.compareAndSet(p, null, newNode)) {
295 jsr166 1.63 // Successful CAS is the linearization point
296     // for e to become an element of this queue,
297     // and for newNode to become "live".
298 jsr166 1.128 if (p != t) // hop two nodes at a time; failure is OK
299 jsr166 1.129 TAIL.weakCompareAndSet(this, t, newNode);
300 jsr166 1.48 return true;
301 dl 1.1 }
302 jsr166 1.65 // Lost CAS race to another thread; re-read next
303 dl 1.1 }
304 jsr166 1.65 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 dl 1.1 }
314     }
315    
316     public E poll() {
317 jsr166 1.133 restartFromHead: for (;;) {
318     for (Node<E> h = head, p = h, q;; p = q) {
319 jsr166 1.132 final E item;
320     if ((item = p.item) != null
321     && ITEM.compareAndSet(p, item, null)) {
322 jsr166 1.65 // 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 dl 1.1 }
332 jsr166 1.65 else if (p == q)
333     continue restartFromHead;
334 dl 1.1 }
335     }
336     }
337    
338 jsr166 1.48 public E peek() {
339 jsr166 1.133 restartFromHead: for (;;) {
340     for (Node<E> h = head, p = h, q;; p = q) {
341 jsr166 1.132 final E item;
342     if ((item = p.item) != null
343     || (q = p.next) == null) {
344 jsr166 1.65 updateHead(h, p);
345     return item;
346     }
347     else if (p == q)
348     continue restartFromHead;
349 dl 1.1 }
350     }
351     }
352    
353     /**
354 jsr166 1.51 * 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 dl 1.1 */
361 dl 1.23 Node<E> first() {
362 jsr166 1.133 restartFromHead: for (;;) {
363     for (Node<E> h = head, p = h, q;; p = q) {
364 jsr166 1.65 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 dl 1.1 }
372     }
373     }
374    
375 dl 1.28 /**
376 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
377 dl 1.28 *
378 jsr166 1.48 * @return {@code true} if this queue contains no elements
379 dl 1.28 */
380 dl 1.1 public boolean isEmpty() {
381     return first() == null;
382     }
383    
384     /**
385 dl 1.17 * Returns the number of elements in this queue. If this queue
386 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
387     * {@code Integer.MAX_VALUE}.
388 tim 1.2 *
389 dl 1.17 * <p>Beware that, unlike in most collections, this method is
390 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
391     * asynchronous nature of these queues, determining the current
392 jsr166 1.55 * 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 dl 1.17 *
398 jsr166 1.37 * @return the number of elements in this queue
399 tim 1.2 */
400 dl 1.1 public int size() {
401 jsr166 1.100 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 jsr166 1.116 if (p == (p = p.next))
408 jsr166 1.100 continue restartFromHead;
409     }
410     return count;
411     }
412 dl 1.1 }
413    
414 jsr166 1.37 /**
415 jsr166 1.48 * 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 jsr166 1.37 *
419     * @param o object to be checked for containment in this queue
420 jsr166 1.48 * @return {@code true} if this queue contains the specified element
421 jsr166 1.37 */
422 dholmes 1.6 public boolean contains(Object o) {
423 jsr166 1.133 if (o == null) return false;
424     restartFromHead: for (;;) {
425     for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
426 jsr166 1.132 final E item;
427     if ((item = p.item) != null && o.equals(item))
428 jsr166 1.103 return true;
429 jsr166 1.133 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 jsr166 1.103 }
439 jsr166 1.133 return false;
440 dl 1.1 }
441     }
442    
443 jsr166 1.37 /**
444     * Removes a single instance of the specified element from this queue,
445 jsr166 1.48 * 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 jsr166 1.37 * elements.
448 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
449 jsr166 1.37 * (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 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
453 jsr166 1.37 */
454 dholmes 1.6 public boolean remove(Object o) {
455 jsr166 1.133 if (o == null) return false;
456     restartFromHead: for (;;) {
457     for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
458 jsr166 1.132 final E item;
459 jsr166 1.133 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 jsr166 1.110 if (removed)
466 jsr166 1.103 return true;
467 jsr166 1.133 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 jsr166 1.48 }
475 jsr166 1.133 return false;
476 dl 1.1 }
477     }
478 tim 1.2
479 jsr166 1.33 /**
480 jsr166 1.55 * 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 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
483     * itself result in {@code IllegalArgumentException}.
484 jsr166 1.55 *
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 jsr166 1.56 * @throws NullPointerException if the specified collection or any
488     * of its elements are null
489     * @throws IllegalArgumentException if the collection is this queue
490 jsr166 1.55 */
491     public boolean addAll(Collection<? extends E> c) {
492 jsr166 1.56 if (c == this)
493     // As historically specified in AbstractQueue#addAll
494     throw new IllegalArgumentException();
495    
496 jsr166 1.55 // Copy c into a private chain of Nodes
497 jsr166 1.65 Node<E> beginningOfTheEnd = null, last = null;
498 jsr166 1.55 for (E e : c) {
499 jsr166 1.118 Node<E> newNode = newNode(Objects.requireNonNull(e));
500 jsr166 1.65 if (beginningOfTheEnd == null)
501     beginningOfTheEnd = last = newNode;
502 jsr166 1.55 else {
503 jsr166 1.125 NEXT.set(last, newNode);
504 jsr166 1.55 last = newNode;
505     }
506     }
507 jsr166 1.65 if (beginningOfTheEnd == null)
508 jsr166 1.55 return false;
509    
510 jsr166 1.65 // 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 dl 1.123 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
516 jsr166 1.65 // Successful CAS is the linearization point
517     // for all elements to be added to this queue.
518 jsr166 1.129 if (!TAIL.weakCompareAndSet(this, t, last)) {
519 jsr166 1.55 // Try a little harder to update tail,
520     // since we may be adding many elements.
521     t = tail;
522     if (last.next == null)
523 jsr166 1.129 TAIL.weakCompareAndSet(this, t, last);
524 jsr166 1.55 }
525     return true;
526     }
527 jsr166 1.65 // Lost CAS race to another thread; re-read next
528 jsr166 1.55 }
529 jsr166 1.65 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 jsr166 1.55 }
539     }
540    
541 jsr166 1.117 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 jsr166 1.132 final E item;
548     if ((item = p.item) != null) {
549 jsr166 1.117 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 jsr166 1.120 return Helpers.toString(a, size, charLength);
565 jsr166 1.117 }
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 jsr166 1.132 final E item;
574     if ((item = p.item) != null) {
575 jsr166 1.117 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 jsr166 1.55 /**
598 jsr166 1.48 * 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 jsr166 1.117 return toArrayInternal(null);
612 jsr166 1.48 }
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 jsr166 1.115 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
636 jsr166 1.48 *
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 jsr166 1.117 if (a == null) throw new NullPointerException();
652     return (T[]) toArrayInternal(a);
653 jsr166 1.48 }
654    
655     /**
656 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
657 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
658     *
659 jsr166 1.98 * <p>The returned iterator is
660     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
661 dholmes 1.7 *
662 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
663 dholmes 1.7 */
664 dl 1.1 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 dl 1.23 private Node<E> nextNode;
673 dl 1.1
674 tim 1.2 /**
675 dl 1.1 * 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 jsr166 1.29 */
680 dl 1.1 private E nextItem;
681    
682     /**
683     * Node of the last returned item, to support remove.
684     */
685 dl 1.23 private Node<E> lastRet;
686 dl 1.1
687 tim 1.2 Itr() {
688 jsr166 1.114 restartFromHead: for (;;) {
689     Node<E> h, p, q;
690     for (p = h = head;; p = q) {
691 jsr166 1.131 final E item;
692 jsr166 1.114 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 dl 1.1 }
706 tim 1.2
707 jsr166 1.114 public boolean hasNext() {
708     return nextItem != null;
709     }
710 dl 1.1
711 jsr166 1.114 public E next() {
712 jsr166 1.111 final Node<E> pred = nextNode;
713 jsr166 1.114 if (pred == null) throw new NoSuchElementException();
714     // assert nextItem != null;
715     lastRet = pred;
716     E item = null;
717 jsr166 1.48
718 jsr166 1.114 for (Node<E> p = succ(pred), q;; p = q) {
719     if (p == null || (item = p.item) != null) {
720 dl 1.1 nextNode = p;
721 jsr166 1.114 E x = nextItem;
722 dl 1.1 nextItem = item;
723 jsr166 1.114 return x;
724 jsr166 1.48 }
725 jsr166 1.114 // unlink deleted nodes
726     if ((q = succ(p)) != null)
727 dl 1.123 NEXT.compareAndSet(pred, p, q);
728 dl 1.1 }
729     }
730 tim 1.2
731 dl 1.1 public void remove() {
732 dl 1.23 Node<E> l = lastRet;
733 dl 1.1 if (l == null) throw new IllegalStateException();
734     // rely on a future traversal to relink.
735 jsr166 1.64 l.item = null;
736 dl 1.1 lastRet = null;
737     }
738     }
739    
740     /**
741 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
742 dl 1.1 *
743 jsr166 1.95 * @param s the stream
744 jsr166 1.96 * @throws java.io.IOException if an I/O error occurs
745 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
746 dl 1.1 * 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 tim 1.2
754 dl 1.1 // Write out all elements in the proper order.
755 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
756 jsr166 1.132 final E item;
757     if ((item = p.item) != null)
758 dl 1.1 s.writeObject(item);
759     }
760    
761     // Use trailing null as sentinel
762     s.writeObject(null);
763     }
764    
765     /**
766 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
767 jsr166 1.95 * @param s the stream
768 jsr166 1.96 * @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 dl 1.1 */
772     private void readObject(java.io.ObjectInputStream s)
773     throws java.io.IOException, ClassNotFoundException {
774 tim 1.2 s.defaultReadObject();
775 jsr166 1.55
776     // Read in elements until trailing null sentinel found
777     Node<E> h = null, t = null;
778 jsr166 1.104 for (Object item; (item = s.readObject()) != null; ) {
779 jsr166 1.48 @SuppressWarnings("unchecked")
780 jsr166 1.102 Node<E> newNode = newNode((E) item);
781 jsr166 1.55 if (h == null)
782     h = t = newNode;
783     else {
784 jsr166 1.125 NEXT.set(t, newNode);
785 jsr166 1.55 t = newNode;
786     }
787 dl 1.1 }
788 jsr166 1.55 if (h == null)
789 jsr166 1.102 h = t = newNode(null);
790 jsr166 1.55 head = h;
791     tail = t;
792     }
793    
794 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
795 jsr166 1.130 final class CLQSpliterator implements Spliterator<E> {
796 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
797 dl 1.82 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 dl 1.89 Node<E> p;
803     int b = batch;
804     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
805 jsr166 1.87 if (!exhausted &&
806 jsr166 1.130 ((p = current) != null || (p = first()) != null) &&
807 dl 1.83 p.next != null) {
808 dl 1.92 Object[] a = new Object[n];
809 dl 1.82 int i = 0;
810     do {
811     if ((a[i] = p.item) != null)
812     ++i;
813     if (p == (p = p.next))
814 jsr166 1.130 p = first();
815 dl 1.82 } while (p != null && i < n);
816     if ((current = p) == null)
817     exhausted = true;
818 dl 1.89 if (i > 0) {
819     batch = i;
820     return Spliterators.spliterator
821 jsr166 1.121 (a, 0, i, (Spliterator.ORDERED |
822     Spliterator.NONNULL |
823     Spliterator.CONCURRENT));
824 dl 1.89 }
825 dl 1.82 }
826     return null;
827     }
828    
829 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
830 dl 1.82 Node<E> p;
831     if (action == null) throw new NullPointerException();
832     if (!exhausted &&
833 jsr166 1.130 ((p = current) != null || (p = first()) != null)) {
834 dl 1.82 exhausted = true;
835     do {
836     E e = p.item;
837     if (p == (p = p.next))
838 jsr166 1.130 p = first();
839 dl 1.82 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 jsr166 1.130 ((p = current) != null || (p = first()) != null)) {
850 dl 1.82 E e;
851     do {
852     e = p.item;
853     if (p == (p = p.next))
854 jsr166 1.130 p = first();
855 dl 1.82 } 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 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
867    
868 dl 1.82 public int characteristics() {
869     return Spliterator.ORDERED | Spliterator.NONNULL |
870     Spliterator.CONCURRENT;
871     }
872     }
873    
874 jsr166 1.97 /**
875     * Returns a {@link Spliterator} over the elements in this queue.
876     *
877 jsr166 1.98 * <p>The returned spliterator is
878     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
879     *
880 jsr166 1.97 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
881     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
882     *
883     * @implNote
884     * The {@code Spliterator} implements {@code trySplit} to permit limited
885     * parallelism.
886     *
887     * @return a {@code Spliterator} over the elements in this queue
888     * @since 1.8
889     */
890     @Override
891 dl 1.85 public Spliterator<E> spliterator() {
892 jsr166 1.130 return new CLQSpliterator();
893 dl 1.82 }
894    
895 jsr166 1.131 /**
896     * @throws NullPointerException {@inheritDoc}
897     */
898     public boolean removeIf(Predicate<? super E> filter) {
899     Objects.requireNonNull(filter);
900     return bulkRemove(filter);
901     }
902    
903     /**
904     * @throws NullPointerException {@inheritDoc}
905     */
906     public boolean removeAll(Collection<?> c) {
907     Objects.requireNonNull(c);
908     return bulkRemove(e -> c.contains(e));
909     }
910    
911     /**
912     * @throws NullPointerException {@inheritDoc}
913     */
914     public boolean retainAll(Collection<?> c) {
915     Objects.requireNonNull(c);
916     return bulkRemove(e -> !c.contains(e));
917     }
918    
919 jsr166 1.133 public void clear() {
920     bulkRemove(e -> true);
921     }
922    
923     /**
924     * Tolerate this many consecutive dead nodes before CAS-collapsing.
925     * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
926     */
927     private static final int MAX_HOPS = 8;
928    
929 jsr166 1.131 /** Implementation of bulk remove methods. */
930     private boolean bulkRemove(Predicate<? super E> filter) {
931     boolean removed = false;
932 jsr166 1.133 restartFromHead: for (;;) {
933     int hops = MAX_HOPS;
934     // c will be CASed to collapse intervening dead nodes between
935     // pred (or head if null) and p.
936     for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
937     final E item; boolean pAlive;
938     if (pAlive = ((item = p.item) != null)) {
939     if (filter.test(item)) {
940     if (ITEM.compareAndSet(p, item, null))
941     removed = true;
942     pAlive = false;
943     }
944     }
945     if ((q = p.next) == null || pAlive || --hops == 0) {
946     // p might already be self-linked here, but if so:
947     // - CASing head will surely fail
948     // - CASing pred's next will be useless but harmless.
949     if (c != p && tryCasSuccessor(pred, c, p))
950     c = p;
951     // if c != p, CAS failed, so abandon old pred
952     if (pAlive || c != p) {
953     hops = MAX_HOPS;
954     pred = p;
955     c = q;
956     }
957     } else if (p == q)
958     continue restartFromHead;
959 jsr166 1.131 }
960 jsr166 1.133 return removed;
961 jsr166 1.131 }
962     }
963    
964 jsr166 1.133 /**
965     * @throws NullPointerException {@inheritDoc}
966     */
967 jsr166 1.131 public void forEach(Consumer<? super E> action) {
968     Objects.requireNonNull(action);
969 jsr166 1.133 restartFromHead: for (;;) {
970     for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
971     final E item;
972     if ((item = p.item) != null)
973     action.accept(item);
974     if (c != p && tryCasSuccessor(pred, c, p))
975     c = p;
976     q = p.next;
977     if (item != null || c != p) {
978     pred = p;
979     c = q;
980     }
981     else if (p == q)
982     continue restartFromHead;
983     }
984     return;
985     }
986 jsr166 1.131 }
987    
988 dl 1.123 // VarHandle mechanics
989     private static final VarHandle HEAD;
990     private static final VarHandle TAIL;
991     private static final VarHandle ITEM;
992     private static final VarHandle NEXT;
993 dl 1.71 static {
994 jsr166 1.48 try {
995 dl 1.123 MethodHandles.Lookup l = MethodHandles.lookup();
996     HEAD = l.findVarHandle(ConcurrentLinkedQueue.class, "head",
997     Node.class);
998     TAIL = l.findVarHandle(ConcurrentLinkedQueue.class, "tail",
999     Node.class);
1000     ITEM = l.findVarHandle(Node.class, "item", Object.class);
1001     NEXT = l.findVarHandle(Node.class, "next", Node.class);
1002 jsr166 1.108 } catch (ReflectiveOperationException e) {
1003 dl 1.71 throw new Error(e);
1004 jsr166 1.48 }
1005     }
1006 dl 1.1 }