ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.108
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.107: +1 -1 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

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     if (h != p && casHead(h, p))
260 jsr166 1.102 lazySetNext(h, h);
261 jsr166 1.48 }
262    
263     /**
264     * Returns the successor of p, or the head node if p.next has been
265     * linked to self, which will only be true if traversing with a
266     * stale pointer that is now off the list.
267     */
268     final Node<E> succ(Node<E> p) {
269 jsr166 1.55 Node<E> next = p.next;
270 jsr166 1.48 return (p == next) ? head : next;
271     }
272    
273     /**
274 jsr166 1.32 * Inserts the specified element at the tail of this queue.
275 jsr166 1.67 * As the queue is unbounded, this method will never return {@code false}.
276 dl 1.17 *
277 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
278 jsr166 1.32 * @throws NullPointerException if the specified element is null
279 dholmes 1.6 */
280 jsr166 1.31 public boolean offer(E e) {
281 jsr166 1.55 checkNotNull(e);
282 jsr166 1.102 final Node<E> newNode = newNode(e);
283 jsr166 1.58
284 jsr166 1.65 for (Node<E> t = tail, p = t;;) {
285     Node<E> q = p.next;
286     if (q == null) {
287     // p is last node
288 jsr166 1.102 if (casNext(p, null, newNode)) {
289 jsr166 1.63 // Successful CAS is the linearization point
290     // for e to become an element of this queue,
291     // and for newNode to become "live".
292 jsr166 1.65 if (p != t) // hop two nodes at a time
293 jsr166 1.58 casTail(t, newNode); // Failure is OK.
294 jsr166 1.48 return true;
295 dl 1.1 }
296 jsr166 1.65 // Lost CAS race to another thread; re-read next
297 dl 1.1 }
298 jsr166 1.65 else if (p == q)
299     // We have fallen off list. If tail is unchanged, it
300     // will also be off-list, in which case we need to
301     // jump to head, from which all live nodes are always
302     // reachable. Else the new tail is a better bet.
303     p = (t != (t = tail)) ? t : head;
304     else
305     // Check for tail updates after two hops.
306     p = (p != t && t != (t = tail)) ? t : q;
307 dl 1.1 }
308     }
309    
310     public E poll() {
311 jsr166 1.65 restartFromHead:
312     for (;;) {
313     for (Node<E> h = head, p = h, q;;) {
314     E item = p.item;
315 jsr166 1.48
316 jsr166 1.102 if (item != null && casItem(p, item, null)) {
317 jsr166 1.65 // Successful CAS is the linearization point
318     // for item to be removed from this queue.
319     if (p != h) // hop two nodes at a time
320     updateHead(h, ((q = p.next) != null) ? q : p);
321     return item;
322     }
323     else if ((q = p.next) == null) {
324     updateHead(h, p);
325     return null;
326 dl 1.1 }
327 jsr166 1.65 else if (p == q)
328     continue restartFromHead;
329     else
330     p = q;
331 dl 1.1 }
332     }
333     }
334    
335 jsr166 1.48 public E peek() {
336 jsr166 1.65 restartFromHead:
337 dl 1.1 for (;;) {
338 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
339     E item = p.item;
340     if (item != null || (q = p.next) == null) {
341     updateHead(h, p);
342     return item;
343     }
344     else if (p == q)
345     continue restartFromHead;
346     else
347     p = q;
348 dl 1.1 }
349     }
350     }
351    
352     /**
353 jsr166 1.51 * Returns the first live (non-deleted) node on list, or null if none.
354     * This is yet another variant of poll/peek; here returning the
355     * first node, not element. We could make peek() a wrapper around
356     * first(), but that would cost an extra volatile read of item,
357     * and the need to add a retry loop to deal with the possibility
358     * of losing a race to a concurrent poll().
359 dl 1.1 */
360 dl 1.23 Node<E> first() {
361 jsr166 1.65 restartFromHead:
362 dl 1.1 for (;;) {
363 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
364     boolean hasItem = (p.item != null);
365     if (hasItem || (q = p.next) == null) {
366     updateHead(h, p);
367     return hasItem ? p : null;
368     }
369     else if (p == q)
370     continue restartFromHead;
371     else
372     p = q;
373 dl 1.1 }
374     }
375     }
376    
377 dl 1.28 /**
378 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
379 dl 1.28 *
380 jsr166 1.48 * @return {@code true} if this queue contains no elements
381 dl 1.28 */
382 dl 1.1 public boolean isEmpty() {
383     return first() == null;
384     }
385    
386     /**
387 dl 1.17 * Returns the number of elements in this queue. If this queue
388 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
389     * {@code Integer.MAX_VALUE}.
390 tim 1.2 *
391 dl 1.17 * <p>Beware that, unlike in most collections, this method is
392 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
393     * asynchronous nature of these queues, determining the current
394 jsr166 1.55 * number of elements requires an O(n) traversal.
395     * Additionally, if elements are added or removed during execution
396     * of this method, the returned result may be inaccurate. Thus,
397     * this method is typically not very useful in concurrent
398     * applications.
399 dl 1.17 *
400 jsr166 1.37 * @return the number of elements in this queue
401 tim 1.2 */
402 dl 1.1 public int size() {
403 jsr166 1.100 restartFromHead: for (;;) {
404     int count = 0;
405     for (Node<E> p = first(); p != null;) {
406     if (p.item != null)
407     if (++count == Integer.MAX_VALUE)
408     break; // @see Collection.size()
409     Node<E> next = p.next;
410 jsr166 1.101 if (p == next)
411 jsr166 1.100 continue restartFromHead;
412     p = next;
413     }
414     return count;
415     }
416 dl 1.1 }
417    
418 jsr166 1.37 /**
419 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
420     * More formally, returns {@code true} if and only if this queue contains
421     * at least one element {@code e} such that {@code o.equals(e)}.
422 jsr166 1.37 *
423     * @param o object to be checked for containment in this queue
424 jsr166 1.48 * @return {@code true} if this queue contains the specified element
425 jsr166 1.37 */
426 dholmes 1.6 public boolean contains(Object o) {
427 jsr166 1.103 if (o != null) {
428     for (Node<E> p = first(); p != null; p = succ(p)) {
429     E item = p.item;
430     if (item != null && o.equals(item))
431     return true;
432     }
433 dl 1.1 }
434     return false;
435     }
436    
437 jsr166 1.37 /**
438     * Removes a single instance of the specified element from this queue,
439 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
440     * that {@code o.equals(e)}, if this queue contains one or more such
441 jsr166 1.37 * elements.
442 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
443 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
444     *
445     * @param o element to be removed from this queue, if present
446 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
447 jsr166 1.37 */
448 dholmes 1.6 public boolean remove(Object o) {
449 jsr166 1.103 if (o != null) {
450     Node<E> pred = null;
451     for (Node<E> p = first(); p != null; p = succ(p)) {
452     E item = p.item;
453     if (item != null &&
454     o.equals(item) &&
455     casItem(p, item, null)) {
456     Node<E> next = succ(p);
457     if (pred != null && next != null)
458     casNext(pred, p, next);
459     return true;
460     }
461     pred = p;
462 jsr166 1.48 }
463 dl 1.1 }
464     return false;
465     }
466 tim 1.2
467 jsr166 1.33 /**
468 jsr166 1.55 * Appends all of the elements in the specified collection to the end of
469     * this queue, in the order that they are returned by the specified
470 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
471     * itself result in {@code IllegalArgumentException}.
472 jsr166 1.55 *
473     * @param c the elements to be inserted into this queue
474     * @return {@code true} if this queue changed as a result of the call
475 jsr166 1.56 * @throws NullPointerException if the specified collection or any
476     * of its elements are null
477     * @throws IllegalArgumentException if the collection is this queue
478 jsr166 1.55 */
479     public boolean addAll(Collection<? extends E> c) {
480 jsr166 1.56 if (c == this)
481     // As historically specified in AbstractQueue#addAll
482     throw new IllegalArgumentException();
483    
484 jsr166 1.55 // Copy c into a private chain of Nodes
485 jsr166 1.65 Node<E> beginningOfTheEnd = null, last = null;
486 jsr166 1.55 for (E e : c) {
487     checkNotNull(e);
488 jsr166 1.102 Node<E> newNode = newNode(e);
489 jsr166 1.65 if (beginningOfTheEnd == null)
490     beginningOfTheEnd = last = newNode;
491 jsr166 1.55 else {
492 jsr166 1.102 lazySetNext(last, newNode);
493 jsr166 1.55 last = newNode;
494     }
495     }
496 jsr166 1.65 if (beginningOfTheEnd == null)
497 jsr166 1.55 return false;
498    
499 jsr166 1.65 // Atomically append the chain at the tail of this collection
500     for (Node<E> t = tail, p = t;;) {
501     Node<E> q = p.next;
502     if (q == null) {
503     // p is last node
504 jsr166 1.102 if (casNext(p, null, beginningOfTheEnd)) {
505 jsr166 1.65 // Successful CAS is the linearization point
506     // for all elements to be added to this queue.
507     if (!casTail(t, last)) {
508 jsr166 1.55 // Try a little harder to update tail,
509     // since we may be adding many elements.
510     t = tail;
511     if (last.next == null)
512     casTail(t, last);
513     }
514     return true;
515     }
516 jsr166 1.65 // Lost CAS race to another thread; re-read next
517 jsr166 1.55 }
518 jsr166 1.65 else if (p == q)
519     // We have fallen off list. If tail is unchanged, it
520     // will also be off-list, in which case we need to
521     // jump to head, from which all live nodes are always
522     // reachable. Else the new tail is a better bet.
523     p = (t != (t = tail)) ? t : head;
524     else
525     // Check for tail updates after two hops.
526     p = (p != t && t != (t = tail)) ? t : q;
527 jsr166 1.55 }
528     }
529    
530     /**
531 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
532     * proper sequence.
533     *
534     * <p>The returned array will be "safe" in that no references to it are
535     * maintained by this queue. (In other words, this method must allocate
536     * a new array). The caller is thus free to modify the returned array.
537     *
538     * <p>This method acts as bridge between array-based and collection-based
539     * APIs.
540     *
541     * @return an array containing all of the elements in this queue
542     */
543     public Object[] toArray() {
544     // Use ArrayList to deal with resizing.
545     ArrayList<E> al = new ArrayList<E>();
546     for (Node<E> p = first(); p != null; p = succ(p)) {
547 jsr166 1.64 E item = p.item;
548 jsr166 1.48 if (item != null)
549     al.add(item);
550     }
551     return al.toArray();
552     }
553    
554     /**
555     * Returns an array containing all of the elements in this queue, in
556     * proper sequence; the runtime type of the returned array is that of
557     * the specified array. If the queue fits in the specified array, it
558     * is returned therein. Otherwise, a new array is allocated with the
559     * runtime type of the specified array and the size of this queue.
560     *
561     * <p>If this queue fits in the specified array with room to spare
562     * (i.e., the array has more elements than this queue), the element in
563     * the array immediately following the end of the queue is set to
564     * {@code null}.
565     *
566     * <p>Like the {@link #toArray()} method, this method acts as bridge between
567     * array-based and collection-based APIs. Further, this method allows
568     * precise control over the runtime type of the output array, and may,
569     * under certain circumstances, be used to save allocation costs.
570     *
571     * <p>Suppose {@code x} is a queue known to contain only strings.
572     * The following code can be used to dump the queue into a newly
573     * allocated array of {@code String}:
574     *
575 jsr166 1.77 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
576 jsr166 1.48 *
577     * Note that {@code toArray(new Object[0])} is identical in function to
578     * {@code toArray()}.
579     *
580     * @param a the array into which the elements of the queue are to
581     * be stored, if it is big enough; otherwise, a new array of the
582     * same runtime type is allocated for this purpose
583     * @return an array containing all of the elements in this queue
584     * @throws ArrayStoreException if the runtime type of the specified array
585     * is not a supertype of the runtime type of every element in
586     * this queue
587     * @throws NullPointerException if the specified array is null
588     */
589     @SuppressWarnings("unchecked")
590     public <T> T[] toArray(T[] a) {
591     // try to use sent-in array
592     int k = 0;
593     Node<E> p;
594     for (p = first(); p != null && k < a.length; p = succ(p)) {
595 jsr166 1.64 E item = p.item;
596 jsr166 1.48 if (item != null)
597     a[k++] = (T)item;
598     }
599     if (p == null) {
600     if (k < a.length)
601     a[k] = null;
602     return a;
603     }
604    
605     // If won't fit, use ArrayList version
606     ArrayList<E> al = new ArrayList<E>();
607     for (Node<E> q = first(); q != null; q = succ(q)) {
608 jsr166 1.64 E item = q.item;
609 jsr166 1.48 if (item != null)
610     al.add(item);
611     }
612     return al.toArray(a);
613     }
614    
615     /**
616 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
617 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
618     *
619 jsr166 1.98 * <p>The returned iterator is
620     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
621 dholmes 1.7 *
622 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
623 dholmes 1.7 */
624 dl 1.1 public Iterator<E> iterator() {
625     return new Itr();
626     }
627    
628     private class Itr implements Iterator<E> {
629     /**
630     * Next node to return item for.
631     */
632 dl 1.23 private Node<E> nextNode;
633 dl 1.1
634 tim 1.2 /**
635 dl 1.1 * nextItem holds on to item fields because once we claim
636     * that an element exists in hasNext(), we must return it in
637     * the following next() call even if it was in the process of
638     * being removed when hasNext() was called.
639 jsr166 1.29 */
640 dl 1.1 private E nextItem;
641    
642     /**
643     * Node of the last returned item, to support remove.
644     */
645 dl 1.23 private Node<E> lastRet;
646 dl 1.1
647 tim 1.2 Itr() {
648 dl 1.1 advance();
649     }
650 tim 1.2
651 dl 1.1 /**
652 dl 1.26 * Moves to next valid node and returns item to return for
653     * next(), or null if no such.
654 dl 1.1 */
655 tim 1.2 private E advance() {
656 dl 1.1 lastRet = nextNode;
657 dl 1.22 E x = nextItem;
658 dl 1.1
659 jsr166 1.48 Node<E> pred, p;
660     if (nextNode == null) {
661     p = first();
662     pred = null;
663     } else {
664     pred = nextNode;
665     p = succ(nextNode);
666     }
667    
668 dl 1.1 for (;;) {
669     if (p == null) {
670     nextNode = null;
671     nextItem = null;
672     return x;
673     }
674 jsr166 1.64 E item = p.item;
675 dl 1.1 if (item != null) {
676     nextNode = p;
677     nextItem = item;
678     return x;
679 jsr166 1.48 } else {
680     // skip over nulls
681     Node<E> next = succ(p);
682     if (pred != null && next != null)
683 jsr166 1.102 casNext(pred, p, next);
684 jsr166 1.48 p = next;
685     }
686 dl 1.1 }
687     }
688 tim 1.2
689 dl 1.1 public boolean hasNext() {
690     return nextNode != null;
691     }
692 tim 1.2
693 dl 1.1 public E next() {
694     if (nextNode == null) throw new NoSuchElementException();
695     return advance();
696     }
697 tim 1.2
698 dl 1.1 public void remove() {
699 dl 1.23 Node<E> l = lastRet;
700 dl 1.1 if (l == null) throw new IllegalStateException();
701     // rely on a future traversal to relink.
702 jsr166 1.64 l.item = null;
703 dl 1.1 lastRet = null;
704     }
705     }
706    
707     /**
708 jsr166 1.79 * Saves this queue to a stream (that is, serializes it).
709 dl 1.1 *
710 jsr166 1.95 * @param s the stream
711 jsr166 1.96 * @throws java.io.IOException if an I/O error occurs
712 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
713 dl 1.1 * the proper order, followed by a null
714     */
715     private void writeObject(java.io.ObjectOutputStream s)
716     throws java.io.IOException {
717    
718     // Write out any hidden stuff
719     s.defaultWriteObject();
720 tim 1.2
721 dl 1.1 // Write out all elements in the proper order.
722 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
723 jsr166 1.64 Object item = p.item;
724 dl 1.1 if (item != null)
725     s.writeObject(item);
726     }
727    
728     // Use trailing null as sentinel
729     s.writeObject(null);
730     }
731    
732     /**
733 jsr166 1.79 * Reconstitutes this queue from a stream (that is, deserializes it).
734 jsr166 1.95 * @param s the stream
735 jsr166 1.96 * @throws ClassNotFoundException if the class of a serialized object
736     * could not be found
737     * @throws java.io.IOException if an I/O error occurs
738 dl 1.1 */
739     private void readObject(java.io.ObjectInputStream s)
740     throws java.io.IOException, ClassNotFoundException {
741 tim 1.2 s.defaultReadObject();
742 jsr166 1.55
743     // Read in elements until trailing null sentinel found
744     Node<E> h = null, t = null;
745 jsr166 1.104 for (Object item; (item = s.readObject()) != null; ) {
746 jsr166 1.48 @SuppressWarnings("unchecked")
747 jsr166 1.102 Node<E> newNode = newNode((E) item);
748 jsr166 1.55 if (h == null)
749     h = t = newNode;
750     else {
751 jsr166 1.102 lazySetNext(t, newNode);
752 jsr166 1.55 t = newNode;
753     }
754 dl 1.1 }
755 jsr166 1.55 if (h == null)
756 jsr166 1.102 h = t = newNode(null);
757 jsr166 1.55 head = h;
758     tail = t;
759     }
760    
761 dl 1.86 /** A customized variant of Spliterators.IteratorSpliterator */
762 dl 1.82 static final class CLQSpliterator<E> implements Spliterator<E> {
763 dl 1.89 static final int MAX_BATCH = 1 << 25; // max batch array size;
764 dl 1.82 final ConcurrentLinkedQueue<E> queue;
765     Node<E> current; // current node; null until initialized
766     int batch; // batch size for splits
767     boolean exhausted; // true when no more nodes
768     CLQSpliterator(ConcurrentLinkedQueue<E> queue) {
769     this.queue = queue;
770     }
771    
772     public Spliterator<E> trySplit() {
773 dl 1.89 Node<E> p;
774 dl 1.82 final ConcurrentLinkedQueue<E> q = this.queue;
775 dl 1.89 int b = batch;
776     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
777 jsr166 1.87 if (!exhausted &&
778 dl 1.83 ((p = current) != null || (p = q.first()) != null) &&
779     p.next != null) {
780 dl 1.92 Object[] a = new Object[n];
781 dl 1.82 int i = 0;
782     do {
783     if ((a[i] = p.item) != null)
784     ++i;
785     if (p == (p = p.next))
786     p = q.first();
787     } while (p != null && i < n);
788     if ((current = p) == null)
789     exhausted = true;
790 dl 1.89 if (i > 0) {
791     batch = i;
792     return Spliterators.spliterator
793     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
794     Spliterator.CONCURRENT);
795     }
796 dl 1.82 }
797     return null;
798     }
799    
800 dl 1.90 public void forEachRemaining(Consumer<? super E> action) {
801 dl 1.82 Node<E> p;
802     if (action == null) throw new NullPointerException();
803     final ConcurrentLinkedQueue<E> q = this.queue;
804     if (!exhausted &&
805     ((p = current) != null || (p = q.first()) != null)) {
806     exhausted = true;
807     do {
808     E e = p.item;
809     if (p == (p = p.next))
810     p = q.first();
811     if (e != null)
812     action.accept(e);
813     } while (p != null);
814     }
815     }
816    
817     public boolean tryAdvance(Consumer<? super E> action) {
818     Node<E> p;
819     if (action == null) throw new NullPointerException();
820     final ConcurrentLinkedQueue<E> q = this.queue;
821     if (!exhausted &&
822     ((p = current) != null || (p = q.first()) != null)) {
823     E e;
824     do {
825     e = p.item;
826     if (p == (p = p.next))
827     p = q.first();
828     } while (e == null && p != null);
829     if ((current = p) == null)
830     exhausted = true;
831     if (e != null) {
832     action.accept(e);
833     return true;
834     }
835     }
836     return false;
837     }
838    
839 dl 1.83 public long estimateSize() { return Long.MAX_VALUE; }
840    
841 dl 1.82 public int characteristics() {
842     return Spliterator.ORDERED | Spliterator.NONNULL |
843     Spliterator.CONCURRENT;
844     }
845     }
846    
847 jsr166 1.97 /**
848     * Returns a {@link Spliterator} over the elements in this queue.
849     *
850 jsr166 1.98 * <p>The returned spliterator is
851     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
852     *
853 jsr166 1.97 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
854     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
855     *
856     * @implNote
857     * The {@code Spliterator} implements {@code trySplit} to permit limited
858     * parallelism.
859     *
860     * @return a {@code Spliterator} over the elements in this queue
861     * @since 1.8
862     */
863     @Override
864 dl 1.85 public Spliterator<E> spliterator() {
865 dl 1.82 return new CLQSpliterator<E>(this);
866     }
867    
868 jsr166 1.55 /**
869     * Throws NullPointerException if argument is null.
870     *
871     * @param v the element
872     */
873     private static void checkNotNull(Object v) {
874     if (v == null)
875     throw new NullPointerException();
876 dl 1.1 }
877    
878 jsr166 1.50 private boolean casTail(Node<E> cmp, Node<E> val) {
879 jsr166 1.102 return U.compareAndSwapObject(this, TAIL, cmp, val);
880 jsr166 1.50 }
881 dl 1.72
882 jsr166 1.50 private boolean casHead(Node<E> cmp, Node<E> val) {
883 jsr166 1.102 return U.compareAndSwapObject(this, HEAD, cmp, val);
884 jsr166 1.48 }
885 dl 1.72
886 dl 1.71 // Unsafe mechanics
887 dl 1.72
888 jsr166 1.102 private static final sun.misc.Unsafe U;
889     private static final long HEAD;
890     private static final long TAIL;
891     private static final long ITEM;
892     private static final long NEXT;
893 dl 1.71 static {
894 jsr166 1.48 try {
895 jsr166 1.102 U = sun.misc.Unsafe.getUnsafe();
896 jsr166 1.76 Class<?> k = ConcurrentLinkedQueue.class;
897 jsr166 1.102 HEAD = U.objectFieldOffset(k.getDeclaredField("head"));
898     TAIL = U.objectFieldOffset(k.getDeclaredField("tail"));
899     k = Node.class;
900     ITEM = U.objectFieldOffset(k.getDeclaredField("item"));
901     NEXT = U.objectFieldOffset(k.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 }