ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.57
Committed: Wed Sep 1 22:49:09 2010 UTC (13 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.56: +5 -6 lines
Log Message:
Use relaxed Unsafe.putObject in Node constructors

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.24 * Expert Group and released to the public domain, as explained at
4     * 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     * ConcurrentModificationException}, and may proceed concurrently with
40     * other operations. Elements contained in the queue since the creation
41     * 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     * (fewer CASes). This is controlled by local "hops" variables
114     * that only trigger helping-CASes after experiencing multiple
115     * lags.
116     *
117     * Since head and tail are updated concurrently and independently,
118     * it is possible for tail to lag behind head (why not)?
119     *
120     * CASing a Node's item reference to null atomically removes the
121     * element from the queue. Iterators skip over Nodes with null
122     * items. Prior implementations of this class had a race between
123     * poll() and remove(Object) where the same element would appear
124     * to be successfully removed by two concurrent operations. The
125     * method remove(Object) also lazily unlinks deleted Nodes, but
126     * this is merely an optimization.
127     *
128     * When constructing a Node (before enqueuing it) we avoid paying
129     * for a volatile write to item by using lazySet instead of a
130     * normal write. This allows the cost of enqueue to be
131     * "one-and-a-half" CASes.
132     *
133     * Both head and tail may or may not point to a Node with a
134     * non-null item. If the queue is empty, all items must of course
135     * be null. Upon creation, both head and tail refer to a dummy
136     * Node with null item. Both head and tail are only updated using
137     * CAS, so they never regress, although again this is merely an
138     * optimization.
139 dl 1.1 */
140 jsr166 1.51
141 dl 1.23 private static class Node<E> {
142 dl 1.22 private volatile E item;
143 dl 1.23 private volatile Node<E> next;
144 jsr166 1.29
145 jsr166 1.57 /**
146     * Constructs a new node. Uses relaxed write because item can
147     * only be seen after publication via casNext.
148     */
149 jsr166 1.51 Node(E item) {
150 jsr166 1.57 UNSAFE.putObject(this, itemOffset, item);
151 jsr166 1.51 }
152 jsr166 1.29
153 dl 1.22 E getItem() {
154 dl 1.13 return item;
155     }
156 jsr166 1.29
157 dl 1.22 boolean casItem(E cmp, E val) {
158 jsr166 1.50 return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
159 dl 1.13 }
160 jsr166 1.29
161 dl 1.22 void setItem(E val) {
162 jsr166 1.48 item = val;
163     }
164    
165     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 jsr166 1.50 private static final sun.misc.Unsafe UNSAFE =
176     sun.misc.Unsafe.getUnsafe();
177     private static final long nextOffset =
178     objectFieldOffset(UNSAFE, "next", Node.class);
179     private static final long itemOffset =
180     objectFieldOffset(UNSAFE, "item", Node.class);
181 jsr166 1.48 }
182    
183 tim 1.2 /**
184 jsr166 1.51 * A node from which the first live (non-deleted) node (if any)
185     * can be reached in O(1) time.
186     * Invariants:
187     * - all live nodes are reachable from head via succ()
188     * - head != null
189     * - (tmp = head).next != tmp || tmp != head
190     * Non-invariants:
191     * - head.item may or may not be null.
192     * - it is permitted for tail to lag behind head, that is, for tail
193     * to not be reachable from head!
194 dl 1.1 */
195 jsr166 1.55 private transient volatile Node<E> head;
196 dl 1.1
197 jsr166 1.51 /**
198     * A node from which the last node on list (that is, the unique
199     * node with node.next == null) can be reached in O(1) time.
200     * Invariants:
201     * - the last node is always reachable from tail via succ()
202     * - tail != null
203     * Non-invariants:
204     * - tail.item may or may not be null.
205     * - it is permitted for tail to lag behind head, that is, for tail
206     * to not be reachable from head!
207     * - tail.next may or may not be self-pointing to tail.
208     */
209 jsr166 1.55 private transient volatile Node<E> tail;
210 dl 1.1
211    
212     /**
213 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
214 dl 1.1 */
215 jsr166 1.55 public ConcurrentLinkedQueue() {
216     head = tail = new Node<E>(null);
217     }
218 dl 1.1
219     /**
220 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue}
221 dholmes 1.7 * initially containing the elements of the given collection,
222 dholmes 1.6 * added in traversal order of the collection's iterator.
223 jsr166 1.55 *
224 dholmes 1.6 * @param c the collection of elements to initially contain
225 jsr166 1.34 * @throws NullPointerException if the specified collection or any
226     * of its elements are null
227 dl 1.1 */
228 dholmes 1.6 public ConcurrentLinkedQueue(Collection<? extends E> c) {
229 jsr166 1.55 Node<E> h = null, t = null;
230     for (E e : c) {
231     checkNotNull(e);
232     Node<E> newNode = new Node<E>(e);
233     if (h == null)
234     h = t = newNode;
235     else {
236     t.next = newNode;
237     t = newNode;
238     }
239     }
240     if (h == null)
241     h = t = new Node<E>(null);
242     head = h;
243     tail = t;
244 dl 1.1 }
245    
246 jsr166 1.29 // Have to override just to update the javadoc
247 dholmes 1.6
248     /**
249 jsr166 1.35 * Inserts the specified element at the tail of this queue.
250 dholmes 1.7 *
251 jsr166 1.48 * @return {@code true} (as specified by {@link Collection#add})
252 jsr166 1.32 * @throws NullPointerException if the specified element is null
253 dholmes 1.6 */
254 jsr166 1.31 public boolean add(E e) {
255     return offer(e);
256 dholmes 1.6 }
257    
258     /**
259 jsr166 1.51 * We don't bother to update head or tail pointers if fewer than
260 jsr166 1.48 * HOPS links from "true" location. We assume that volatile
261     * writes are significantly more expensive than volatile reads.
262     */
263     private static final int HOPS = 1;
264    
265     /**
266     * Try to CAS head to p. If successful, repoint old head to itself
267     * as sentinel for succ(), below.
268     */
269     final void updateHead(Node<E> h, Node<E> p) {
270     if (h != p && casHead(h, p))
271     h.lazySetNext(h);
272     }
273    
274     /**
275     * Returns the successor of p, or the head node if p.next has been
276     * linked to self, which will only be true if traversing with a
277     * stale pointer that is now off the list.
278     */
279     final Node<E> succ(Node<E> p) {
280 jsr166 1.55 Node<E> next = p.next;
281 jsr166 1.48 return (p == next) ? head : next;
282     }
283    
284     /**
285 jsr166 1.32 * Inserts the specified element at the tail of this queue.
286 dl 1.17 *
287 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
288 jsr166 1.32 * @throws NullPointerException if the specified element is null
289 dholmes 1.6 */
290 jsr166 1.31 public boolean offer(E e) {
291 jsr166 1.55 checkNotNull(e);
292 jsr166 1.48 Node<E> n = new Node<E>(e);
293     retry:
294 jsr166 1.38 for (;;) {
295 dl 1.23 Node<E> t = tail;
296 jsr166 1.48 Node<E> p = t;
297     for (int hops = 0; ; hops++) {
298     Node<E> next = succ(p);
299     if (next != null) {
300     if (hops > HOPS && t != tail)
301     continue retry;
302     p = next;
303     } else if (p.casNext(null, n)) {
304     if (hops >= HOPS)
305     casTail(t, n); // Failure is OK.
306     return true;
307 tim 1.12 } else {
308 jsr166 1.48 p = succ(p);
309 dl 1.1 }
310     }
311     }
312     }
313    
314     public E poll() {
315 jsr166 1.48 Node<E> h = head;
316     Node<E> p = h;
317     for (int hops = 0; ; hops++) {
318     E item = p.getItem();
319    
320     if (item != null && p.casItem(item, null)) {
321     if (hops >= HOPS) {
322 jsr166 1.55 Node<E> q = p.next;
323 jsr166 1.48 updateHead(h, (q != null) ? q : p);
324 dl 1.1 }
325 jsr166 1.48 return item;
326 dl 1.1 }
327 jsr166 1.48 Node<E> next = succ(p);
328     if (next == null) {
329     updateHead(h, p);
330     break;
331     }
332     p = next;
333 dl 1.1 }
334 jsr166 1.48 return null;
335 dl 1.1 }
336    
337 jsr166 1.48 public E peek() {
338     Node<E> h = head;
339     Node<E> p = h;
340     E item;
341 dl 1.1 for (;;) {
342 jsr166 1.48 item = p.getItem();
343     if (item != null)
344     break;
345     Node<E> next = succ(p);
346     if (next == null) {
347     break;
348 dl 1.1 }
349 jsr166 1.48 p = next;
350 dl 1.1 }
351 jsr166 1.48 updateHead(h, p);
352     return item;
353 dl 1.1 }
354    
355     /**
356 jsr166 1.51 * Returns the first live (non-deleted) node on list, or null if none.
357     * This is yet another variant of poll/peek; here returning the
358     * first node, not element. We could make peek() a wrapper around
359     * first(), but that would cost an extra volatile read of item,
360     * and the need to add a retry loop to deal with the possibility
361     * of losing a race to a concurrent poll().
362 dl 1.1 */
363 dl 1.23 Node<E> first() {
364 jsr166 1.48 Node<E> h = head;
365     Node<E> p = h;
366     Node<E> result;
367 dl 1.1 for (;;) {
368 jsr166 1.48 E item = p.getItem();
369     if (item != null) {
370     result = p;
371     break;
372     }
373     Node<E> next = succ(p);
374     if (next == null) {
375     result = null;
376     break;
377 dl 1.1 }
378 jsr166 1.48 p = next;
379 dl 1.1 }
380 jsr166 1.48 updateHead(h, p);
381     return result;
382 dl 1.1 }
383    
384 dl 1.28 /**
385 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
386 dl 1.28 *
387 jsr166 1.48 * @return {@code true} if this queue contains no elements
388 dl 1.28 */
389 dl 1.1 public boolean isEmpty() {
390     return first() == null;
391     }
392    
393     /**
394 dl 1.17 * Returns the number of elements in this queue. If this queue
395 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
396     * {@code Integer.MAX_VALUE}.
397 tim 1.2 *
398 dl 1.17 * <p>Beware that, unlike in most collections, this method is
399 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
400     * asynchronous nature of these queues, determining the current
401 jsr166 1.55 * number of elements requires an O(n) traversal.
402     * Additionally, if elements are added or removed during execution
403     * of this method, the returned result may be inaccurate. Thus,
404     * this method is typically not very useful in concurrent
405     * applications.
406 dl 1.17 *
407 jsr166 1.37 * @return the number of elements in this queue
408 tim 1.2 */
409 dl 1.1 public int size() {
410     int count = 0;
411 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
412 dl 1.8 if (p.getItem() != null) {
413     // Collections.size() spec says to max out
414     if (++count == Integer.MAX_VALUE)
415     break;
416     }
417 dl 1.1 }
418     return count;
419     }
420    
421 jsr166 1.37 /**
422 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
423     * More formally, returns {@code true} if and only if this queue contains
424     * at least one element {@code e} such that {@code o.equals(e)}.
425 jsr166 1.37 *
426     * @param o object to be checked for containment in this queue
427 jsr166 1.48 * @return {@code true} if this queue contains the specified element
428 jsr166 1.37 */
429 dholmes 1.6 public boolean contains(Object o) {
430     if (o == null) return false;
431 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
432 dl 1.22 E item = p.getItem();
433 tim 1.2 if (item != null &&
434 dholmes 1.6 o.equals(item))
435 dl 1.1 return true;
436     }
437     return false;
438     }
439    
440 jsr166 1.37 /**
441     * Removes a single instance of the specified element from this queue,
442 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
443     * that {@code o.equals(e)}, if this queue contains one or more such
444 jsr166 1.37 * elements.
445 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
446 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
447     *
448     * @param o element to be removed from this queue, if present
449 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
450 jsr166 1.37 */
451 dholmes 1.6 public boolean remove(Object o) {
452     if (o == null) return false;
453 jsr166 1.48 Node<E> pred = null;
454     for (Node<E> p = first(); p != null; p = succ(p)) {
455 dl 1.22 E item = p.getItem();
456 jsr166 1.51 if (item != null &&
457     o.equals(item) &&
458     p.casItem(item, null)) {
459 jsr166 1.48 Node<E> next = succ(p);
460     if (pred != null && next != null)
461     pred.casNext(p, next);
462 dl 1.1 return true;
463 jsr166 1.48 }
464     pred = p;
465 dl 1.1 }
466     return false;
467     }
468 tim 1.2
469 jsr166 1.33 /**
470 jsr166 1.55 * Appends all of the elements in the specified collection to the end of
471     * this queue, in the order that they are returned by the specified
472 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
473     * itself result in {@code IllegalArgumentException}.
474 jsr166 1.55 *
475     * @param c the elements to be inserted into this queue
476     * @return {@code true} if this queue changed as a result of the call
477 jsr166 1.56 * @throws NullPointerException if the specified collection or any
478     * of its elements are null
479     * @throws IllegalArgumentException if the collection is this queue
480 jsr166 1.55 */
481     public boolean addAll(Collection<? extends E> c) {
482 jsr166 1.56 if (c == this)
483     // As historically specified in AbstractQueue#addAll
484     throw new IllegalArgumentException();
485    
486 jsr166 1.55 // Copy c into a private chain of Nodes
487     Node<E> splice = null, last = null;
488     for (E e : c) {
489     checkNotNull(e);
490     Node<E> newNode = new Node<E>(e);
491     if (splice == null)
492     splice = last = newNode;
493     else {
494     last.next = newNode;
495     last = newNode;
496     }
497     }
498     if (splice == null)
499     return false;
500    
501     // Atomically splice the chain as the tail of this collection
502     retry:
503     for (;;) {
504     for (Node<E> t = tail, p = t;;) {
505     Node<E> next = succ(p);
506     if (next != null) {
507     if (t != tail)
508     continue retry;
509     p = next;
510     } else if (p.casNext(null, splice)) {
511     if (! casTail(t, last)) {
512     // Try a little harder to update tail,
513     // since we may be adding many elements.
514     t = tail;
515     if (last.next == null)
516     casTail(t, last);
517     }
518     return true;
519     } else {
520     p = succ(p);
521     }
522     }
523     }
524     }
525    
526     /**
527 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
528     * proper sequence.
529     *
530     * <p>The returned array will be "safe" in that no references to it are
531     * maintained by this queue. (In other words, this method must allocate
532     * a new array). The caller is thus free to modify the returned array.
533     *
534     * <p>This method acts as bridge between array-based and collection-based
535     * APIs.
536     *
537     * @return an array containing all of the elements in this queue
538     */
539     public Object[] toArray() {
540     // Use ArrayList to deal with resizing.
541     ArrayList<E> al = new ArrayList<E>();
542     for (Node<E> p = first(); p != null; p = succ(p)) {
543     E item = p.getItem();
544     if (item != null)
545     al.add(item);
546     }
547     return al.toArray();
548     }
549    
550     /**
551     * Returns an array containing all of the elements in this queue, in
552     * proper sequence; the runtime type of the returned array is that of
553     * the specified array. If the queue fits in the specified array, it
554     * is returned therein. Otherwise, a new array is allocated with the
555     * runtime type of the specified array and the size of this queue.
556     *
557     * <p>If this queue fits in the specified array with room to spare
558     * (i.e., the array has more elements than this queue), the element in
559     * the array immediately following the end of the queue is set to
560     * {@code null}.
561     *
562     * <p>Like the {@link #toArray()} method, this method acts as bridge between
563     * array-based and collection-based APIs. Further, this method allows
564     * precise control over the runtime type of the output array, and may,
565     * under certain circumstances, be used to save allocation costs.
566     *
567     * <p>Suppose {@code x} is a queue known to contain only strings.
568     * The following code can be used to dump the queue into a newly
569     * allocated array of {@code String}:
570     *
571     * <pre>
572     * String[] y = x.toArray(new String[0]);</pre>
573     *
574     * Note that {@code toArray(new Object[0])} is identical in function to
575     * {@code toArray()}.
576     *
577     * @param a the array into which the elements of the queue are to
578     * be stored, if it is big enough; otherwise, a new array of the
579     * same runtime type is allocated for this purpose
580     * @return an array containing all of the elements in this queue
581     * @throws ArrayStoreException if the runtime type of the specified array
582     * is not a supertype of the runtime type of every element in
583     * this queue
584     * @throws NullPointerException if the specified array is null
585     */
586     @SuppressWarnings("unchecked")
587     public <T> T[] toArray(T[] a) {
588     // try to use sent-in array
589     int k = 0;
590     Node<E> p;
591     for (p = first(); p != null && k < a.length; p = succ(p)) {
592     E item = p.getItem();
593     if (item != null)
594     a[k++] = (T)item;
595     }
596     if (p == null) {
597     if (k < a.length)
598     a[k] = null;
599     return a;
600     }
601    
602     // If won't fit, use ArrayList version
603     ArrayList<E> al = new ArrayList<E>();
604     for (Node<E> q = first(); q != null; q = succ(q)) {
605     E item = q.getItem();
606     if (item != null)
607     al.add(item);
608     }
609     return al.toArray(a);
610     }
611    
612     /**
613 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
614 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
615     *
616     * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
617 jsr166 1.52 * will never throw {@link java.util.ConcurrentModificationException
618     * ConcurrentModificationException},
619 dl 1.9 * and guarantees to traverse elements as they existed upon
620     * construction of the iterator, and may (but is not guaranteed to)
621     * reflect any modifications subsequent to construction.
622 dholmes 1.7 *
623 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
624 dholmes 1.7 */
625 dl 1.1 public Iterator<E> iterator() {
626     return new Itr();
627     }
628    
629     private class Itr implements Iterator<E> {
630     /**
631     * Next node to return item for.
632     */
633 dl 1.23 private Node<E> nextNode;
634 dl 1.1
635 tim 1.2 /**
636 dl 1.1 * nextItem holds on to item fields because once we claim
637     * that an element exists in hasNext(), we must return it in
638     * the following next() call even if it was in the process of
639     * being removed when hasNext() was called.
640 jsr166 1.29 */
641 dl 1.1 private E nextItem;
642    
643     /**
644     * Node of the last returned item, to support remove.
645     */
646 dl 1.23 private Node<E> lastRet;
647 dl 1.1
648 tim 1.2 Itr() {
649 dl 1.1 advance();
650     }
651 tim 1.2
652 dl 1.1 /**
653 dl 1.26 * Moves to next valid node and returns item to return for
654     * next(), or null if no such.
655 dl 1.1 */
656 tim 1.2 private E advance() {
657 dl 1.1 lastRet = nextNode;
658 dl 1.22 E x = nextItem;
659 dl 1.1
660 jsr166 1.48 Node<E> pred, p;
661     if (nextNode == null) {
662     p = first();
663     pred = null;
664     } else {
665     pred = nextNode;
666     p = succ(nextNode);
667     }
668    
669 dl 1.1 for (;;) {
670     if (p == null) {
671     nextNode = null;
672     nextItem = null;
673     return x;
674     }
675 dl 1.22 E item = p.getItem();
676 dl 1.1 if (item != null) {
677     nextNode = p;
678     nextItem = item;
679     return x;
680 jsr166 1.48 } else {
681     // skip over nulls
682     Node<E> next = succ(p);
683     if (pred != null && next != null)
684     pred.casNext(p, next);
685     p = next;
686     }
687 dl 1.1 }
688     }
689 tim 1.2
690 dl 1.1 public boolean hasNext() {
691     return nextNode != null;
692     }
693 tim 1.2
694 dl 1.1 public E next() {
695     if (nextNode == null) throw new NoSuchElementException();
696     return advance();
697     }
698 tim 1.2
699 dl 1.1 public void remove() {
700 dl 1.23 Node<E> l = lastRet;
701 dl 1.1 if (l == null) throw new IllegalStateException();
702     // rely on a future traversal to relink.
703     l.setItem(null);
704     lastRet = null;
705     }
706     }
707    
708     /**
709 jsr166 1.55 * Saves the state to a stream (that is, serializes it).
710 dl 1.1 *
711 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
712 dl 1.1 * the proper order, followed by a null
713     * @param s the stream
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 dl 1.1 Object item = p.getItem();
724     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.55 * Reconstitutes the instance from a stream (that is, deserializes it).
734 dl 1.1 * @param s the stream
735     */
736     private void readObject(java.io.ObjectInputStream s)
737     throws java.io.IOException, ClassNotFoundException {
738 tim 1.2 s.defaultReadObject();
739 jsr166 1.55
740     // Read in elements until trailing null sentinel found
741     Node<E> h = null, t = null;
742     Object item;
743     while ((item = s.readObject()) != null) {
744 jsr166 1.48 @SuppressWarnings("unchecked")
745 jsr166 1.55 Node<E> newNode = new Node<E>((E) item);
746     if (h == null)
747     h = t = newNode;
748     else {
749     t.next = newNode;
750     t = newNode;
751     }
752 dl 1.1 }
753 jsr166 1.55 if (h == null)
754     h = t = new Node<E>(null);
755     head = h;
756     tail = t;
757     }
758    
759     /**
760     * Throws NullPointerException if argument is null.
761     *
762     * @param v the element
763     */
764     private static void checkNotNull(Object v) {
765     if (v == null)
766     throw new NullPointerException();
767 dl 1.1 }
768    
769 jsr166 1.48 // Unsafe mechanics
770 jsr166 1.50
771     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
772     private static final long headOffset =
773     objectFieldOffset(UNSAFE, "head", ConcurrentLinkedQueue.class);
774     private static final long tailOffset =
775     objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedQueue.class);
776    
777     private boolean casTail(Node<E> cmp, Node<E> val) {
778     return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
779     }
780    
781     private boolean casHead(Node<E> cmp, Node<E> val) {
782     return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
783 jsr166 1.48 }
784    
785 jsr166 1.50 private void lazySetHead(Node<E> val) {
786     UNSAFE.putOrderedObject(this, headOffset, val);
787 jsr166 1.48 }
788    
789 jsr166 1.50 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
790     String field, Class<?> klazz) {
791 jsr166 1.48 try {
792 jsr166 1.50 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
793 jsr166 1.48 } catch (NoSuchFieldException e) {
794 jsr166 1.50 // Convert Exception to corresponding Error
795     NoSuchFieldError error = new NoSuchFieldError(field);
796 jsr166 1.48 error.initCause(e);
797     throw error;
798     }
799     }
800 dl 1.1 }