ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.70
Committed: Fri Nov 19 08:02:09 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.69: +5 -5 lines
Log Message:
make iterator weakly consistent specs more consistent

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