ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.144
Committed: Mon Jan 2 00:10:14 2017 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.143: +2 -0 lines
Log Message:
add assertions that we never cas-unlink the trailing node

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