ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.84
Committed: Tue Feb 26 17:28:00 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.83: +2 -2 lines
Log Message:
promote comments to actual javadoc

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