ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.79
Committed: Mon Dec 12 20:53:11 2011 UTC (12 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.78: +2 -4 lines
Log Message:
uniform serialization method javadocs

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