ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.117
Committed: Fri Feb 20 03:09:08 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.116: +75 -30 lines
Log Message:
improve toArray and toString implementations

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