ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.118
Committed: Sat Feb 21 17:15:00 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.117: +4 -16 lines
Log Message:
s/checkNotNull/Objects.requireNonNull/g

File Contents

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