ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.116
Committed: Wed Feb 18 06:39:40 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.115: +1 -3 lines
Log Message:
use "standard" if (p == (p = p.next)) idiom

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