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