ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.80
Committed: Sun Oct 21 06:14:12 2012 UTC (11 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.79: +0 -1 lines
Log Message:
delete trailing empty lines of javadoc

File Contents

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