ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.93
Committed: Mon Jun 17 17:17:05 2013 UTC (10 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.92: +1 -1 lines
Log Message:
inaccurate terminology; s/wait-free/non-blocking/

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 dl 1.82 import java.util.Arrays;
11 jsr166 1.51 import java.util.ArrayList;
12     import java.util.Collection;
13 dl 1.82 import java.util.Collections;
14 jsr166 1.51 import java.util.Iterator;
15     import java.util.NoSuchElementException;
16     import java.util.Queue;
17 dl 1.82 import java.util.Spliterator;
18 dl 1.83 import java.util.Spliterators;
19 dl 1.82 import java.util.stream.Stream;
20     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 dholmes 1.6 * algorithm based on one described in <a
38 dl 1.1 * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
39     * 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     * {@code equals}, 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 dl 1.21 * @param <E> the type of elements held in this collection
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.64 * for a volatile write to item by using Unsafe.putObject instead
143     * of a normal write. This allows the cost of enqueue to be
144 jsr166 1.48 * "one-and-a-half" CASes.
145     *
146     * Both head and tail may or may not point to a Node with a
147     * non-null item. If the queue is empty, all items must of course
148     * be null. Upon creation, both head and tail refer to a dummy
149     * Node with null item. Both head and tail are only updated using
150     * CAS, so they never regress, although again this is merely an
151     * optimization.
152 dl 1.1 */
153 jsr166 1.51
154 dl 1.23 private static class Node<E> {
155 jsr166 1.64 volatile E item;
156     volatile Node<E> next;
157 jsr166 1.29
158 jsr166 1.57 /**
159     * Constructs a new node. Uses relaxed write because item can
160     * only be seen after publication via casNext.
161     */
162 jsr166 1.51 Node(E item) {
163 jsr166 1.57 UNSAFE.putObject(this, itemOffset, item);
164 jsr166 1.51 }
165 jsr166 1.29
166 dl 1.22 boolean casItem(E cmp, E val) {
167 jsr166 1.50 return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
168 dl 1.13 }
169 jsr166 1.29
170 jsr166 1.48 void lazySetNext(Node<E> val) {
171 jsr166 1.50 UNSAFE.putOrderedObject(this, nextOffset, val);
172 dl 1.13 }
173 jsr166 1.29
174 dl 1.23 boolean casNext(Node<E> cmp, Node<E> val) {
175 jsr166 1.50 return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
176 dl 1.13 }
177 dl 1.1
178 jsr166 1.50 // Unsafe mechanics
179 dl 1.1
180 dl 1.71 private static final sun.misc.Unsafe UNSAFE;
181     private static final long itemOffset;
182     private static final long nextOffset;
183    
184     static {
185     try {
186     UNSAFE = sun.misc.Unsafe.getUnsafe();
187 jsr166 1.76 Class<?> k = Node.class;
188 dl 1.71 itemOffset = UNSAFE.objectFieldOffset
189     (k.getDeclaredField("item"));
190     nextOffset = UNSAFE.objectFieldOffset
191     (k.getDeclaredField("next"));
192     } catch (Exception e) {
193     throw new Error(e);
194     }
195     }
196 jsr166 1.48 }
197    
198 tim 1.2 /**
199 jsr166 1.51 * A node from which the first live (non-deleted) node (if any)
200     * can be reached in O(1) time.
201     * Invariants:
202     * - all live nodes are reachable from head via succ()
203     * - head != null
204     * - (tmp = head).next != tmp || tmp != head
205     * Non-invariants:
206     * - head.item may or may not be null.
207     * - it is permitted for tail to lag behind head, that is, for tail
208     * to not be reachable from head!
209 dl 1.1 */
210 jsr166 1.55 private transient volatile Node<E> head;
211 dl 1.1
212 jsr166 1.51 /**
213     * A node from which the last node on list (that is, the unique
214     * node with node.next == null) can be reached in O(1) time.
215     * Invariants:
216     * - the last node is always reachable from tail via succ()
217     * - tail != null
218     * Non-invariants:
219     * - tail.item may or may not be null.
220     * - it is permitted for tail to lag behind head, that is, for tail
221     * to not be reachable from head!
222     * - tail.next may or may not be self-pointing to tail.
223     */
224 jsr166 1.55 private transient volatile Node<E> tail;
225 dl 1.1
226     /**
227 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
228 dl 1.1 */
229 jsr166 1.55 public ConcurrentLinkedQueue() {
230     head = tail = new Node<E>(null);
231     }
232 dl 1.1
233     /**
234 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue}
235 dholmes 1.7 * initially containing the elements of the given collection,
236 dholmes 1.6 * added in traversal order of the collection's iterator.
237 jsr166 1.55 *
238 dholmes 1.6 * @param c the collection of elements to initially contain
239 jsr166 1.34 * @throws NullPointerException if the specified collection or any
240     * of its elements are null
241 dl 1.1 */
242 dholmes 1.6 public ConcurrentLinkedQueue(Collection<? extends E> c) {
243 jsr166 1.55 Node<E> h = null, t = null;
244     for (E e : c) {
245     checkNotNull(e);
246     Node<E> newNode = new Node<E>(e);
247     if (h == null)
248     h = t = newNode;
249     else {
250 jsr166 1.62 t.lazySetNext(newNode);
251 jsr166 1.55 t = newNode;
252     }
253     }
254     if (h == null)
255     h = t = new Node<E>(null);
256     head = h;
257     tail = t;
258 dl 1.1 }
259    
260 jsr166 1.29 // Have to override just to update the javadoc
261 dholmes 1.6
262     /**
263 jsr166 1.35 * Inserts the specified element at the tail of this queue.
264 jsr166 1.67 * As the queue is unbounded, this method will never throw
265     * {@link IllegalStateException} or return {@code false}.
266 dholmes 1.7 *
267 jsr166 1.48 * @return {@code true} (as specified by {@link Collection#add})
268 jsr166 1.32 * @throws NullPointerException if the specified element is null
269 dholmes 1.6 */
270 jsr166 1.31 public boolean add(E e) {
271     return offer(e);
272 dholmes 1.6 }
273    
274     /**
275 jsr166 1.81 * Tries to CAS head to p. If successful, repoint old head to itself
276 jsr166 1.48 * as sentinel for succ(), below.
277     */
278     final void updateHead(Node<E> h, Node<E> p) {
279     if (h != p && casHead(h, p))
280     h.lazySetNext(h);
281     }
282    
283     /**
284     * Returns the successor of p, or the head node if p.next has been
285     * linked to self, which will only be true if traversing with a
286     * stale pointer that is now off the list.
287     */
288     final Node<E> succ(Node<E> p) {
289 jsr166 1.55 Node<E> next = p.next;
290 jsr166 1.48 return (p == next) ? head : next;
291     }
292    
293     /**
294 jsr166 1.32 * Inserts the specified element at the tail of this queue.
295 jsr166 1.67 * As the queue is unbounded, this method will never return {@code false}.
296 dl 1.17 *
297 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
298 jsr166 1.32 * @throws NullPointerException if the specified element is null
299 dholmes 1.6 */
300 jsr166 1.31 public boolean offer(E e) {
301 jsr166 1.55 checkNotNull(e);
302 jsr166 1.60 final Node<E> newNode = new Node<E>(e);
303 jsr166 1.58
304 jsr166 1.65 for (Node<E> t = tail, p = t;;) {
305     Node<E> q = p.next;
306     if (q == null) {
307     // p is last node
308     if (p.casNext(null, newNode)) {
309 jsr166 1.63 // Successful CAS is the linearization point
310     // for e to become an element of this queue,
311     // and for newNode to become "live".
312 jsr166 1.65 if (p != t) // hop two nodes at a time
313 jsr166 1.58 casTail(t, newNode); // Failure is OK.
314 jsr166 1.48 return true;
315 dl 1.1 }
316 jsr166 1.65 // Lost CAS race to another thread; re-read next
317 dl 1.1 }
318 jsr166 1.65 else if (p == q)
319     // We have fallen off list. If tail is unchanged, it
320     // will also be off-list, in which case we need to
321     // jump to head, from which all live nodes are always
322     // reachable. Else the new tail is a better bet.
323     p = (t != (t = tail)) ? t : head;
324     else
325     // Check for tail updates after two hops.
326     p = (p != t && t != (t = tail)) ? t : q;
327 dl 1.1 }
328     }
329    
330     public E poll() {
331 jsr166 1.65 restartFromHead:
332     for (;;) {
333     for (Node<E> h = head, p = h, q;;) {
334     E item = p.item;
335 jsr166 1.48
336 jsr166 1.65 if (item != null && p.casItem(item, null)) {
337     // Successful CAS is the linearization point
338     // for item to be removed from this queue.
339     if (p != h) // hop two nodes at a time
340     updateHead(h, ((q = p.next) != null) ? q : p);
341     return item;
342     }
343     else if ((q = p.next) == null) {
344     updateHead(h, p);
345     return null;
346 dl 1.1 }
347 jsr166 1.65 else if (p == q)
348     continue restartFromHead;
349     else
350     p = q;
351 dl 1.1 }
352     }
353     }
354    
355 jsr166 1.48 public E peek() {
356 jsr166 1.65 restartFromHead:
357 dl 1.1 for (;;) {
358 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
359     E item = p.item;
360     if (item != null || (q = p.next) == null) {
361     updateHead(h, p);
362     return item;
363     }
364     else if (p == q)
365     continue restartFromHead;
366     else
367     p = q;
368 dl 1.1 }
369     }
370     }
371    
372     /**
373 jsr166 1.51 * Returns the first live (non-deleted) node on list, or null if none.
374     * This is yet another variant of poll/peek; here returning the
375     * first node, not element. We could make peek() a wrapper around
376     * first(), but that would cost an extra volatile read of item,
377     * and the need to add a retry loop to deal with the possibility
378     * of losing a race to a concurrent poll().
379 dl 1.1 */
380 dl 1.23 Node<E> first() {
381 jsr166 1.65 restartFromHead:
382 dl 1.1 for (;;) {
383 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
384     boolean hasItem = (p.item != null);
385     if (hasItem || (q = p.next) == null) {
386     updateHead(h, p);
387     return hasItem ? p : null;
388     }
389     else if (p == q)
390     continue restartFromHead;
391     else
392     p = q;
393 dl 1.1 }
394     }
395     }
396    
397 dl 1.28 /**
398 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
399 dl 1.28 *
400 jsr166 1.48 * @return {@code true} if this queue contains no elements
401 dl 1.28 */
402 dl 1.1 public boolean isEmpty() {
403     return first() == null;
404     }
405    
406     /**
407 dl 1.17 * Returns the number of elements in this queue. If this queue
408 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
409     * {@code Integer.MAX_VALUE}.
410 tim 1.2 *
411 dl 1.17 * <p>Beware that, unlike in most collections, this method is
412 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
413     * asynchronous nature of these queues, determining the current
414 jsr166 1.55 * number of elements requires an O(n) traversal.
415     * Additionally, if elements are added or removed during execution
416     * of this method, the returned result may be inaccurate. Thus,
417     * this method is typically not very useful in concurrent
418     * applications.
419 dl 1.17 *
420 jsr166 1.37 * @return the number of elements in this queue
421 tim 1.2 */
422 dl 1.1 public int size() {
423     int count = 0;
424 jsr166 1.64 for (Node<E> p = first(); p != null; p = succ(p))
425     if (p.item != null)
426     // Collection.size() spec says to max out
427 dl 1.8 if (++count == Integer.MAX_VALUE)
428     break;
429 dl 1.1 return count;
430     }
431    
432 jsr166 1.37 /**
433 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
434     * More formally, returns {@code true} if and only if this queue contains
435     * at least one element {@code e} such that {@code o.equals(e)}.
436 jsr166 1.37 *
437     * @param o object to be checked for containment in this queue
438 jsr166 1.48 * @return {@code true} if this queue contains the specified element
439 jsr166 1.37 */
440 dholmes 1.6 public boolean contains(Object o) {
441     if (o == null) return false;
442 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
443 jsr166 1.64 E item = p.item;
444 jsr166 1.65 if (item != null && o.equals(item))
445 dl 1.1 return true;
446     }
447     return false;
448     }
449    
450 jsr166 1.37 /**
451     * Removes a single instance of the specified element from this queue,
452 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
453     * that {@code o.equals(e)}, if this queue contains one or more such
454 jsr166 1.37 * elements.
455 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
456 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
457     *
458     * @param o element to be removed from this queue, if present
459 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
460 jsr166 1.37 */
461 dholmes 1.6 public boolean remove(Object o) {
462     if (o == null) return false;
463 jsr166 1.48 Node<E> pred = null;
464     for (Node<E> p = first(); p != null; p = succ(p)) {
465 jsr166 1.64 E item = p.item;
466 jsr166 1.51 if (item != null &&
467     o.equals(item) &&
468     p.casItem(item, null)) {
469 jsr166 1.48 Node<E> next = succ(p);
470     if (pred != null && next != null)
471     pred.casNext(p, next);
472 dl 1.1 return true;
473 jsr166 1.48 }
474     pred = p;
475 dl 1.1 }
476     return false;
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     checkNotNull(e);
500     Node<E> newNode = new Node<E>(e);
501 jsr166 1.65 if (beginningOfTheEnd == null)
502     beginningOfTheEnd = last = newNode;
503 jsr166 1.55 else {
504 jsr166 1.62 last.lazySetNext(newNode);
505 jsr166 1.55 last = newNode;
506     }
507     }
508 jsr166 1.65 if (beginningOfTheEnd == null)
509 jsr166 1.55 return false;
510    
511 jsr166 1.65 // Atomically append the chain at the tail of this collection
512     for (Node<E> t = tail, p = t;;) {
513     Node<E> q = p.next;
514     if (q == null) {
515     // p is last node
516     if (p.casNext(null, beginningOfTheEnd)) {
517     // Successful CAS is the linearization point
518     // for all elements to be added to this queue.
519     if (!casTail(t, last)) {
520 jsr166 1.55 // Try a little harder to update tail,
521     // since we may be adding many elements.
522     t = tail;
523     if (last.next == null)
524     casTail(t, last);
525     }
526     return true;
527     }
528 jsr166 1.65 // Lost CAS race to another thread; re-read next
529 jsr166 1.55 }
530 jsr166 1.65 else if (p == q)
531     // We have fallen off list. If tail is unchanged, it
532     // will also be off-list, in which case we need to
533     // jump to head, from which all live nodes are always
534     // reachable. Else the new tail is a better bet.
535     p = (t != (t = tail)) ? t : head;
536     else
537     // Check for tail updates after two hops.
538     p = (p != t && t != (t = tail)) ? t : q;
539 jsr166 1.55 }
540     }
541    
542     /**
543 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
544     * proper sequence.
545     *
546     * <p>The returned array will be "safe" in that no references to it are
547     * maintained by this queue. (In other words, this method must allocate
548     * a new array). The caller is thus free to modify the returned array.
549     *
550     * <p>This method acts as bridge between array-based and collection-based
551     * APIs.
552     *
553     * @return an array containing all of the elements in this queue
554     */
555     public Object[] toArray() {
556     // Use ArrayList to deal with resizing.
557     ArrayList<E> al = new ArrayList<E>();
558     for (Node<E> p = first(); p != null; p = succ(p)) {
559 jsr166 1.64 E item = p.item;
560 jsr166 1.48 if (item != null)
561     al.add(item);
562     }
563     return al.toArray();
564     }
565    
566     /**
567     * Returns an array containing all of the elements in this queue, in
568     * proper sequence; the runtime type of the returned array is that of
569     * the specified array. If the queue fits in the specified array, it
570     * is returned therein. Otherwise, a new array is allocated with the
571     * runtime type of the specified array and the size of this queue.
572     *
573     * <p>If this queue fits in the specified array with room to spare
574     * (i.e., the array has more elements than this queue), the element in
575     * the array immediately following the end of the queue is set to
576     * {@code null}.
577     *
578     * <p>Like the {@link #toArray()} method, this method acts as bridge between
579     * array-based and collection-based APIs. Further, this method allows
580     * precise control over the runtime type of the output array, and may,
581     * under certain circumstances, be used to save allocation costs.
582     *
583     * <p>Suppose {@code x} is a queue known to contain only strings.
584     * The following code can be used to dump the queue into a newly
585     * allocated array of {@code String}:
586     *
587 jsr166 1.77 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
588 jsr166 1.48 *
589     * Note that {@code toArray(new Object[0])} is identical in function to
590     * {@code toArray()}.
591     *
592     * @param a the array into which the elements of the queue are to
593     * be stored, if it is big enough; otherwise, a new array of the
594     * same runtime type is allocated for this purpose
595     * @return an array containing all of the elements in this queue
596     * @throws ArrayStoreException if the runtime type of the specified array
597     * is not a supertype of the runtime type of every element in
598     * this queue
599     * @throws NullPointerException if the specified array is null
600     */
601     @SuppressWarnings("unchecked")
602     public <T> T[] toArray(T[] a) {
603     // try to use sent-in array
604     int k = 0;
605     Node<E> p;
606     for (p = first(); p != null && k < a.length; p = succ(p)) {
607 jsr166 1.64 E item = p.item;
608 jsr166 1.48 if (item != null)
609     a[k++] = (T)item;
610     }
611     if (p == null) {
612     if (k < a.length)
613     a[k] = null;
614     return a;
615     }
616    
617     // If won't fit, use ArrayList version
618     ArrayList<E> al = new ArrayList<E>();
619     for (Node<E> q = first(); q != null; q = succ(q)) {
620 jsr166 1.64 E item = q.item;
621 jsr166 1.48 if (item != null)
622     al.add(item);
623     }
624     return al.toArray(a);
625     }
626    
627     /**
628 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
629 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
630     *
631 jsr166 1.70 * <p>The returned iterator is a "weakly consistent" iterator that
632 jsr166 1.52 * will never throw {@link java.util.ConcurrentModificationException
633 jsr166 1.70 * ConcurrentModificationException}, and guarantees to traverse
634     * elements as they existed upon construction of the iterator, and
635     * may (but is not guaranteed to) reflect any modifications
636     * subsequent to construction.
637 dholmes 1.7 *
638 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
639 dholmes 1.7 */
640 dl 1.1 public Iterator<E> iterator() {
641     return new Itr();
642     }
643    
644     private class Itr implements Iterator<E> {
645     /**
646     * Next node to return item for.
647     */
648 dl 1.23 private Node<E> nextNode;
649 dl 1.1
650 tim 1.2 /**
651 dl 1.1 * nextItem holds on to item fields because once we claim
652     * that an element exists in hasNext(), we must return it in
653     * the following next() call even if it was in the process of
654     * being removed when hasNext() was called.
655 jsr166 1.29 */
656 dl 1.1 private E nextItem;
657    
658     /**
659     * Node of the last returned item, to support remove.
660     */
661 dl 1.23 private Node<E> lastRet;
662 dl 1.1
663 tim 1.2 Itr() {
664 dl 1.1 advance();
665     }
666 tim 1.2
667 dl 1.1 /**
668 dl 1.26 * Moves to next valid node and returns item to return for
669     * next(), or null if no such.
670 dl 1.1 */
671 tim 1.2 private E advance() {
672 dl 1.1 lastRet = nextNode;
673 dl 1.22 E x = nextItem;
674 dl 1.1
675 jsr166 1.48 Node<E> pred, p;
676     if (nextNode == null) {
677     p = first();
678     pred = null;
679     } else {
680     pred = nextNode;
681     p = succ(nextNode);
682     }
683    
684 dl 1.1 for (;;) {
685     if (p == null) {
686     nextNode = null;
687     nextItem = null;
688     return x;
689     }
690 jsr166 1.64 E item = p.item;
691 dl 1.1 if (item != null) {
692     nextNode = p;
693     nextItem = item;
694     return x;
695 jsr166 1.48 } else {
696     // skip over nulls
697     Node<E> next = succ(p);
698     if (pred != null && next != null)
699     pred.casNext(p, next);
700     p = next;
701     }
702 dl 1.1 }
703     }
704 tim 1.2
705 dl 1.1 public boolean hasNext() {
706     return nextNode != null;
707     }
708 tim 1.2
709 dl 1.1 public E next() {
710     if (nextNode == null) throw new NoSuchElementException();
711     return advance();
712     }
713 tim 1.2
714 dl 1.1 public void remove() {
715 dl 1.23 Node<E> l = lastRet;
716 dl 1.1 if (l == null) throw new IllegalStateException();
717     // rely on a future traversal to relink.
718 jsr166 1.64 l.item = null;
719 dl 1.1 lastRet = null;
720     }
721     }
722    
723     /**
724 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
725 dl 1.1 *
726 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
727 dl 1.1 * the proper order, followed by a null
728     */
729     private void writeObject(java.io.ObjectOutputStream s)
730     throws java.io.IOException {
731    
732     // Write out any hidden stuff
733     s.defaultWriteObject();
734 tim 1.2
735 dl 1.1 // Write out all elements in the proper order.
736 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
737 jsr166 1.64 Object item = p.item;
738 dl 1.1 if (item != null)
739     s.writeObject(item);
740     }
741    
742     // Use trailing null as sentinel
743     s.writeObject(null);
744     }
745    
746     /**
747 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
748 dl 1.1 */
749     private void readObject(java.io.ObjectInputStream s)
750     throws java.io.IOException, ClassNotFoundException {
751 tim 1.2 s.defaultReadObject();
752 jsr166 1.55
753     // Read in elements until trailing null sentinel found
754     Node<E> h = null, t = null;
755     Object item;
756     while ((item = s.readObject()) != null) {
757 jsr166 1.48 @SuppressWarnings("unchecked")
758 jsr166 1.55 Node<E> newNode = new Node<E>((E) item);
759     if (h == null)
760     h = t = newNode;
761     else {
762 jsr166 1.62 t.lazySetNext(newNode);
763 jsr166 1.55 t = newNode;
764     }
765 dl 1.1 }
766 jsr166 1.55 if (h == null)
767     h = t = new Node<E>(null);
768     head = h;
769     tail = t;
770     }
771    
772 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
773 dl 1.82 static final class CLQSpliterator<E> implements Spliterator<E> {
774 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
775 dl 1.82 final ConcurrentLinkedQueue<E> queue;
776     Node<E> current; // current node; null until initialized
777     int batch; // batch size for splits
778     boolean exhausted; // true when no more nodes
779     CLQSpliterator(ConcurrentLinkedQueue<E> queue) {
780     this.queue = queue;
781     }
782    
783     public Spliterator<E> trySplit() {
784 dl 1.89 Node<E> p;
785 dl 1.82 final ConcurrentLinkedQueue<E> q = this.queue;
786 dl 1.89 int b = batch;
787     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
788 jsr166 1.87 if (!exhausted &&
789 dl 1.83 ((p = current) != null || (p = q.first()) != null) &&
790     p.next != null) {
791 dl 1.92 Object[] a = new Object[n];
792 dl 1.82 int i = 0;
793     do {
794     if ((a[i] = p.item) != null)
795     ++i;
796     if (p == (p = p.next))
797     p = q.first();
798     } while (p != null && i < n);
799     if ((current = p) == null)
800     exhausted = true;
801 dl 1.89 if (i > 0) {
802     batch = i;
803     return Spliterators.spliterator
804     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
805     Spliterator.CONCURRENT);
806     }
807 dl 1.82 }
808     return null;
809     }
810    
811 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
812 dl 1.82 Node<E> p;
813     if (action == null) throw new NullPointerException();
814     final ConcurrentLinkedQueue<E> q = this.queue;
815     if (!exhausted &&
816     ((p = current) != null || (p = q.first()) != null)) {
817     exhausted = true;
818     do {
819     E e = p.item;
820     if (p == (p = p.next))
821     p = q.first();
822     if (e != null)
823     action.accept(e);
824     } while (p != null);
825     }
826     }
827    
828     public boolean tryAdvance(Consumer<? super E> action) {
829     Node<E> p;
830     if (action == null) throw new NullPointerException();
831     final ConcurrentLinkedQueue<E> q = this.queue;
832     if (!exhausted &&
833     ((p = current) != null || (p = q.first()) != null)) {
834     E e;
835     do {
836     e = p.item;
837     if (p == (p = p.next))
838     p = q.first();
839     } while (e == null && p != null);
840     if ((current = p) == null)
841     exhausted = true;
842     if (e != null) {
843     action.accept(e);
844     return true;
845     }
846     }
847     return false;
848     }
849    
850 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
851    
852 dl 1.82 public int characteristics() {
853     return Spliterator.ORDERED | Spliterator.NONNULL |
854     Spliterator.CONCURRENT;
855     }
856     }
857    
858    
859 dl 1.85 public Spliterator<E> spliterator() {
860 dl 1.82 return new CLQSpliterator<E>(this);
861     }
862    
863 jsr166 1.55 /**
864     * Throws NullPointerException if argument is null.
865     *
866     * @param v the element
867     */
868     private static void checkNotNull(Object v) {
869     if (v == null)
870     throw new NullPointerException();
871 dl 1.1 }
872    
873 jsr166 1.50 private boolean casTail(Node<E> cmp, Node<E> val) {
874     return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
875     }
876 dl 1.72
877 jsr166 1.50 private boolean casHead(Node<E> cmp, Node<E> val) {
878     return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
879 jsr166 1.48 }
880 dl 1.72
881 dl 1.71 // Unsafe mechanics
882 dl 1.72
883 dl 1.71 private static final sun.misc.Unsafe UNSAFE;
884     private static final long headOffset;
885     private static final long tailOffset;
886     static {
887 jsr166 1.48 try {
888 dl 1.71 UNSAFE = sun.misc.Unsafe.getUnsafe();
889 jsr166 1.76 Class<?> k = ConcurrentLinkedQueue.class;
890 dl 1.71 headOffset = UNSAFE.objectFieldOffset
891     (k.getDeclaredField("head"));
892     tailOffset = UNSAFE.objectFieldOffset
893     (k.getDeclaredField("tail"));
894     } catch (Exception e) {
895     throw new Error(e);
896 jsr166 1.48 }
897     }
898 dl 1.1 }