ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.128
Committed: Tue Jun 28 17:04:36 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.127: +2 -2 lines
Log Message:
whitespace

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