ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.147
Committed: Wed Jan 4 01:25:06 2017 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.146: +3 -4 lines
Log Message:
sync bulkRemove with LTQ

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.146 final E item; final boolean pAlive;
430     if (pAlive = ((item = p.item) != null))
431     if (o.equals(item))
432     return true;
433     if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
434 jsr166 1.133 pred = p;
435 jsr166 1.146 c = p = p.next;
436 jsr166 1.133 }
437 jsr166 1.146 else if (p == (p = p.next))
438 jsr166 1.133 continue restartFromHead;
439 jsr166 1.103 }
440 jsr166 1.133 return false;
441 dl 1.1 }
442     }
443    
444 jsr166 1.37 /**
445     * Removes a single instance of the specified element from this queue,
446 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
447     * that {@code o.equals(e)}, if this queue contains one or more such
448 jsr166 1.37 * elements.
449 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
450 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
451     *
452     * @param o element to be removed from this queue, if present
453 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
454 jsr166 1.37 */
455 dholmes 1.6 public boolean remove(Object o) {
456 jsr166 1.133 if (o == null) return false;
457     restartFromHead: for (;;) {
458 jsr166 1.141 for (Node<E> p = head, c = p, pred = null, q; p != null; ) {
459 jsr166 1.146 final E item; final boolean pAlive;
460     if (pAlive = ((item = p.item) != null)) {
461     if (o.equals(item)
462     && ITEM.compareAndSet(p, item, null)) {
463     if ((q = p.next) == null) q = p;
464     if (c != q) tryCasSuccessor(pred, c, q);
465     return true;
466     }
467     }
468     if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
469 jsr166 1.133 pred = p;
470 jsr166 1.146 c = p = p.next;
471 jsr166 1.133 }
472 jsr166 1.146 else if (p == (p = p.next))
473 jsr166 1.133 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.137 Objects.requireNonNull(a);
652 jsr166 1.117 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 jsr166 1.142 // Default implementation of forEachRemaining is "good enough".
732    
733 dl 1.1 public void remove() {
734 dl 1.23 Node<E> l = lastRet;
735 dl 1.1 if (l == null) throw new IllegalStateException();
736     // rely on a future traversal to relink.
737 jsr166 1.64 l.item = null;
738 dl 1.1 lastRet = null;
739     }
740     }
741    
742     /**
743 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
744 dl 1.1 *
745 jsr166 1.95 * @param s the stream
746 jsr166 1.96 * @throws java.io.IOException if an I/O error occurs
747 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
748 dl 1.1 * the proper order, followed by a null
749     */
750     private void writeObject(java.io.ObjectOutputStream s)
751     throws java.io.IOException {
752    
753     // Write out any hidden stuff
754     s.defaultWriteObject();
755 tim 1.2
756 dl 1.1 // Write out all elements in the proper order.
757 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
758 jsr166 1.132 final E item;
759     if ((item = p.item) != null)
760 dl 1.1 s.writeObject(item);
761     }
762    
763     // Use trailing null as sentinel
764     s.writeObject(null);
765     }
766    
767     /**
768 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
769 jsr166 1.95 * @param s the stream
770 jsr166 1.96 * @throws ClassNotFoundException if the class of a serialized object
771     * could not be found
772     * @throws java.io.IOException if an I/O error occurs
773 dl 1.1 */
774     private void readObject(java.io.ObjectInputStream s)
775     throws java.io.IOException, ClassNotFoundException {
776 tim 1.2 s.defaultReadObject();
777 jsr166 1.55
778     // Read in elements until trailing null sentinel found
779     Node<E> h = null, t = null;
780 jsr166 1.104 for (Object item; (item = s.readObject()) != null; ) {
781 jsr166 1.48 @SuppressWarnings("unchecked")
782 jsr166 1.102 Node<E> newNode = newNode((E) item);
783 jsr166 1.55 if (h == null)
784     h = t = newNode;
785     else {
786 jsr166 1.125 NEXT.set(t, newNode);
787 jsr166 1.55 t = newNode;
788     }
789 dl 1.1 }
790 jsr166 1.55 if (h == null)
791 jsr166 1.102 h = t = newNode(null);
792 jsr166 1.55 head = h;
793     tail = t;
794     }
795    
796 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
797 jsr166 1.130 final class CLQSpliterator implements Spliterator<E> {
798 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
799 dl 1.82 Node<E> current; // current node; null until initialized
800     int batch; // batch size for splits
801     boolean exhausted; // true when no more nodes
802    
803     public Spliterator<E> trySplit() {
804 jsr166 1.139 Node<E> p, q;
805     if ((p = current()) == null || (q = p.next) == null)
806     return null;
807     int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
808     Object[] a = null;
809     do {
810     final E e;
811     if ((e = p.item) != null)
812     ((a != null) ? a : (a = new Object[n]))[i++] = e;
813     if (p == (p = q))
814     p = first();
815     } while (p != null && (q = p.next) != null && i < n);
816     setCurrent(p);
817     return (i == 0) ? null :
818     Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
819     Spliterator.NONNULL |
820     Spliterator.CONCURRENT));
821 dl 1.82 }
822    
823 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
824 jsr166 1.137 Objects.requireNonNull(action);
825 jsr166 1.142 final Node<E> p;
826 jsr166 1.139 if ((p = current()) != null) {
827 jsr166 1.136 current = null;
828 dl 1.82 exhausted = true;
829 jsr166 1.142 forEachFrom(action, p);
830 dl 1.82 }
831     }
832    
833     public boolean tryAdvance(Consumer<? super E> action) {
834 jsr166 1.137 Objects.requireNonNull(action);
835 dl 1.82 Node<E> p;
836 jsr166 1.139 if ((p = current()) != null) {
837 dl 1.82 E e;
838     do {
839     e = p.item;
840     if (p == (p = p.next))
841 jsr166 1.130 p = first();
842 dl 1.82 } while (e == null && p != null);
843 jsr166 1.139 setCurrent(p);
844 dl 1.82 if (e != null) {
845     action.accept(e);
846     return true;
847     }
848     }
849     return false;
850     }
851    
852 jsr166 1.139 private void setCurrent(Node<E> p) {
853     if ((current = p) == null)
854     exhausted = true;
855     }
856    
857     private Node<E> current() {
858     Node<E> p;
859     if ((p = current) == null && !exhausted)
860     setCurrent(p = first());
861     return p;
862     }
863    
864 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
865    
866 dl 1.82 public int characteristics() {
867 jsr166 1.135 return (Spliterator.ORDERED |
868     Spliterator.NONNULL |
869     Spliterator.CONCURRENT);
870 dl 1.82 }
871     }
872    
873 jsr166 1.97 /**
874     * Returns a {@link Spliterator} over the elements in this queue.
875     *
876 jsr166 1.98 * <p>The returned spliterator is
877     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
878     *
879 jsr166 1.97 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
880     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
881     *
882     * @implNote
883     * The {@code Spliterator} implements {@code trySplit} to permit limited
884     * parallelism.
885     *
886     * @return a {@code Spliterator} over the elements in this queue
887     * @since 1.8
888     */
889     @Override
890 dl 1.85 public Spliterator<E> spliterator() {
891 jsr166 1.130 return new CLQSpliterator();
892 dl 1.82 }
893    
894 jsr166 1.131 /**
895     * @throws NullPointerException {@inheritDoc}
896     */
897     public boolean removeIf(Predicate<? super E> filter) {
898     Objects.requireNonNull(filter);
899     return bulkRemove(filter);
900     }
901    
902     /**
903     * @throws NullPointerException {@inheritDoc}
904     */
905     public boolean removeAll(Collection<?> c) {
906     Objects.requireNonNull(c);
907     return bulkRemove(e -> c.contains(e));
908     }
909    
910     /**
911     * @throws NullPointerException {@inheritDoc}
912     */
913     public boolean retainAll(Collection<?> c) {
914     Objects.requireNonNull(c);
915     return bulkRemove(e -> !c.contains(e));
916     }
917    
918 jsr166 1.133 public void clear() {
919     bulkRemove(e -> true);
920     }
921    
922     /**
923     * Tolerate this many consecutive dead nodes before CAS-collapsing.
924     * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
925     */
926     private static final int MAX_HOPS = 8;
927    
928 jsr166 1.131 /** Implementation of bulk remove methods. */
929     private boolean bulkRemove(Predicate<? super E> filter) {
930     boolean removed = false;
931 jsr166 1.133 restartFromHead: for (;;) {
932     int hops = MAX_HOPS;
933     // c will be CASed to collapse intervening dead nodes between
934     // pred (or head if null) and p.
935     for (Node<E> p = head, c = p, pred = null, q; p != null; p = q) {
936     final E item; boolean pAlive;
937     if (pAlive = ((item = p.item) != null)) {
938     if (filter.test(item)) {
939     if (ITEM.compareAndSet(p, item, null))
940     removed = true;
941     pAlive = false;
942     }
943     }
944     if ((q = p.next) == null || pAlive || --hops == 0) {
945     // p might already be self-linked here, but if so:
946     // - CASing head will surely fail
947     // - CASing pred's next will be useless but harmless.
948 jsr166 1.147 if ((c != p && !tryCasSuccessor(pred, c, c = p))
949     || pAlive) {
950     // if CAS failed or alive, abandon old pred
951 jsr166 1.133 hops = MAX_HOPS;
952     pred = p;
953     c = q;
954     }
955     } else if (p == q)
956     continue restartFromHead;
957 jsr166 1.131 }
958 jsr166 1.133 return removed;
959 jsr166 1.131 }
960     }
961    
962 jsr166 1.133 /**
963 jsr166 1.142 * Runs action on each element found during a traversal starting at p.
964     * If p is null, the action is not run.
965     */
966     @SuppressWarnings("unchecked")
967     void forEachFrom(Consumer<? super E> action, Node<E> p) {
968     for (Node<E> c = p, pred = null, q; p != null; ) {
969     final Object item; final boolean pAlive;
970     if (pAlive = ((item = p.item) != null))
971     action.accept((E) item);
972 jsr166 1.146 if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
973 jsr166 1.142 pred = p;
974 jsr166 1.146 c = p = p.next;
975 jsr166 1.142 }
976 jsr166 1.146 else if (p == (p = p.next)) {
977 jsr166 1.142 pred = null;
978     c = p = head;
979     }
980     }
981     }
982    
983     /**
984 jsr166 1.133 * @throws NullPointerException {@inheritDoc}
985     */
986 jsr166 1.131 public void forEach(Consumer<? super E> action) {
987     Objects.requireNonNull(action);
988 jsr166 1.142 forEachFrom(action, head);
989 jsr166 1.131 }
990    
991 dl 1.123 // VarHandle mechanics
992     private static final VarHandle HEAD;
993     private static final VarHandle TAIL;
994     private static final VarHandle ITEM;
995     private static final VarHandle NEXT;
996 dl 1.71 static {
997 jsr166 1.48 try {
998 dl 1.123 MethodHandles.Lookup l = MethodHandles.lookup();
999     HEAD = l.findVarHandle(ConcurrentLinkedQueue.class, "head",
1000     Node.class);
1001     TAIL = l.findVarHandle(ConcurrentLinkedQueue.class, "tail",
1002     Node.class);
1003     ITEM = l.findVarHandle(Node.class, "item", Object.class);
1004     NEXT = l.findVarHandle(Node.class, "next", Node.class);
1005 jsr166 1.108 } catch (ReflectiveOperationException e) {
1006 dl 1.71 throw new Error(e);
1007 jsr166 1.48 }
1008     }
1009 dl 1.1 }