ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.74
Committed: Fri Apr 22 11:51:42 2011 UTC (13 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.73: +8 -1 lines
Log Message:
Improved bulk operation disclaimers for concurrent collections

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     * Additionally, the bulk operations <tt>addAll</tt>,
49     * <tt>removeAll</tt>, <tt>retainAll</tt>, <tt>containsAll</tt>,
50     * <tt>equals</tt>, and <tt>toArray</tt> are <em>not</em> guaranteed
51     * to be performed atomically. For example, an iterator operating
52     * concurrently with an <tt>addAll</tt> operation might view only some
53     * 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     Class k = Node.class;
183     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     /**
223 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
224 dl 1.1 */
225 jsr166 1.55 public ConcurrentLinkedQueue() {
226     head = tail = new Node<E>(null);
227     }
228 dl 1.1
229     /**
230 jsr166 1.48 * Creates a {@code ConcurrentLinkedQueue}
231 dholmes 1.7 * initially containing the elements of the given collection,
232 dholmes 1.6 * added in traversal order of the collection's iterator.
233 jsr166 1.55 *
234 dholmes 1.6 * @param c the collection of elements to initially contain
235 jsr166 1.34 * @throws NullPointerException if the specified collection or any
236     * of its elements are null
237 dl 1.1 */
238 dholmes 1.6 public ConcurrentLinkedQueue(Collection<? extends E> c) {
239 jsr166 1.55 Node<E> h = null, t = null;
240     for (E e : c) {
241     checkNotNull(e);
242     Node<E> newNode = new Node<E>(e);
243     if (h == null)
244     h = t = newNode;
245     else {
246 jsr166 1.62 t.lazySetNext(newNode);
247 jsr166 1.55 t = newNode;
248     }
249     }
250     if (h == null)
251     h = t = new Node<E>(null);
252     head = h;
253     tail = t;
254 dl 1.1 }
255    
256 jsr166 1.29 // Have to override just to update the javadoc
257 dholmes 1.6
258     /**
259 jsr166 1.35 * Inserts the specified element at the tail of this queue.
260 jsr166 1.67 * As the queue is unbounded, this method will never throw
261     * {@link IllegalStateException} or return {@code false}.
262 dholmes 1.7 *
263 jsr166 1.48 * @return {@code true} (as specified by {@link Collection#add})
264 jsr166 1.32 * @throws NullPointerException if the specified element is null
265 dholmes 1.6 */
266 jsr166 1.31 public boolean add(E e) {
267     return offer(e);
268 dholmes 1.6 }
269    
270     /**
271 jsr166 1.48 * Try to CAS head to p. If successful, repoint old head to itself
272     * as sentinel for succ(), below.
273     */
274     final void updateHead(Node<E> h, Node<E> p) {
275     if (h != p && casHead(h, p))
276     h.lazySetNext(h);
277     }
278    
279     /**
280     * Returns the successor of p, or the head node if p.next has been
281     * linked to self, which will only be true if traversing with a
282     * stale pointer that is now off the list.
283     */
284     final Node<E> succ(Node<E> p) {
285 jsr166 1.55 Node<E> next = p.next;
286 jsr166 1.48 return (p == next) ? head : next;
287     }
288    
289     /**
290 jsr166 1.32 * Inserts the specified element at the tail of this queue.
291 jsr166 1.67 * As the queue is unbounded, this method will never return {@code false}.
292 dl 1.17 *
293 jsr166 1.48 * @return {@code true} (as specified by {@link Queue#offer})
294 jsr166 1.32 * @throws NullPointerException if the specified element is null
295 dholmes 1.6 */
296 jsr166 1.31 public boolean offer(E e) {
297 jsr166 1.55 checkNotNull(e);
298 jsr166 1.60 final Node<E> newNode = new Node<E>(e);
299 jsr166 1.58
300 jsr166 1.65 for (Node<E> t = tail, p = t;;) {
301     Node<E> q = p.next;
302     if (q == null) {
303     // p is last node
304     if (p.casNext(null, newNode)) {
305 jsr166 1.63 // Successful CAS is the linearization point
306     // for e to become an element of this queue,
307     // and for newNode to become "live".
308 jsr166 1.65 if (p != t) // hop two nodes at a time
309 jsr166 1.58 casTail(t, newNode); // Failure is OK.
310 jsr166 1.48 return true;
311 dl 1.1 }
312 jsr166 1.65 // Lost CAS race to another thread; re-read next
313 dl 1.1 }
314 jsr166 1.65 else if (p == q)
315     // We have fallen off list. If tail is unchanged, it
316     // will also be off-list, in which case we need to
317     // jump to head, from which all live nodes are always
318     // reachable. Else the new tail is a better bet.
319     p = (t != (t = tail)) ? t : head;
320     else
321     // Check for tail updates after two hops.
322     p = (p != t && t != (t = tail)) ? t : q;
323 dl 1.1 }
324     }
325    
326     public E poll() {
327 jsr166 1.65 restartFromHead:
328     for (;;) {
329     for (Node<E> h = head, p = h, q;;) {
330     E item = p.item;
331 jsr166 1.48
332 jsr166 1.65 if (item != null && p.casItem(item, null)) {
333     // Successful CAS is the linearization point
334     // for item to be removed from this queue.
335     if (p != h) // hop two nodes at a time
336     updateHead(h, ((q = p.next) != null) ? q : p);
337     return item;
338     }
339     else if ((q = p.next) == null) {
340     updateHead(h, p);
341     return null;
342 dl 1.1 }
343 jsr166 1.65 else if (p == q)
344     continue restartFromHead;
345     else
346     p = q;
347 dl 1.1 }
348     }
349     }
350    
351 jsr166 1.48 public E peek() {
352 jsr166 1.65 restartFromHead:
353 dl 1.1 for (;;) {
354 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
355     E item = p.item;
356     if (item != null || (q = p.next) == null) {
357     updateHead(h, p);
358     return item;
359     }
360     else if (p == q)
361     continue restartFromHead;
362     else
363     p = q;
364 dl 1.1 }
365     }
366     }
367    
368     /**
369 jsr166 1.51 * Returns the first live (non-deleted) node on list, or null if none.
370     * This is yet another variant of poll/peek; here returning the
371     * first node, not element. We could make peek() a wrapper around
372     * first(), but that would cost an extra volatile read of item,
373     * and the need to add a retry loop to deal with the possibility
374     * of losing a race to a concurrent poll().
375 dl 1.1 */
376 dl 1.23 Node<E> first() {
377 jsr166 1.65 restartFromHead:
378 dl 1.1 for (;;) {
379 jsr166 1.65 for (Node<E> h = head, p = h, q;;) {
380     boolean hasItem = (p.item != null);
381     if (hasItem || (q = p.next) == null) {
382     updateHead(h, p);
383     return hasItem ? p : null;
384     }
385     else if (p == q)
386     continue restartFromHead;
387     else
388     p = q;
389 dl 1.1 }
390     }
391     }
392    
393 dl 1.28 /**
394 jsr166 1.48 * Returns {@code true} if this queue contains no elements.
395 dl 1.28 *
396 jsr166 1.48 * @return {@code true} if this queue contains no elements
397 dl 1.28 */
398 dl 1.1 public boolean isEmpty() {
399     return first() == null;
400     }
401    
402     /**
403 dl 1.17 * Returns the number of elements in this queue. If this queue
404 jsr166 1.48 * contains more than {@code Integer.MAX_VALUE} elements, returns
405     * {@code Integer.MAX_VALUE}.
406 tim 1.2 *
407 dl 1.17 * <p>Beware that, unlike in most collections, this method is
408 dl 1.1 * <em>NOT</em> a constant-time operation. Because of the
409     * asynchronous nature of these queues, determining the current
410 jsr166 1.55 * number of elements requires an O(n) traversal.
411     * Additionally, if elements are added or removed during execution
412     * of this method, the returned result may be inaccurate. Thus,
413     * this method is typically not very useful in concurrent
414     * applications.
415 dl 1.17 *
416 jsr166 1.37 * @return the number of elements in this queue
417 tim 1.2 */
418 dl 1.1 public int size() {
419     int count = 0;
420 jsr166 1.64 for (Node<E> p = first(); p != null; p = succ(p))
421     if (p.item != null)
422     // Collection.size() spec says to max out
423 dl 1.8 if (++count == Integer.MAX_VALUE)
424     break;
425 dl 1.1 return count;
426     }
427    
428 jsr166 1.37 /**
429 jsr166 1.48 * Returns {@code true} if this queue contains the specified element.
430     * More formally, returns {@code true} if and only if this queue contains
431     * at least one element {@code e} such that {@code o.equals(e)}.
432 jsr166 1.37 *
433     * @param o object to be checked for containment in this queue
434 jsr166 1.48 * @return {@code true} if this queue contains the specified element
435 jsr166 1.37 */
436 dholmes 1.6 public boolean contains(Object o) {
437     if (o == null) return false;
438 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
439 jsr166 1.64 E item = p.item;
440 jsr166 1.65 if (item != null && o.equals(item))
441 dl 1.1 return true;
442     }
443     return false;
444     }
445    
446 jsr166 1.37 /**
447     * Removes a single instance of the specified element from this queue,
448 jsr166 1.48 * if it is present. More formally, removes an element {@code e} such
449     * that {@code o.equals(e)}, if this queue contains one or more such
450 jsr166 1.37 * elements.
451 jsr166 1.48 * Returns {@code true} if this queue contained the specified element
452 jsr166 1.37 * (or equivalently, if this queue changed as a result of the call).
453     *
454     * @param o element to be removed from this queue, if present
455 jsr166 1.48 * @return {@code true} if this queue changed as a result of the call
456 jsr166 1.37 */
457 dholmes 1.6 public boolean remove(Object o) {
458     if (o == null) return false;
459 jsr166 1.48 Node<E> pred = null;
460     for (Node<E> p = first(); p != null; p = succ(p)) {
461 jsr166 1.64 E item = p.item;
462 jsr166 1.51 if (item != null &&
463     o.equals(item) &&
464     p.casItem(item, null)) {
465 jsr166 1.48 Node<E> next = succ(p);
466     if (pred != null && next != null)
467     pred.casNext(p, next);
468 dl 1.1 return true;
469 jsr166 1.48 }
470     pred = p;
471 dl 1.1 }
472     return false;
473     }
474 tim 1.2
475 jsr166 1.33 /**
476 jsr166 1.55 * Appends all of the elements in the specified collection to the end of
477     * this queue, in the order that they are returned by the specified
478 jsr166 1.56 * collection's iterator. Attempts to {@code addAll} of a queue to
479     * itself result in {@code IllegalArgumentException}.
480 jsr166 1.55 *
481     * @param c the elements to be inserted into this queue
482     * @return {@code true} if this queue changed as a result of the call
483 jsr166 1.56 * @throws NullPointerException if the specified collection or any
484     * of its elements are null
485     * @throws IllegalArgumentException if the collection is this queue
486 jsr166 1.55 */
487     public boolean addAll(Collection<? extends E> c) {
488 jsr166 1.56 if (c == this)
489     // As historically specified in AbstractQueue#addAll
490     throw new IllegalArgumentException();
491    
492 jsr166 1.55 // Copy c into a private chain of Nodes
493 jsr166 1.65 Node<E> beginningOfTheEnd = null, last = null;
494 jsr166 1.55 for (E e : c) {
495     checkNotNull(e);
496     Node<E> newNode = new Node<E>(e);
497 jsr166 1.65 if (beginningOfTheEnd == null)
498     beginningOfTheEnd = last = newNode;
499 jsr166 1.55 else {
500 jsr166 1.62 last.lazySetNext(newNode);
501 jsr166 1.55 last = newNode;
502     }
503     }
504 jsr166 1.65 if (beginningOfTheEnd == null)
505 jsr166 1.55 return false;
506    
507 jsr166 1.65 // Atomically append the chain at the tail of this collection
508     for (Node<E> t = tail, p = t;;) {
509     Node<E> q = p.next;
510     if (q == null) {
511     // p is last node
512     if (p.casNext(null, beginningOfTheEnd)) {
513     // Successful CAS is the linearization point
514     // for all elements to be added to this queue.
515     if (!casTail(t, last)) {
516 jsr166 1.55 // Try a little harder to update tail,
517     // since we may be adding many elements.
518     t = tail;
519     if (last.next == null)
520     casTail(t, last);
521     }
522     return true;
523     }
524 jsr166 1.65 // Lost CAS race to another thread; re-read next
525 jsr166 1.55 }
526 jsr166 1.65 else if (p == q)
527     // We have fallen off list. If tail is unchanged, it
528     // will also be off-list, in which case we need to
529     // jump to head, from which all live nodes are always
530     // reachable. Else the new tail is a better bet.
531     p = (t != (t = tail)) ? t : head;
532     else
533     // Check for tail updates after two hops.
534     p = (p != t && t != (t = tail)) ? t : q;
535 jsr166 1.55 }
536     }
537    
538     /**
539 jsr166 1.48 * Returns an array containing all of the elements in this queue, in
540     * proper sequence.
541     *
542     * <p>The returned array will be "safe" in that no references to it are
543     * maintained by this queue. (In other words, this method must allocate
544     * a new array). The caller is thus free to modify the returned array.
545     *
546     * <p>This method acts as bridge between array-based and collection-based
547     * APIs.
548     *
549     * @return an array containing all of the elements in this queue
550     */
551     public Object[] toArray() {
552     // Use ArrayList to deal with resizing.
553     ArrayList<E> al = new ArrayList<E>();
554     for (Node<E> p = first(); p != null; p = succ(p)) {
555 jsr166 1.64 E item = p.item;
556 jsr166 1.48 if (item != null)
557     al.add(item);
558     }
559     return al.toArray();
560     }
561    
562     /**
563     * Returns an array containing all of the elements in this queue, in
564     * proper sequence; the runtime type of the returned array is that of
565     * the specified array. If the queue fits in the specified array, it
566     * is returned therein. Otherwise, a new array is allocated with the
567     * runtime type of the specified array and the size of this queue.
568     *
569     * <p>If this queue fits in the specified array with room to spare
570     * (i.e., the array has more elements than this queue), the element in
571     * the array immediately following the end of the queue is set to
572     * {@code null}.
573     *
574     * <p>Like the {@link #toArray()} method, this method acts as bridge between
575     * array-based and collection-based APIs. Further, this method allows
576     * precise control over the runtime type of the output array, and may,
577     * under certain circumstances, be used to save allocation costs.
578     *
579     * <p>Suppose {@code x} is a queue known to contain only strings.
580     * The following code can be used to dump the queue into a newly
581     * allocated array of {@code String}:
582     *
583     * <pre>
584     * String[] y = x.toArray(new String[0]);</pre>
585     *
586     * Note that {@code toArray(new Object[0])} is identical in function to
587     * {@code toArray()}.
588     *
589     * @param a the array into which the elements of the queue are to
590     * be stored, if it is big enough; otherwise, a new array of the
591     * same runtime type is allocated for this purpose
592     * @return an array containing all of the elements in this queue
593     * @throws ArrayStoreException if the runtime type of the specified array
594     * is not a supertype of the runtime type of every element in
595     * this queue
596     * @throws NullPointerException if the specified array is null
597     */
598     @SuppressWarnings("unchecked")
599     public <T> T[] toArray(T[] a) {
600     // try to use sent-in array
601     int k = 0;
602     Node<E> p;
603     for (p = first(); p != null && k < a.length; p = succ(p)) {
604 jsr166 1.64 E item = p.item;
605 jsr166 1.48 if (item != null)
606     a[k++] = (T)item;
607     }
608     if (p == null) {
609     if (k < a.length)
610     a[k] = null;
611     return a;
612     }
613    
614     // If won't fit, use ArrayList version
615     ArrayList<E> al = new ArrayList<E>();
616     for (Node<E> q = first(); q != null; q = succ(q)) {
617 jsr166 1.64 E item = q.item;
618 jsr166 1.48 if (item != null)
619     al.add(item);
620     }
621     return al.toArray(a);
622     }
623    
624     /**
625 dholmes 1.7 * Returns an iterator over the elements in this queue in proper sequence.
626 jsr166 1.55 * The elements will be returned in order from first (head) to last (tail).
627     *
628 jsr166 1.70 * <p>The returned iterator is a "weakly consistent" iterator that
629 jsr166 1.52 * will never throw {@link java.util.ConcurrentModificationException
630 jsr166 1.70 * ConcurrentModificationException}, and guarantees to traverse
631     * elements as they existed upon construction of the iterator, and
632     * may (but is not guaranteed to) reflect any modifications
633     * subsequent to construction.
634 dholmes 1.7 *
635 jsr166 1.33 * @return an iterator over the elements in this queue in proper sequence
636 dholmes 1.7 */
637 dl 1.1 public Iterator<E> iterator() {
638     return new Itr();
639     }
640    
641     private class Itr implements Iterator<E> {
642     /**
643     * Next node to return item for.
644     */
645 dl 1.23 private Node<E> nextNode;
646 dl 1.1
647 tim 1.2 /**
648 dl 1.1 * nextItem holds on to item fields because once we claim
649     * that an element exists in hasNext(), we must return it in
650     * the following next() call even if it was in the process of
651     * being removed when hasNext() was called.
652 jsr166 1.29 */
653 dl 1.1 private E nextItem;
654    
655     /**
656     * Node of the last returned item, to support remove.
657     */
658 dl 1.23 private Node<E> lastRet;
659 dl 1.1
660 tim 1.2 Itr() {
661 dl 1.1 advance();
662     }
663 tim 1.2
664 dl 1.1 /**
665 dl 1.26 * Moves to next valid node and returns item to return for
666     * next(), or null if no such.
667 dl 1.1 */
668 tim 1.2 private E advance() {
669 dl 1.1 lastRet = nextNode;
670 dl 1.22 E x = nextItem;
671 dl 1.1
672 jsr166 1.48 Node<E> pred, p;
673     if (nextNode == null) {
674     p = first();
675     pred = null;
676     } else {
677     pred = nextNode;
678     p = succ(nextNode);
679     }
680    
681 dl 1.1 for (;;) {
682     if (p == null) {
683     nextNode = null;
684     nextItem = null;
685     return x;
686     }
687 jsr166 1.64 E item = p.item;
688 dl 1.1 if (item != null) {
689     nextNode = p;
690     nextItem = item;
691     return x;
692 jsr166 1.48 } else {
693     // skip over nulls
694     Node<E> next = succ(p);
695     if (pred != null && next != null)
696     pred.casNext(p, next);
697     p = next;
698     }
699 dl 1.1 }
700     }
701 tim 1.2
702 dl 1.1 public boolean hasNext() {
703     return nextNode != null;
704     }
705 tim 1.2
706 dl 1.1 public E next() {
707     if (nextNode == null) throw new NoSuchElementException();
708     return advance();
709     }
710 tim 1.2
711 dl 1.1 public void remove() {
712 dl 1.23 Node<E> l = lastRet;
713 dl 1.1 if (l == null) throw new IllegalStateException();
714     // rely on a future traversal to relink.
715 jsr166 1.64 l.item = null;
716 dl 1.1 lastRet = null;
717     }
718     }
719    
720     /**
721 jsr166 1.55 * Saves the state to a stream (that is, serializes it).
722 dl 1.1 *
723 jsr166 1.48 * @serialData All of the elements (each an {@code E}) in
724 dl 1.1 * the proper order, followed by a null
725     * @param s the stream
726     */
727     private void writeObject(java.io.ObjectOutputStream s)
728     throws java.io.IOException {
729    
730     // Write out any hidden stuff
731     s.defaultWriteObject();
732 tim 1.2
733 dl 1.1 // Write out all elements in the proper order.
734 jsr166 1.48 for (Node<E> p = first(); p != null; p = succ(p)) {
735 jsr166 1.64 Object item = p.item;
736 dl 1.1 if (item != null)
737     s.writeObject(item);
738     }
739    
740     // Use trailing null as sentinel
741     s.writeObject(null);
742     }
743    
744     /**
745 jsr166 1.55 * Reconstitutes the instance from a stream (that is, deserializes it).
746 dl 1.1 * @param s the stream
747     */
748     private void readObject(java.io.ObjectInputStream s)
749     throws java.io.IOException, ClassNotFoundException {
750 tim 1.2 s.defaultReadObject();
751 jsr166 1.55
752     // Read in elements until trailing null sentinel found
753     Node<E> h = null, t = null;
754     Object item;
755     while ((item = s.readObject()) != null) {
756 jsr166 1.48 @SuppressWarnings("unchecked")
757 jsr166 1.55 Node<E> newNode = new Node<E>((E) item);
758     if (h == null)
759     h = t = newNode;
760     else {
761 jsr166 1.62 t.lazySetNext(newNode);
762 jsr166 1.55 t = newNode;
763     }
764 dl 1.1 }
765 jsr166 1.55 if (h == null)
766     h = t = new Node<E>(null);
767     head = h;
768     tail = t;
769     }
770    
771     /**
772     * Throws NullPointerException if argument is null.
773     *
774     * @param v the element
775     */
776     private static void checkNotNull(Object v) {
777     if (v == null)
778     throw new NullPointerException();
779 dl 1.1 }
780    
781 jsr166 1.50 private boolean casTail(Node<E> cmp, Node<E> val) {
782     return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
783     }
784 dl 1.72
785 jsr166 1.50 private boolean casHead(Node<E> cmp, Node<E> val) {
786     return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
787 jsr166 1.48 }
788 dl 1.72
789 dl 1.71 // Unsafe mechanics
790 dl 1.72
791 dl 1.71 private static final sun.misc.Unsafe UNSAFE;
792     private static final long headOffset;
793     private static final long tailOffset;
794     static {
795 jsr166 1.48 try {
796 dl 1.71 UNSAFE = sun.misc.Unsafe.getUnsafe();
797     Class k = ConcurrentLinkedQueue.class;
798     headOffset = UNSAFE.objectFieldOffset
799     (k.getDeclaredField("head"));
800     tailOffset = UNSAFE.objectFieldOffset
801     (k.getDeclaredField("tail"));
802     } catch (Exception e) {
803     throw new Error(e);
804 jsr166 1.48 }
805     }
806 dl 1.1 }