ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.113
Committed: Sun Jan 18 16:34:02 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.112: +1 -0 lines
Log Message:
add an assert

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.55 private 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     Node<E> next = p.next;
411 jsr166 1.101 if (p == next)
412 jsr166 1.100 continue restartFromHead;
413     p = next;
414     }
415     return count;
416     }
417 dl 1.1 }
418    
419 jsr166 1.37 /**
420 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
421     * More formally, returns {@code true} if and only if this queue contains
422     * at least one element {@code e} such that {@code o.equals(e)}.
423 jsr166 1.37 *
424     * @param o object to be checked for containment in this queue
425 jsr166 1.48 * @return {@code true} if this queue contains the specified element
426 jsr166 1.37 */
427 dholmes 1.6 public boolean contains(Object o) {
428 jsr166 1.103 if (o != null) {
429     for (Node<E> p = first(); p != null; p = succ(p)) {
430     E item = p.item;
431     if (item != null && o.equals(item))
432     return true;
433     }
434 dl 1.1 }
435     return false;
436     }
437    
438 jsr166 1.37 /**
439     * Removes a single instance of the specified element from this queue,
440 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
441     * that {@code o.equals(e)}, if this queue contains one or more such
442 jsr166 1.37 * elements.
443 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
444 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
445     *
446     * @param o element to be removed from this queue, if present
447 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
448 jsr166 1.37 */
449 dholmes 1.6 public boolean remove(Object o) {
450 jsr166 1.103 if (o != null) {
451 jsr166 1.110 Node<E> next, pred = null;
452     for (Node<E> p = first(); p != null; pred = p, p = next) {
453     boolean removed = false;
454 jsr166 1.103 E item = p.item;
455 jsr166 1.110 if (item != null) {
456     if (!o.equals(item)) {
457     next = succ(p);
458     continue;
459     }
460     removed = casItem(p, item, null);
461     }
462    
463     next = succ(p);
464     if (pred != null && next != null) // unlink
465     casNext(pred, p, next);
466     if (removed)
467 jsr166 1.103 return true;
468 jsr166 1.48 }
469 dl 1.1 }
470     return false;
471     }
472 tim 1.2
473 jsr166 1.33 /**
474 jsr166 1.55 * Appends all of the elements in the specified collection to the end of
475     * this queue, in the order that they are returned by the specified
476 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
477     * itself result in {@code IllegalArgumentException}.
478 jsr166 1.55 *
479     * @param c the elements to be inserted into this queue
480     * @return {@code true} if this queue changed as a result of the call
481 jsr166 1.56 * @throws NullPointerException if the specified collection or any
482     * of its elements are null
483     * @throws IllegalArgumentException if the collection is this queue
484 jsr166 1.55 */
485     public boolean addAll(Collection<? extends E> c) {
486 jsr166 1.56 if (c == this)
487     // As historically specified in AbstractQueue#addAll
488     throw new IllegalArgumentException();
489    
490 jsr166 1.55 // Copy c into a private chain of Nodes
491 jsr166 1.65 Node<E> beginningOfTheEnd = null, last = null;
492 jsr166 1.55 for (E e : c) {
493     checkNotNull(e);
494 jsr166 1.102 Node<E> newNode = newNode(e);
495 jsr166 1.65 if (beginningOfTheEnd == null)
496     beginningOfTheEnd = last = newNode;
497 jsr166 1.55 else {
498 jsr166 1.102 lazySetNext(last, newNode);
499 jsr166 1.55 last = newNode;
500     }
501     }
502 jsr166 1.65 if (beginningOfTheEnd == null)
503 jsr166 1.55 return false;
504    
505 jsr166 1.65 // Atomically append the chain at the tail of this collection
506     for (Node<E> t = tail, p = t;;) {
507     Node<E> q = p.next;
508     if (q == null) {
509     // p is last node
510 jsr166 1.102 if (casNext(p, null, beginningOfTheEnd)) {
511 jsr166 1.65 // Successful CAS is the linearization point
512     // for all elements to be added to this queue.
513     if (!casTail(t, last)) {
514 jsr166 1.55 // Try a little harder to update tail,
515     // since we may be adding many elements.
516     t = tail;
517     if (last.next == null)
518     casTail(t, last);
519     }
520     return true;
521     }
522 jsr166 1.65 // Lost CAS race to another thread; re-read next
523 jsr166 1.55 }
524 jsr166 1.65 else if (p == q)
525     // We have fallen off list. If tail is unchanged, it
526     // will also be off-list, in which case we need to
527     // jump to head, from which all live nodes are always
528     // reachable. Else the new tail is a better bet.
529     p = (t != (t = tail)) ? t : head;
530     else
531     // Check for tail updates after two hops.
532     p = (p != t && t != (t = tail)) ? t : q;
533 jsr166 1.55 }
534     }
535    
536     /**
537 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
538     * proper sequence.
539     *
540     * <p>The returned array will be "safe" in that no references to it are
541     * maintained by this queue. (In other words, this method must allocate
542     * a new array). The caller is thus free to modify the returned array.
543     *
544     * <p>This method acts as bridge between array-based and collection-based
545     * APIs.
546     *
547     * @return an array containing all of the elements in this queue
548     */
549     public Object[] toArray() {
550     // Use ArrayList to deal with resizing.
551     ArrayList<E> al = new ArrayList<E>();
552     for (Node<E> p = first(); p != null; p = succ(p)) {
553 jsr166 1.64 E item = p.item;
554 jsr166 1.48 if (item != null)
555     al.add(item);
556     }
557     return al.toArray();
558     }
559    
560     /**
561     * Returns an array containing all of the elements in this queue, in
562     * proper sequence; the runtime type of the returned array is that of
563     * the specified array. If the queue fits in the specified array, it
564     * is returned therein. Otherwise, a new array is allocated with the
565     * runtime type of the specified array and the size of this queue.
566     *
567     * <p>If this queue fits in the specified array with room to spare
568     * (i.e., the array has more elements than this queue), the element in
569     * the array immediately following the end of the queue is set to
570     * {@code null}.
571     *
572     * <p>Like the {@link #toArray()} method, this method acts as bridge between
573     * array-based and collection-based APIs. Further, this method allows
574     * precise control over the runtime type of the output array, and may,
575     * under certain circumstances, be used to save allocation costs.
576     *
577     * <p>Suppose {@code x} is a queue known to contain only strings.
578     * The following code can be used to dump the queue into a newly
579     * allocated array of {@code String}:
580     *
581 jsr166 1.77 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
582 jsr166 1.48 *
583     * Note that {@code toArray(new Object[0])} is identical in function to
584     * {@code toArray()}.
585     *
586     * @param a the array into which the elements of the queue are to
587     * be stored, if it is big enough; otherwise, a new array of the
588     * same runtime type is allocated for this purpose
589     * @return an array containing all of the elements in this queue
590     * @throws ArrayStoreException if the runtime type of the specified array
591     * is not a supertype of the runtime type of every element in
592     * this queue
593     * @throws NullPointerException if the specified array is null
594     */
595     @SuppressWarnings("unchecked")
596     public <T> T[] toArray(T[] a) {
597     // try to use sent-in array
598     int k = 0;
599     Node<E> p;
600     for (p = first(); p != null && k < a.length; p = succ(p)) {
601 jsr166 1.64 E item = p.item;
602 jsr166 1.48 if (item != null)
603     a[k++] = (T)item;
604     }
605     if (p == null) {
606     if (k < a.length)
607     a[k] = null;
608     return a;
609     }
610    
611     // If won't fit, use ArrayList version
612     ArrayList<E> al = new ArrayList<E>();
613     for (Node<E> q = first(); q != null; q = succ(q)) {
614 jsr166 1.64 E item = q.item;
615 jsr166 1.48 if (item != null)
616     al.add(item);
617     }
618     return al.toArray(a);
619     }
620    
621     /**
622 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
623 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
624     *
625 jsr166 1.98 * <p>The returned iterator is
626     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
627 dholmes 1.7 *
628 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
629 dholmes 1.7 */
630 dl 1.1 public Iterator<E> iterator() {
631     return new Itr();
632     }
633    
634     private class Itr implements Iterator<E> {
635     /**
636     * Next node to return item for.
637     */
638 dl 1.23 private Node<E> nextNode;
639 dl 1.1
640 tim 1.2 /**
641 dl 1.1 * nextItem holds on to item fields because once we claim
642     * that an element exists in hasNext(), we must return it in
643     * the following next() call even if it was in the process of
644     * being removed when hasNext() was called.
645 jsr166 1.29 */
646 dl 1.1 private E nextItem;
647    
648     /**
649     * Node of the last returned item, to support remove.
650     */
651 dl 1.23 private Node<E> lastRet;
652 dl 1.1
653 tim 1.2 Itr() {
654 dl 1.1 advance();
655     }
656 tim 1.2
657 dl 1.1 /**
658 jsr166 1.111 * Moves to next valid node.
659 dl 1.1 */
660 jsr166 1.111 private void advance() {
661 dl 1.1 lastRet = nextNode;
662    
663 jsr166 1.111 final Node<E> pred = nextNode;
664 jsr166 1.48
665 jsr166 1.111 for (Node<E> p = (pred == null) ? first() : succ(pred);;) {
666 dl 1.1 if (p == null) {
667     nextNode = null;
668     nextItem = null;
669 jsr166 1.111 break;
670 dl 1.1 }
671 jsr166 1.64 E item = p.item;
672 dl 1.1 if (item != null) {
673     nextNode = p;
674     nextItem = item;
675 jsr166 1.111 break;
676 jsr166 1.48 } else {
677     // skip over nulls
678     Node<E> next = succ(p);
679     if (pred != null && next != null)
680 jsr166 1.102 casNext(pred, p, next);
681 jsr166 1.48 p = next;
682     }
683 dl 1.1 }
684     }
685 tim 1.2
686 dl 1.1 public boolean hasNext() {
687 jsr166 1.112 return nextItem != null;
688 dl 1.1 }
689 tim 1.2
690 dl 1.1 public E next() {
691 jsr166 1.111 E x = nextItem;
692     if (x == null) throw new NoSuchElementException();
693     advance();
694     return x;
695 dl 1.1 }
696 tim 1.2
697 dl 1.1 public void remove() {
698 dl 1.23 Node<E> l = lastRet;
699 dl 1.1 if (l == null) throw new IllegalStateException();
700     // rely on a future traversal to relink.
701 jsr166 1.64 l.item = null;
702 dl 1.1 lastRet = null;
703     }
704     }
705    
706     /**
707 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
708 dl 1.1 *
709 jsr166 1.95 * @param s the stream
710 jsr166 1.96 * @throws java.io.IOException if an I/O error occurs
711 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
712 dl 1.1 * the proper order, followed by a null
713     */
714     private void writeObject(java.io.ObjectOutputStream s)
715     throws java.io.IOException {
716    
717     // Write out any hidden stuff
718     s.defaultWriteObject();
719 tim 1.2
720 dl 1.1 // Write out all elements in the proper order.
721 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
722 jsr166 1.64 Object item = p.item;
723 dl 1.1 if (item != null)
724     s.writeObject(item);
725     }
726    
727     // Use trailing null as sentinel
728     s.writeObject(null);
729     }
730    
731     /**
732 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
733 jsr166 1.95 * @param s the stream
734 jsr166 1.96 * @throws ClassNotFoundException if the class of a serialized object
735     * could not be found
736     * @throws java.io.IOException if an I/O error occurs
737 dl 1.1 */
738     private void readObject(java.io.ObjectInputStream s)
739     throws java.io.IOException, ClassNotFoundException {
740 tim 1.2 s.defaultReadObject();
741 jsr166 1.55
742     // Read in elements until trailing null sentinel found
743     Node<E> h = null, t = null;
744 jsr166 1.104 for (Object item; (item = s.readObject()) != null; ) {
745 jsr166 1.48 @SuppressWarnings("unchecked")
746 jsr166 1.102 Node<E> newNode = newNode((E) item);
747 jsr166 1.55 if (h == null)
748     h = t = newNode;
749     else {
750 jsr166 1.102 lazySetNext(t, newNode);
751 jsr166 1.55 t = newNode;
752     }
753 dl 1.1 }
754 jsr166 1.55 if (h == null)
755 jsr166 1.102 h = t = newNode(null);
756 jsr166 1.55 head = h;
757     tail = t;
758     }
759    
760 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
761 dl 1.82 static final class CLQSpliterator<E> implements Spliterator<E> {
762 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
763 dl 1.82 final ConcurrentLinkedQueue<E> queue;
764     Node<E> current; // current node; null until initialized
765     int batch; // batch size for splits
766     boolean exhausted; // true when no more nodes
767     CLQSpliterator(ConcurrentLinkedQueue<E> queue) {
768     this.queue = queue;
769     }
770    
771     public Spliterator<E> trySplit() {
772 dl 1.89 Node<E> p;
773 dl 1.82 final ConcurrentLinkedQueue<E> q = this.queue;
774 dl 1.89 int b = batch;
775     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
776 jsr166 1.87 if (!exhausted &&
777 dl 1.83 ((p = current) != null || (p = q.first()) != null) &&
778     p.next != null) {
779 dl 1.92 Object[] a = new Object[n];
780 dl 1.82 int i = 0;
781     do {
782     if ((a[i] = p.item) != null)
783     ++i;
784     if (p == (p = p.next))
785     p = q.first();
786     } while (p != null && i < n);
787     if ((current = p) == null)
788     exhausted = true;
789 dl 1.89 if (i > 0) {
790     batch = i;
791     return Spliterators.spliterator
792     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
793     Spliterator.CONCURRENT);
794     }
795 dl 1.82 }
796     return null;
797     }
798    
799 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
800 dl 1.82 Node<E> p;
801     if (action == null) throw new NullPointerException();
802     final ConcurrentLinkedQueue<E> q = this.queue;
803     if (!exhausted &&
804     ((p = current) != null || (p = q.first()) != null)) {
805     exhausted = true;
806     do {
807     E e = p.item;
808     if (p == (p = p.next))
809     p = q.first();
810     if (e != null)
811     action.accept(e);
812     } while (p != null);
813     }
814     }
815    
816     public boolean tryAdvance(Consumer<? super E> action) {
817     Node<E> p;
818     if (action == null) throw new NullPointerException();
819     final ConcurrentLinkedQueue<E> q = this.queue;
820     if (!exhausted &&
821     ((p = current) != null || (p = q.first()) != null)) {
822     E e;
823     do {
824     e = p.item;
825     if (p == (p = p.next))
826     p = q.first();
827     } while (e == null && p != null);
828     if ((current = p) == null)
829     exhausted = true;
830     if (e != null) {
831     action.accept(e);
832     return true;
833     }
834     }
835     return false;
836     }
837    
838 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
839    
840 dl 1.82 public int characteristics() {
841     return Spliterator.ORDERED | Spliterator.NONNULL |
842     Spliterator.CONCURRENT;
843     }
844     }
845    
846 jsr166 1.97 /**
847     * Returns a {@link Spliterator} over the elements in this queue.
848     *
849 jsr166 1.98 * <p>The returned spliterator is
850     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
851     *
852 jsr166 1.97 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
853     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
854     *
855     * @implNote
856     * The {@code Spliterator} implements {@code trySplit} to permit limited
857     * parallelism.
858     *
859     * @return a {@code Spliterator} over the elements in this queue
860     * @since 1.8
861     */
862     @Override
863 dl 1.85 public Spliterator<E> spliterator() {
864 dl 1.82 return new CLQSpliterator<E>(this);
865     }
866    
867 jsr166 1.55 /**
868     * Throws NullPointerException if argument is null.
869     *
870     * @param v the element
871     */
872     private static void checkNotNull(Object v) {
873     if (v == null)
874     throw new NullPointerException();
875 dl 1.1 }
876    
877 jsr166 1.50 private boolean casTail(Node<E> cmp, Node<E> val) {
878 jsr166 1.102 return U.compareAndSwapObject(this, TAIL, cmp, val);
879 jsr166 1.50 }
880 dl 1.72
881 jsr166 1.50 private boolean casHead(Node<E> cmp, Node<E> val) {
882 jsr166 1.102 return U.compareAndSwapObject(this, HEAD, cmp, val);
883 jsr166 1.48 }
884 dl 1.72
885 dl 1.71 // Unsafe mechanics
886 dl 1.72
887 jsr166 1.109 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
888 jsr166 1.102 private static final long HEAD;
889     private static final long TAIL;
890     private static final long ITEM;
891     private static final long NEXT;
892 dl 1.71 static {
893 jsr166 1.48 try {
894 jsr166 1.109 HEAD = U.objectFieldOffset
895     (ConcurrentLinkedQueue.class.getDeclaredField("head"));
896     TAIL = U.objectFieldOffset
897     (ConcurrentLinkedQueue.class.getDeclaredField("tail"));
898     ITEM = U.objectFieldOffset
899     (Node.class.getDeclaredField("item"));
900     NEXT = U.objectFieldOffset
901     (Node.class.getDeclaredField("next"));
902 jsr166 1.108 } catch (ReflectiveOperationException e) {
903 dl 1.71 throw new Error(e);
904 jsr166 1.48 }
905     }
906 dl 1.1 }