ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.119
Committed: Sun Feb 22 04:52:04 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.118: +0 -1 lines
Log Message:
unused import

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