ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.130
Committed: Wed Nov 30 03:31:47 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.129: +8 -15 lines
Log Message:
convert Spliterator implementations to inner classes

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 dl 1.1
22     /**
23 jsr166 1.29 * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
24 dholmes 1.6 * This queue orders elements FIFO (first-in-first-out).
25     * The <em>head</em> of the queue is that element that has been on the
26     * queue the longest time.
27     * The <em>tail</em> of the queue is that element that has been on the
28 dl 1.17 * queue the shortest time. New elements
29     * are inserted at the tail of the queue, and the queue retrieval
30     * operations obtain elements at the head of the queue.
31 jsr166 1.48 * A {@code ConcurrentLinkedQueue} is an appropriate choice when
32 dl 1.19 * many threads will share access to a common collection.
33 jsr166 1.55 * Like most other concurrent collection implementations, this class
34     * does not permit the use of {@code null} elements.
35 dl 1.1 *
36 jsr166 1.93 * <p>This implementation employs an efficient <em>non-blocking</em>
37 jsr166 1.99 * algorithm based on one described in
38     * <a href="http://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf">
39     * Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue
40 dl 1.15 * Algorithms</a> by Maged M. Michael and Michael L. Scott.
41 dl 1.1 *
42 jsr166 1.55 * <p>Iterators are <i>weakly consistent</i>, returning elements
43     * reflecting the state of the queue at some point at or since the
44     * creation of the iterator. They do <em>not</em> throw {@link
45 dl 1.68 * java.util.ConcurrentModificationException}, and may proceed concurrently
46 jsr166 1.69 * with other operations. Elements contained in the queue since the creation
47 jsr166 1.55 * of the iterator will be returned exactly once.
48     *
49     * <p>Beware that, unlike in most collections, the {@code size} method
50     * is <em>NOT</em> a constant-time operation. Because of the
51 dl 1.1 * asynchronous nature of these queues, determining the current number
52 dl 1.74 * of elements requires a traversal of the elements, and so may report
53     * inaccurate results if this collection is modified during traversal.
54 dl 1.75 * Additionally, the bulk operations {@code addAll},
55     * {@code removeAll}, {@code retainAll}, {@code containsAll},
56 jsr166 1.126 * and {@code toArray} are <em>not</em> guaranteed
57 dl 1.74 * to be performed atomically. For example, an iterator operating
58 dl 1.75 * concurrently with an {@code addAll} operation might view only some
59 dl 1.74 * of the added elements.
60 dl 1.18 *
61 jsr166 1.55 * <p>This class and its iterator implement all of the <em>optional</em>
62     * methods of the {@link Queue} and {@link Iterator} interfaces.
63 dl 1.18 *
64 jsr166 1.43 * <p>Memory consistency effects: As with other concurrent
65     * collections, actions in a thread prior to placing an object into a
66     * {@code ConcurrentLinkedQueue}
67     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
68     * actions subsequent to the access or removal of that element from
69     * the {@code ConcurrentLinkedQueue} in another thread.
70     *
71 dl 1.25 * <p>This class is a member of the
72 jsr166 1.47 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
73 dl 1.25 * Java Collections Framework</a>.
74     *
75 dl 1.1 * @since 1.5
76     * @author Doug Lea
77 jsr166 1.105 * @param <E> the type of elements held in this queue
78 dl 1.25 */
79 dl 1.1 public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
80     implements Queue<E>, java.io.Serializable {
81 dl 1.14 private static final long serialVersionUID = 196745693267521676L;
82 dl 1.1
83     /*
84 jsr166 1.48 * This is a modification of the Michael & Scott algorithm,
85     * adapted for a garbage-collected environment, with support for
86     * interior node deletion (to support remove(Object)). For
87     * explanation, read the paper.
88 dl 1.44 *
89 jsr166 1.48 * Note that like most non-blocking algorithms in this package,
90     * this implementation relies on the fact that in garbage
91 dl 1.44 * collected systems, there is no possibility of ABA problems due
92     * to recycled nodes, so there is no need to use "counted
93     * pointers" or related techniques seen in versions used in
94     * non-GC'ed settings.
95 jsr166 1.48 *
96     * The fundamental invariants are:
97     * - There is exactly one (last) Node with a null next reference,
98     * which is CASed when enqueueing. This last Node can be
99     * reached in O(1) time from tail, but tail is merely an
100     * optimization - it can always be reached in O(N) time from
101     * head as well.
102     * - The elements contained in the queue are the non-null items in
103     * Nodes that are reachable from head. CASing the item
104     * reference of a Node to null atomically removes it from the
105     * queue. Reachability of all elements from head must remain
106     * true even in the case of concurrent modifications that cause
107     * head to advance. A dequeued Node may remain in use
108     * indefinitely due to creation of an Iterator or simply a
109     * poll() that has lost its time slice.
110     *
111     * The above might appear to imply that all Nodes are GC-reachable
112     * from a predecessor dequeued Node. That would cause two problems:
113     * - allow a rogue Iterator to cause unbounded memory retention
114     * - cause cross-generational linking of old Nodes to new Nodes if
115     * a Node was tenured while live, which generational GCs have a
116     * hard time dealing with, causing repeated major collections.
117     * However, only non-deleted Nodes need to be reachable from
118     * dequeued Nodes, and reachability does not necessarily have to
119     * be of the kind understood by the GC. We use the trick of
120     * linking a Node that has just been dequeued to itself. Such a
121     * self-link implicitly means to advance to head.
122     *
123     * Both head and tail are permitted to lag. In fact, failing to
124     * update them every time one could is a significant optimization
125 jsr166 1.65 * (fewer CASes). As with LinkedTransferQueue (see the internal
126     * documentation for that class), we use a slack threshold of two;
127     * that is, we update head/tail when the current pointer appears
128     * to be two or more steps away from the first/last node.
129 jsr166 1.48 *
130     * Since head and tail are updated concurrently and independently,
131     * it is possible for tail to lag behind head (why not)?
132     *
133     * CASing a Node's item reference to null atomically removes the
134     * element from the queue. Iterators skip over Nodes with null
135     * items. Prior implementations of this class had a race between
136     * poll() and remove(Object) where the same element would appear
137     * to be successfully removed by two concurrent operations. The
138     * method remove(Object) also lazily unlinks deleted Nodes, but
139     * this is merely an optimization.
140     *
141     * When constructing a Node (before enqueuing it) we avoid paying
142 jsr166 1.124 * for a volatile write to item. This allows the cost of enqueue
143     * to be "one-and-a-half" CASes.
144 jsr166 1.48 *
145     * Both head and tail may or may not point to a Node with a
146     * non-null item. If the queue is empty, all items must of course
147     * be null. Upon creation, both head and tail refer to a dummy
148     * Node with null item. Both head and tail are only updated using
149     * CAS, so they never regress, although again this is merely an
150     * optimization.
151 dl 1.1 */
152 jsr166 1.51
153 dl 1.123 static final class Node<E> {
154 jsr166 1.64 volatile E item;
155     volatile Node<E> next;
156 jsr166 1.102 }
157 jsr166 1.29
158 jsr166 1.102 /**
159     * Returns a new node holding item. Uses relaxed write because item
160 dl 1.123 * can only be seen after piggy-backing publication via CAS.
161 jsr166 1.102 */
162     static <E> Node<E> newNode(E item) {
163     Node<E> node = new Node<E>();
164 dl 1.123 ITEM.set(node, item);
165 jsr166 1.102 return node;
166     }
167 jsr166 1.29
168 tim 1.2 /**
169 jsr166 1.51 * A node from which the first live (non-deleted) node (if any)
170     * can be reached in O(1) time.
171     * Invariants:
172     * - all live nodes are reachable from head via succ()
173     * - head != null
174     * - (tmp = head).next != tmp || tmp != head
175     * Non-invariants:
176     * - head.item may or may not be null.
177     * - it is permitted for tail to lag behind head, that is, for tail
178     * to not be reachable from head!
179 dl 1.1 */
180 jsr166 1.114 transient volatile Node<E> head;
181 dl 1.1
182 jsr166 1.51 /**
183     * A node from which the last node on list (that is, the unique
184     * node with node.next == null) can be reached in O(1) time.
185     * Invariants:
186     * - the last node is always reachable from tail via succ()
187     * - tail != null
188     * Non-invariants:
189     * - tail.item may or may not be null.
190     * - it is permitted for tail to lag behind head, that is, for tail
191     * to not be reachable from head!
192     * - tail.next may or may not be self-pointing to tail.
193     */
194 jsr166 1.55 private transient volatile Node<E> tail;
195 dl 1.1
196     /**
197 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
198 dl 1.1 */
199 jsr166 1.55 public ConcurrentLinkedQueue() {
200 jsr166 1.102 head = tail = newNode(null);
201 jsr166 1.55 }
202 dl 1.1
203     /**
204 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue}
205 dholmes 1.7 * initially containing the elements of the given collection,
206 dholmes 1.6 * added in traversal order of the collection's iterator.
207 jsr166 1.55 *
208 dholmes 1.6 * @param c the collection of elements to initially contain
209 jsr166 1.34 * @throws NullPointerException if the specified collection or any
210     * of its elements are null
211 dl 1.1 */
212 dholmes 1.6 public ConcurrentLinkedQueue(Collection<? extends E> c) {
213 jsr166 1.55 Node<E> h = null, t = null;
214     for (E e : c) {
215 jsr166 1.118 Node<E> newNode = newNode(Objects.requireNonNull(e));
216 jsr166 1.55 if (h == null)
217     h = t = newNode;
218     else {
219 jsr166 1.125 NEXT.set(t, newNode);
220 jsr166 1.55 t = newNode;
221     }
222     }
223     if (h == null)
224 jsr166 1.102 h = t = newNode(null);
225 jsr166 1.55 head = h;
226     tail = t;
227 dl 1.1 }
228    
229 jsr166 1.29 // Have to override just to update the javadoc
230 dholmes 1.6
231     /**
232 jsr166 1.35 * Inserts the specified element at the tail of this queue.
233 jsr166 1.67 * As the queue is unbounded, this method will never throw
234     * {@link IllegalStateException} or return {@code false}.
235 dholmes 1.7 *
236 jsr166 1.48 * @return {@code true} (as specified by {@link Collection#add})
237 jsr166 1.32 * @throws NullPointerException if the specified element is null
238 dholmes 1.6 */
239 jsr166 1.31 public boolean add(E e) {
240     return offer(e);
241 dholmes 1.6 }
242    
243     /**
244 jsr166 1.81 * Tries to CAS head to p. If successful, repoint old head to itself
245 jsr166 1.48 * as sentinel for succ(), below.
246     */
247     final void updateHead(Node<E> h, Node<E> p) {
248 jsr166 1.113 // assert h != null && p != null && (h == p || h.item == null);
249 dl 1.123 if (h != p && HEAD.compareAndSet(this, h, p))
250     NEXT.setRelease(h, h);
251 jsr166 1.48 }
252    
253     /**
254     * Returns the successor of p, or the head node if p.next has been
255     * linked to self, which will only be true if traversing with a
256     * stale pointer that is now off the list.
257     */
258     final Node<E> succ(Node<E> p) {
259 jsr166 1.55 Node<E> next = p.next;
260 jsr166 1.48 return (p == next) ? head : next;
261     }
262    
263     /**
264 jsr166 1.32 * Inserts the specified element at the tail of this queue.
265 jsr166 1.67 * As the queue is unbounded, this method will never return {@code false}.
266 dl 1.17 *
267 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
268 jsr166 1.32 * @throws NullPointerException if the specified element is null
269 dholmes 1.6 */
270 jsr166 1.31 public boolean offer(E e) {
271 jsr166 1.118 final Node<E> newNode = newNode(Objects.requireNonNull(e));
272 jsr166 1.58
273 jsr166 1.65 for (Node<E> t = tail, p = t;;) {
274     Node<E> q = p.next;
275     if (q == null) {
276     // p is last node
277 dl 1.123 if (NEXT.compareAndSet(p, null, newNode)) {
278 jsr166 1.63 // Successful CAS is the linearization point
279     // for e to become an element of this queue,
280     // and for newNode to become "live".
281 jsr166 1.128 if (p != t) // hop two nodes at a time; failure is OK
282 jsr166 1.129 TAIL.weakCompareAndSet(this, t, newNode);
283 jsr166 1.48 return true;
284 dl 1.1 }
285 jsr166 1.65 // Lost CAS race to another thread; re-read next
286 dl 1.1 }
287 jsr166 1.65 else if (p == q)
288     // We have fallen off list. If tail is unchanged, it
289     // will also be off-list, in which case we need to
290     // jump to head, from which all live nodes are always
291     // reachable. Else the new tail is a better bet.
292     p = (t != (t = tail)) ? t : head;
293     else
294     // Check for tail updates after two hops.
295     p = (p != t && t != (t = tail)) ? t : q;
296 dl 1.1 }
297     }
298    
299     public E poll() {
300 jsr166 1.65 restartFromHead:
301     for (;;) {
302     for (Node<E> h = head, p = h, q;;) {
303     E item = p.item;
304 jsr166 1.48
305 dl 1.123 if (item != null && ITEM.compareAndSet(p, item, null)) {
306 jsr166 1.65 // Successful CAS is the linearization point
307     // for item to be removed from this queue.
308     if (p != h) // hop two nodes at a time
309     updateHead(h, ((q = p.next) != null) ? q : p);
310     return item;
311     }
312     else if ((q = p.next) == null) {
313     updateHead(h, p);
314     return null;
315 dl 1.1 }
316 jsr166 1.65 else if (p == q)
317     continue restartFromHead;
318     else
319     p = q;
320 dl 1.1 }
321     }
322     }
323    
324 jsr166 1.48 public E peek() {
325 jsr166 1.65 restartFromHead:
326 dl 1.1 for (;;) {
327 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
328     E item = p.item;
329     if (item != null || (q = p.next) == null) {
330     updateHead(h, p);
331     return item;
332     }
333     else if (p == q)
334     continue restartFromHead;
335     else
336     p = q;
337 dl 1.1 }
338     }
339     }
340    
341     /**
342 jsr166 1.51 * Returns the first live (non-deleted) node on list, or null if none.
343     * This is yet another variant of poll/peek; here returning the
344     * first node, not element. We could make peek() a wrapper around
345     * first(), but that would cost an extra volatile read of item,
346     * and the need to add a retry loop to deal with the possibility
347     * of losing a race to a concurrent poll().
348 dl 1.1 */
349 dl 1.23 Node<E> first() {
350 jsr166 1.65 restartFromHead:
351 dl 1.1 for (;;) {
352 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
353     boolean hasItem = (p.item != null);
354     if (hasItem || (q = p.next) == null) {
355     updateHead(h, p);
356     return hasItem ? p : null;
357     }
358     else if (p == q)
359     continue restartFromHead;
360     else
361     p = q;
362 dl 1.1 }
363     }
364     }
365    
366 dl 1.28 /**
367 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
368 dl 1.28 *
369 jsr166 1.48 * @return {@code true} if this queue contains no elements
370 dl 1.28 */
371 dl 1.1 public boolean isEmpty() {
372     return first() == null;
373     }
374    
375     /**
376 dl 1.17 * Returns the number of elements in this queue. If this queue
377 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
378     * {@code Integer.MAX_VALUE}.
379 tim 1.2 *
380 dl 1.17 * <p>Beware that, unlike in most collections, this method is
381 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
382     * asynchronous nature of these queues, determining the current
383 jsr166 1.55 * number of elements requires an O(n) traversal.
384     * Additionally, if elements are added or removed during execution
385     * of this method, the returned result may be inaccurate. Thus,
386     * this method is typically not very useful in concurrent
387     * applications.
388 dl 1.17 *
389 jsr166 1.37 * @return the number of elements in this queue
390 tim 1.2 */
391 dl 1.1 public int size() {
392 jsr166 1.100 restartFromHead: for (;;) {
393     int count = 0;
394     for (Node<E> p = first(); p != null;) {
395     if (p.item != null)
396     if (++count == Integer.MAX_VALUE)
397     break; // @see Collection.size()
398 jsr166 1.116 if (p == (p = p.next))
399 jsr166 1.100 continue restartFromHead;
400     }
401     return count;
402     }
403 dl 1.1 }
404    
405 jsr166 1.37 /**
406 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
407     * More formally, returns {@code true} if and only if this queue contains
408     * at least one element {@code e} such that {@code o.equals(e)}.
409 jsr166 1.37 *
410     * @param o object to be checked for containment in this queue
411 jsr166 1.48 * @return {@code true} if this queue contains the specified element
412 jsr166 1.37 */
413 dholmes 1.6 public boolean contains(Object o) {
414 jsr166 1.103 if (o != null) {
415     for (Node<E> p = first(); p != null; p = succ(p)) {
416     E item = p.item;
417     if (item != null && o.equals(item))
418     return true;
419     }
420 dl 1.1 }
421     return false;
422     }
423    
424 jsr166 1.37 /**
425     * Removes a single instance of the specified element from this queue,
426 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
427     * that {@code o.equals(e)}, if this queue contains one or more such
428 jsr166 1.37 * elements.
429 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
430 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
431     *
432     * @param o element to be removed from this queue, if present
433 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
434 jsr166 1.37 */
435 dholmes 1.6 public boolean remove(Object o) {
436 jsr166 1.103 if (o != null) {
437 jsr166 1.110 Node<E> next, pred = null;
438     for (Node<E> p = first(); p != null; pred = p, p = next) {
439     boolean removed = false;
440 jsr166 1.103 E item = p.item;
441 jsr166 1.110 if (item != null) {
442     if (!o.equals(item)) {
443     next = succ(p);
444     continue;
445     }
446 dl 1.123 removed = ITEM.compareAndSet(p, item, null);
447 jsr166 1.110 }
448    
449     next = succ(p);
450     if (pred != null && next != null) // unlink
451 jsr166 1.129 NEXT.weakCompareAndSet(pred, p, next);
452 jsr166 1.110 if (removed)
453 jsr166 1.103 return true;
454 jsr166 1.48 }
455 dl 1.1 }
456     return false;
457     }
458 tim 1.2
459 jsr166 1.33 /**
460 jsr166 1.55 * Appends all of the elements in the specified collection to the end of
461     * this queue, in the order that they are returned by the specified
462 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
463     * itself result in {@code IllegalArgumentException}.
464 jsr166 1.55 *
465     * @param c the elements to be inserted into this queue
466     * @return {@code true} if this queue changed as a result of the call
467 jsr166 1.56 * @throws NullPointerException if the specified collection or any
468     * of its elements are null
469     * @throws IllegalArgumentException if the collection is this queue
470 jsr166 1.55 */
471     public boolean addAll(Collection<? extends E> c) {
472 jsr166 1.56 if (c == this)
473     // As historically specified in AbstractQueue#addAll
474     throw new IllegalArgumentException();
475    
476 jsr166 1.55 // Copy c into a private chain of Nodes
477 jsr166 1.65 Node<E> beginningOfTheEnd = null, last = null;
478 jsr166 1.55 for (E e : c) {
479 jsr166 1.118 Node<E> newNode = newNode(Objects.requireNonNull(e));
480 jsr166 1.65 if (beginningOfTheEnd == null)
481     beginningOfTheEnd = last = newNode;
482 jsr166 1.55 else {
483 jsr166 1.125 NEXT.set(last, newNode);
484 jsr166 1.55 last = newNode;
485     }
486     }
487 jsr166 1.65 if (beginningOfTheEnd == null)
488 jsr166 1.55 return false;
489    
490 jsr166 1.65 // Atomically append the chain at the tail of this collection
491     for (Node<E> t = tail, p = t;;) {
492     Node<E> q = p.next;
493     if (q == null) {
494     // p is last node
495 dl 1.123 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
496 jsr166 1.65 // Successful CAS is the linearization point
497     // for all elements to be added to this queue.
498 jsr166 1.129 if (!TAIL.weakCompareAndSet(this, t, last)) {
499 jsr166 1.55 // Try a little harder to update tail,
500     // since we may be adding many elements.
501     t = tail;
502     if (last.next == null)
503 jsr166 1.129 TAIL.weakCompareAndSet(this, t, last);
504 jsr166 1.55 }
505     return true;
506     }
507 jsr166 1.65 // Lost CAS race to another thread; re-read next
508 jsr166 1.55 }
509 jsr166 1.65 else if (p == q)
510     // We have fallen off list. If tail is unchanged, it
511     // will also be off-list, in which case we need to
512     // jump to head, from which all live nodes are always
513     // reachable. Else the new tail is a better bet.
514     p = (t != (t = tail)) ? t : head;
515     else
516     // Check for tail updates after two hops.
517     p = (p != t && t != (t = tail)) ? t : q;
518 jsr166 1.55 }
519     }
520    
521 jsr166 1.117 public String toString() {
522     String[] a = null;
523     restartFromHead: for (;;) {
524     int charLength = 0;
525     int size = 0;
526     for (Node<E> p = first(); p != null;) {
527     E item = p.item;
528     if (item != null) {
529     if (a == null)
530     a = new String[4];
531     else if (size == a.length)
532     a = Arrays.copyOf(a, 2 * size);
533     String s = item.toString();
534     a[size++] = s;
535     charLength += s.length();
536     }
537     if (p == (p = p.next))
538     continue restartFromHead;
539     }
540    
541     if (size == 0)
542     return "[]";
543    
544 jsr166 1.120 return Helpers.toString(a, size, charLength);
545 jsr166 1.117 }
546     }
547    
548     private Object[] toArrayInternal(Object[] a) {
549     Object[] x = a;
550     restartFromHead: for (;;) {
551     int size = 0;
552     for (Node<E> p = first(); p != null;) {
553     E item = p.item;
554     if (item != null) {
555     if (x == null)
556     x = new Object[4];
557     else if (size == x.length)
558     x = Arrays.copyOf(x, 2 * (size + 4));
559     x[size++] = item;
560     }
561     if (p == (p = p.next))
562     continue restartFromHead;
563     }
564     if (x == null)
565     return new Object[0];
566     else if (a != null && size <= a.length) {
567     if (a != x)
568     System.arraycopy(x, 0, a, 0, size);
569     if (size < a.length)
570     a[size] = null;
571     return a;
572     }
573     return (size == x.length) ? x : Arrays.copyOf(x, size);
574     }
575     }
576    
577 jsr166 1.55 /**
578 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
579     * proper sequence.
580     *
581     * <p>The returned array will be "safe" in that no references to it are
582     * maintained by this queue. (In other words, this method must allocate
583     * a new array). The caller is thus free to modify the returned array.
584     *
585     * <p>This method acts as bridge between array-based and collection-based
586     * APIs.
587     *
588     * @return an array containing all of the elements in this queue
589     */
590     public Object[] toArray() {
591 jsr166 1.117 return toArrayInternal(null);
592 jsr166 1.48 }
593    
594     /**
595     * Returns an array containing all of the elements in this queue, in
596     * proper sequence; the runtime type of the returned array is that of
597     * the specified array. If the queue fits in the specified array, it
598     * is returned therein. Otherwise, a new array is allocated with the
599     * runtime type of the specified array and the size of this queue.
600     *
601     * <p>If this queue fits in the specified array with room to spare
602     * (i.e., the array has more elements than this queue), the element in
603     * the array immediately following the end of the queue is set to
604     * {@code null}.
605     *
606     * <p>Like the {@link #toArray()} method, this method acts as bridge between
607     * array-based and collection-based APIs. Further, this method allows
608     * precise control over the runtime type of the output array, and may,
609     * under certain circumstances, be used to save allocation costs.
610     *
611     * <p>Suppose {@code x} is a queue known to contain only strings.
612     * The following code can be used to dump the queue into a newly
613     * allocated array of {@code String}:
614     *
615 jsr166 1.115 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
616 jsr166 1.48 *
617     * Note that {@code toArray(new Object[0])} is identical in function to
618     * {@code toArray()}.
619     *
620     * @param a the array into which the elements of the queue are to
621     * be stored, if it is big enough; otherwise, a new array of the
622     * same runtime type is allocated for this purpose
623     * @return an array containing all of the elements in this queue
624     * @throws ArrayStoreException if the runtime type of the specified array
625     * is not a supertype of the runtime type of every element in
626     * this queue
627     * @throws NullPointerException if the specified array is null
628     */
629     @SuppressWarnings("unchecked")
630     public <T> T[] toArray(T[] a) {
631 jsr166 1.117 if (a == null) throw new NullPointerException();
632     return (T[]) toArrayInternal(a);
633 jsr166 1.48 }
634    
635     /**
636 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
637 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
638     *
639 jsr166 1.98 * <p>The returned iterator is
640     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
641 dholmes 1.7 *
642 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
643 dholmes 1.7 */
644 dl 1.1 public Iterator<E> iterator() {
645     return new Itr();
646     }
647    
648     private class Itr implements Iterator<E> {
649     /**
650     * Next node to return item for.
651     */
652 dl 1.23 private Node<E> nextNode;
653 dl 1.1
654 tim 1.2 /**
655 dl 1.1 * nextItem holds on to item fields because once we claim
656     * that an element exists in hasNext(), we must return it in
657     * the following next() call even if it was in the process of
658     * being removed when hasNext() was called.
659 jsr166 1.29 */
660 dl 1.1 private E nextItem;
661    
662     /**
663     * Node of the last returned item, to support remove.
664     */
665 dl 1.23 private Node<E> lastRet;
666 dl 1.1
667 tim 1.2 Itr() {
668 jsr166 1.114 restartFromHead: for (;;) {
669     Node<E> h, p, q;
670     for (p = h = head;; p = q) {
671     E item;
672     if ((item = p.item) != null) {
673     nextNode = p;
674     nextItem = item;
675     break;
676     }
677     else if ((q = p.next) == null)
678     break;
679     else if (p == q)
680     continue restartFromHead;
681     }
682     updateHead(h, p);
683     return;
684     }
685 dl 1.1 }
686 tim 1.2
687 jsr166 1.114 public boolean hasNext() {
688     return nextItem != null;
689     }
690 dl 1.1
691 jsr166 1.114 public E next() {
692 jsr166 1.111 final Node<E> pred = nextNode;
693 jsr166 1.114 if (pred == null) throw new NoSuchElementException();
694     // assert nextItem != null;
695     lastRet = pred;
696     E item = null;
697 jsr166 1.48
698 jsr166 1.114 for (Node<E> p = succ(pred), q;; p = q) {
699     if (p == null || (item = p.item) != null) {
700 dl 1.1 nextNode = p;
701 jsr166 1.114 E x = nextItem;
702 dl 1.1 nextItem = item;
703 jsr166 1.114 return x;
704 jsr166 1.48 }
705 jsr166 1.114 // unlink deleted nodes
706     if ((q = succ(p)) != null)
707 dl 1.123 NEXT.compareAndSet(pred, p, q);
708 dl 1.1 }
709     }
710 tim 1.2
711 dl 1.1 public void remove() {
712 dl 1.23 Node<E> l = lastRet;
713 dl 1.1 if (l == null) throw new IllegalStateException();
714     // rely on a future traversal to relink.
715 jsr166 1.64 l.item = null;
716 dl 1.1 lastRet = null;
717     }
718     }
719    
720     /**
721 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
722 dl 1.1 *
723 jsr166 1.95 * @param s the stream
724 jsr166 1.96 * @throws java.io.IOException if an I/O error occurs
725 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
726 dl 1.1 * the proper order, followed by a null
727     */
728     private void writeObject(java.io.ObjectOutputStream s)
729     throws java.io.IOException {
730    
731     // Write out any hidden stuff
732     s.defaultWriteObject();
733 tim 1.2
734 dl 1.1 // Write out all elements in the proper order.
735 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
736 jsr166 1.64 Object item = p.item;
737 dl 1.1 if (item != null)
738     s.writeObject(item);
739     }
740    
741     // Use trailing null as sentinel
742     s.writeObject(null);
743     }
744    
745     /**
746 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
747 jsr166 1.95 * @param s the stream
748 jsr166 1.96 * @throws ClassNotFoundException if the class of a serialized object
749     * could not be found
750     * @throws java.io.IOException if an I/O error occurs
751 dl 1.1 */
752     private void readObject(java.io.ObjectInputStream s)
753     throws java.io.IOException, ClassNotFoundException {
754 tim 1.2 s.defaultReadObject();
755 jsr166 1.55
756     // Read in elements until trailing null sentinel found
757     Node<E> h = null, t = null;
758 jsr166 1.104 for (Object item; (item = s.readObject()) != null; ) {
759 jsr166 1.48 @SuppressWarnings("unchecked")
760 jsr166 1.102 Node<E> newNode = newNode((E) item);
761 jsr166 1.55 if (h == null)
762     h = t = newNode;
763     else {
764 jsr166 1.125 NEXT.set(t, newNode);
765 jsr166 1.55 t = newNode;
766     }
767 dl 1.1 }
768 jsr166 1.55 if (h == null)
769 jsr166 1.102 h = t = newNode(null);
770 jsr166 1.55 head = h;
771     tail = t;
772     }
773    
774 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
775 jsr166 1.130 final class CLQSpliterator implements Spliterator<E> {
776 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
777 dl 1.82 Node<E> current; // current node; null until initialized
778     int batch; // batch size for splits
779     boolean exhausted; // true when no more nodes
780    
781     public Spliterator<E> trySplit() {
782 dl 1.89 Node<E> p;
783     int b = batch;
784     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
785 jsr166 1.87 if (!exhausted &&
786 jsr166 1.130 ((p = current) != null || (p = first()) != null) &&
787 dl 1.83 p.next != null) {
788 dl 1.92 Object[] a = new Object[n];
789 dl 1.82 int i = 0;
790     do {
791     if ((a[i] = p.item) != null)
792     ++i;
793     if (p == (p = p.next))
794 jsr166 1.130 p = first();
795 dl 1.82 } while (p != null && i < n);
796     if ((current = p) == null)
797     exhausted = true;
798 dl 1.89 if (i > 0) {
799     batch = i;
800     return Spliterators.spliterator
801 jsr166 1.121 (a, 0, i, (Spliterator.ORDERED |
802     Spliterator.NONNULL |
803     Spliterator.CONCURRENT));
804 dl 1.89 }
805 dl 1.82 }
806     return null;
807     }
808    
809 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
810 dl 1.82 Node<E> p;
811     if (action == null) throw new NullPointerException();
812     if (!exhausted &&
813 jsr166 1.130 ((p = current) != null || (p = first()) != null)) {
814 dl 1.82 exhausted = true;
815     do {
816     E e = p.item;
817     if (p == (p = p.next))
818 jsr166 1.130 p = first();
819 dl 1.82 if (e != null)
820     action.accept(e);
821     } while (p != null);
822     }
823     }
824    
825     public boolean tryAdvance(Consumer<? super E> action) {
826     Node<E> p;
827     if (action == null) throw new NullPointerException();
828     if (!exhausted &&
829 jsr166 1.130 ((p = current) != null || (p = first()) != null)) {
830 dl 1.82 E e;
831     do {
832     e = p.item;
833     if (p == (p = p.next))
834 jsr166 1.130 p = first();
835 dl 1.82 } while (e == null && p != null);
836     if ((current = p) == null)
837     exhausted = true;
838     if (e != null) {
839     action.accept(e);
840     return true;
841     }
842     }
843     return false;
844     }
845    
846 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
847    
848 dl 1.82 public int characteristics() {
849     return Spliterator.ORDERED | Spliterator.NONNULL |
850     Spliterator.CONCURRENT;
851     }
852     }
853    
854 jsr166 1.97 /**
855     * Returns a {@link Spliterator} over the elements in this queue.
856     *
857 jsr166 1.98 * <p>The returned spliterator is
858     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
859     *
860 jsr166 1.97 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
861     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
862     *
863     * @implNote
864     * The {@code Spliterator} implements {@code trySplit} to permit limited
865     * parallelism.
866     *
867     * @return a {@code Spliterator} over the elements in this queue
868     * @since 1.8
869     */
870     @Override
871 dl 1.85 public Spliterator<E> spliterator() {
872 jsr166 1.130 return new CLQSpliterator();
873 dl 1.82 }
874    
875 dl 1.123 // VarHandle mechanics
876     private static final VarHandle HEAD;
877     private static final VarHandle TAIL;
878     private static final VarHandle ITEM;
879     private static final VarHandle NEXT;
880 dl 1.71 static {
881 jsr166 1.48 try {
882 dl 1.123 MethodHandles.Lookup l = MethodHandles.lookup();
883     HEAD = l.findVarHandle(ConcurrentLinkedQueue.class, "head",
884     Node.class);
885     TAIL = l.findVarHandle(ConcurrentLinkedQueue.class, "tail",
886     Node.class);
887     ITEM = l.findVarHandle(Node.class, "item", Object.class);
888     NEXT = l.findVarHandle(Node.class, "next", Node.class);
889 jsr166 1.108 } catch (ReflectiveOperationException e) {
890 dl 1.71 throw new Error(e);
891 jsr166 1.48 }
892     }
893 dl 1.1 }