ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.99
Committed: Wed Oct 29 20:23:14 2014 UTC (9 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.98: +3 -3 lines
Log Message:
use new URL for the Micheal/Scott paper

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.Arrays;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.Iterator;
15 import java.util.NoSuchElementException;
16 import java.util.Queue;
17 import java.util.Spliterator;
18 import java.util.Spliterators;
19 import java.util.stream.Stream;
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 * {@code equals}, 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 collection
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 by using Unsafe.putObject instead
143 * of a normal write. This allows the cost of enqueue to be
144 * "one-and-a-half" CASes.
145 *
146 * Both head and tail may or may not point to a Node with a
147 * non-null item. If the queue is empty, all items must of course
148 * be null. Upon creation, both head and tail refer to a dummy
149 * Node with null item. Both head and tail are only updated using
150 * CAS, so they never regress, although again this is merely an
151 * optimization.
152 */
153
154 private static class Node<E> {
155 volatile E item;
156 volatile Node<E> next;
157
158 /**
159 * Constructs a new node. Uses relaxed write because item can
160 * only be seen after publication via casNext.
161 */
162 Node(E item) {
163 UNSAFE.putObject(this, itemOffset, item);
164 }
165
166 boolean casItem(E cmp, E val) {
167 return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
168 }
169
170 void lazySetNext(Node<E> val) {
171 UNSAFE.putOrderedObject(this, nextOffset, val);
172 }
173
174 boolean casNext(Node<E> cmp, Node<E> val) {
175 return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
176 }
177
178 // Unsafe mechanics
179
180 private static final sun.misc.Unsafe UNSAFE;
181 private static final long itemOffset;
182 private static final long nextOffset;
183
184 static {
185 try {
186 UNSAFE = sun.misc.Unsafe.getUnsafe();
187 Class<?> k = Node.class;
188 itemOffset = UNSAFE.objectFieldOffset
189 (k.getDeclaredField("item"));
190 nextOffset = UNSAFE.objectFieldOffset
191 (k.getDeclaredField("next"));
192 } catch (Exception e) {
193 throw new Error(e);
194 }
195 }
196 }
197
198 /**
199 * A node from which the first live (non-deleted) node (if any)
200 * can be reached in O(1) time.
201 * Invariants:
202 * - all live nodes are reachable from head via succ()
203 * - head != null
204 * - (tmp = head).next != tmp || tmp != head
205 * Non-invariants:
206 * - head.item may or may not be null.
207 * - it is permitted for tail to lag behind head, that is, for tail
208 * to not be reachable from head!
209 */
210 private transient volatile Node<E> head;
211
212 /**
213 * A node from which the last node on list (that is, the unique
214 * node with node.next == null) can be reached in O(1) time.
215 * Invariants:
216 * - the last node is always reachable from tail via succ()
217 * - tail != null
218 * Non-invariants:
219 * - tail.item may or may not be null.
220 * - it is permitted for tail to lag behind head, that is, for tail
221 * to not be reachable from head!
222 * - tail.next may or may not be self-pointing to tail.
223 */
224 private transient volatile Node<E> tail;
225
226 /**
227 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
228 */
229 public ConcurrentLinkedQueue() {
230 head = tail = new Node<E>(null);
231 }
232
233 /**
234 * Creates a {@code ConcurrentLinkedQueue}
235 * initially containing the elements of the given collection,
236 * added in traversal order of the collection's iterator.
237 *
238 * @param c the collection of elements to initially contain
239 * @throws NullPointerException if the specified collection or any
240 * of its elements are null
241 */
242 public ConcurrentLinkedQueue(Collection<? extends E> c) {
243 Node<E> h = null, t = null;
244 for (E e : c) {
245 checkNotNull(e);
246 Node<E> newNode = new Node<E>(e);
247 if (h == null)
248 h = t = newNode;
249 else {
250 t.lazySetNext(newNode);
251 t = newNode;
252 }
253 }
254 if (h == null)
255 h = t = new Node<E>(null);
256 head = h;
257 tail = t;
258 }
259
260 // Have to override just to update the javadoc
261
262 /**
263 * Inserts the specified element at the tail of this queue.
264 * As the queue is unbounded, this method will never throw
265 * {@link IllegalStateException} or return {@code false}.
266 *
267 * @return {@code true} (as specified by {@link Collection#add})
268 * @throws NullPointerException if the specified element is null
269 */
270 public boolean add(E e) {
271 return offer(e);
272 }
273
274 /**
275 * Tries to CAS head to p. If successful, repoint old head to itself
276 * as sentinel for succ(), below.
277 */
278 final void updateHead(Node<E> h, Node<E> p) {
279 if (h != p && casHead(h, p))
280 h.lazySetNext(h);
281 }
282
283 /**
284 * Returns the successor of p, or the head node if p.next has been
285 * linked to self, which will only be true if traversing with a
286 * stale pointer that is now off the list.
287 */
288 final Node<E> succ(Node<E> p) {
289 Node<E> next = p.next;
290 return (p == next) ? head : next;
291 }
292
293 /**
294 * Inserts the specified element at the tail of this queue.
295 * As the queue is unbounded, this method will never return {@code false}.
296 *
297 * @return {@code true} (as specified by {@link Queue#offer})
298 * @throws NullPointerException if the specified element is null
299 */
300 public boolean offer(E e) {
301 checkNotNull(e);
302 final Node<E> newNode = new Node<E>(e);
303
304 for (Node<E> t = tail, p = t;;) {
305 Node<E> q = p.next;
306 if (q == null) {
307 // p is last node
308 if (p.casNext(null, newNode)) {
309 // Successful CAS is the linearization point
310 // for e to become an element of this queue,
311 // and for newNode to become "live".
312 if (p != t) // hop two nodes at a time
313 casTail(t, newNode); // Failure is OK.
314 return true;
315 }
316 // Lost CAS race to another thread; re-read next
317 }
318 else if (p == q)
319 // We have fallen off list. If tail is unchanged, it
320 // will also be off-list, in which case we need to
321 // jump to head, from which all live nodes are always
322 // reachable. Else the new tail is a better bet.
323 p = (t != (t = tail)) ? t : head;
324 else
325 // Check for tail updates after two hops.
326 p = (p != t && t != (t = tail)) ? t : q;
327 }
328 }
329
330 public E poll() {
331 restartFromHead:
332 for (;;) {
333 for (Node<E> h = head, p = h, q;;) {
334 E item = p.item;
335
336 if (item != null && p.casItem(item, null)) {
337 // Successful CAS is the linearization point
338 // for item to be removed from this queue.
339 if (p != h) // hop two nodes at a time
340 updateHead(h, ((q = p.next) != null) ? q : p);
341 return item;
342 }
343 else if ((q = p.next) == null) {
344 updateHead(h, p);
345 return null;
346 }
347 else if (p == q)
348 continue restartFromHead;
349 else
350 p = q;
351 }
352 }
353 }
354
355 public E peek() {
356 restartFromHead:
357 for (;;) {
358 for (Node<E> h = head, p = h, q;;) {
359 E item = p.item;
360 if (item != null || (q = p.next) == null) {
361 updateHead(h, p);
362 return item;
363 }
364 else if (p == q)
365 continue restartFromHead;
366 else
367 p = q;
368 }
369 }
370 }
371
372 /**
373 * Returns the first live (non-deleted) node on list, or null if none.
374 * This is yet another variant of poll/peek; here returning the
375 * first node, not element. We could make peek() a wrapper around
376 * first(), but that would cost an extra volatile read of item,
377 * and the need to add a retry loop to deal with the possibility
378 * of losing a race to a concurrent poll().
379 */
380 Node<E> first() {
381 restartFromHead:
382 for (;;) {
383 for (Node<E> h = head, p = h, q;;) {
384 boolean hasItem = (p.item != null);
385 if (hasItem || (q = p.next) == null) {
386 updateHead(h, p);
387 return hasItem ? p : null;
388 }
389 else if (p == q)
390 continue restartFromHead;
391 else
392 p = q;
393 }
394 }
395 }
396
397 /**
398 * Returns {@code true} if this queue contains no elements.
399 *
400 * @return {@code true} if this queue contains no elements
401 */
402 public boolean isEmpty() {
403 return first() == null;
404 }
405
406 /**
407 * Returns the number of elements in this queue. If this queue
408 * contains more than {@code Integer.MAX_VALUE} elements, returns
409 * {@code Integer.MAX_VALUE}.
410 *
411 * <p>Beware that, unlike in most collections, this method is
412 * <em>NOT</em> a constant-time operation. Because of the
413 * asynchronous nature of these queues, determining the current
414 * number of elements requires an O(n) traversal.
415 * Additionally, if elements are added or removed during execution
416 * of this method, the returned result may be inaccurate. Thus,
417 * this method is typically not very useful in concurrent
418 * applications.
419 *
420 * @return the number of elements in this queue
421 */
422 public int size() {
423 int count = 0;
424 for (Node<E> p = first(); p != null; p = succ(p))
425 if (p.item != null)
426 // Collection.size() spec says to max out
427 if (++count == Integer.MAX_VALUE)
428 break;
429 return count;
430 }
431
432 /**
433 * Returns {@code true} if this queue contains the specified element.
434 * More formally, returns {@code true} if and only if this queue contains
435 * at least one element {@code e} such that {@code o.equals(e)}.
436 *
437 * @param o object to be checked for containment in this queue
438 * @return {@code true} if this queue contains the specified element
439 */
440 public boolean contains(Object o) {
441 if (o == null) return false;
442 for (Node<E> p = first(); p != null; p = succ(p)) {
443 E item = p.item;
444 if (item != null && o.equals(item))
445 return true;
446 }
447 return false;
448 }
449
450 /**
451 * Removes a single instance of the specified element from this queue,
452 * if it is present. More formally, removes an element {@code e} such
453 * that {@code o.equals(e)}, if this queue contains one or more such
454 * elements.
455 * Returns {@code true} if this queue contained the specified element
456 * (or equivalently, if this queue changed as a result of the call).
457 *
458 * @param o element to be removed from this queue, if present
459 * @return {@code true} if this queue changed as a result of the call
460 */
461 public boolean remove(Object o) {
462 if (o == null) return false;
463 Node<E> pred = null;
464 for (Node<E> p = first(); p != null; p = succ(p)) {
465 E item = p.item;
466 if (item != null &&
467 o.equals(item) &&
468 p.casItem(item, null)) {
469 Node<E> next = succ(p);
470 if (pred != null && next != null)
471 pred.casNext(p, next);
472 return true;
473 }
474 pred = p;
475 }
476 return false;
477 }
478
479 /**
480 * Appends all of the elements in the specified collection to the end of
481 * this queue, in the order that they are returned by the specified
482 * collection's iterator. Attempts to {@code addAll} of a queue to
483 * itself result in {@code IllegalArgumentException}.
484 *
485 * @param c the elements to be inserted into this queue
486 * @return {@code true} if this queue changed as a result of the call
487 * @throws NullPointerException if the specified collection or any
488 * of its elements are null
489 * @throws IllegalArgumentException if the collection is this queue
490 */
491 public boolean addAll(Collection<? extends E> c) {
492 if (c == this)
493 // As historically specified in AbstractQueue#addAll
494 throw new IllegalArgumentException();
495
496 // Copy c into a private chain of Nodes
497 Node<E> beginningOfTheEnd = null, last = null;
498 for (E e : c) {
499 checkNotNull(e);
500 Node<E> newNode = new Node<E>(e);
501 if (beginningOfTheEnd == null)
502 beginningOfTheEnd = last = newNode;
503 else {
504 last.lazySetNext(newNode);
505 last = newNode;
506 }
507 }
508 if (beginningOfTheEnd == null)
509 return false;
510
511 // Atomically append the chain at the tail of this collection
512 for (Node<E> t = tail, p = t;;) {
513 Node<E> q = p.next;
514 if (q == null) {
515 // p is last node
516 if (p.casNext(null, beginningOfTheEnd)) {
517 // Successful CAS is the linearization point
518 // for all elements to be added to this queue.
519 if (!casTail(t, last)) {
520 // Try a little harder to update tail,
521 // since we may be adding many elements.
522 t = tail;
523 if (last.next == null)
524 casTail(t, last);
525 }
526 return true;
527 }
528 // Lost CAS race to another thread; re-read next
529 }
530 else if (p == q)
531 // We have fallen off list. If tail is unchanged, it
532 // will also be off-list, in which case we need to
533 // jump to head, from which all live nodes are always
534 // reachable. Else the new tail is a better bet.
535 p = (t != (t = tail)) ? t : head;
536 else
537 // Check for tail updates after two hops.
538 p = (p != t && t != (t = tail)) ? t : q;
539 }
540 }
541
542 /**
543 * Returns an array containing all of the elements in this queue, in
544 * proper sequence.
545 *
546 * <p>The returned array will be "safe" in that no references to it are
547 * maintained by this queue. (In other words, this method must allocate
548 * a new array). The caller is thus free to modify the returned array.
549 *
550 * <p>This method acts as bridge between array-based and collection-based
551 * APIs.
552 *
553 * @return an array containing all of the elements in this queue
554 */
555 public Object[] toArray() {
556 // Use ArrayList to deal with resizing.
557 ArrayList<E> al = new ArrayList<E>();
558 for (Node<E> p = first(); p != null; p = succ(p)) {
559 E item = p.item;
560 if (item != null)
561 al.add(item);
562 }
563 return al.toArray();
564 }
565
566 /**
567 * Returns an array containing all of the elements in this queue, in
568 * proper sequence; the runtime type of the returned array is that of
569 * the specified array. If the queue fits in the specified array, it
570 * is returned therein. Otherwise, a new array is allocated with the
571 * runtime type of the specified array and the size of this queue.
572 *
573 * <p>If this queue fits in the specified array with room to spare
574 * (i.e., the array has more elements than this queue), the element in
575 * the array immediately following the end of the queue is set to
576 * {@code null}.
577 *
578 * <p>Like the {@link #toArray()} method, this method acts as bridge between
579 * array-based and collection-based APIs. Further, this method allows
580 * precise control over the runtime type of the output array, and may,
581 * under certain circumstances, be used to save allocation costs.
582 *
583 * <p>Suppose {@code x} is a queue known to contain only strings.
584 * The following code can be used to dump the queue into a newly
585 * allocated array of {@code String}:
586 *
587 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
588 *
589 * Note that {@code toArray(new Object[0])} is identical in function to
590 * {@code toArray()}.
591 *
592 * @param a the array into which the elements of the queue are to
593 * be stored, if it is big enough; otherwise, a new array of the
594 * same runtime type is allocated for this purpose
595 * @return an array containing all of the elements in this queue
596 * @throws ArrayStoreException if the runtime type of the specified array
597 * is not a supertype of the runtime type of every element in
598 * this queue
599 * @throws NullPointerException if the specified array is null
600 */
601 @SuppressWarnings("unchecked")
602 public <T> T[] toArray(T[] a) {
603 // try to use sent-in array
604 int k = 0;
605 Node<E> p;
606 for (p = first(); p != null && k < a.length; p = succ(p)) {
607 E item = p.item;
608 if (item != null)
609 a[k++] = (T)item;
610 }
611 if (p == null) {
612 if (k < a.length)
613 a[k] = null;
614 return a;
615 }
616
617 // If won't fit, use ArrayList version
618 ArrayList<E> al = new ArrayList<E>();
619 for (Node<E> q = first(); q != null; q = succ(q)) {
620 E item = q.item;
621 if (item != null)
622 al.add(item);
623 }
624 return al.toArray(a);
625 }
626
627 /**
628 * Returns an iterator over the elements in this queue in proper sequence.
629 * The elements will be returned in order from first (head) to last (tail).
630 *
631 * <p>The returned iterator is
632 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
633 *
634 * @return an iterator over the elements in this queue in proper sequence
635 */
636 public Iterator<E> iterator() {
637 return new Itr();
638 }
639
640 private class Itr implements Iterator<E> {
641 /**
642 * Next node to return item for.
643 */
644 private Node<E> nextNode;
645
646 /**
647 * nextItem holds on to item fields because once we claim
648 * that an element exists in hasNext(), we must return it in
649 * the following next() call even if it was in the process of
650 * being removed when hasNext() was called.
651 */
652 private E nextItem;
653
654 /**
655 * Node of the last returned item, to support remove.
656 */
657 private Node<E> lastRet;
658
659 Itr() {
660 advance();
661 }
662
663 /**
664 * Moves to next valid node and returns item to return for
665 * next(), or null if no such.
666 */
667 private E advance() {
668 lastRet = nextNode;
669 E x = nextItem;
670
671 Node<E> pred, p;
672 if (nextNode == null) {
673 p = first();
674 pred = null;
675 } else {
676 pred = nextNode;
677 p = succ(nextNode);
678 }
679
680 for (;;) {
681 if (p == null) {
682 nextNode = null;
683 nextItem = null;
684 return x;
685 }
686 E item = p.item;
687 if (item != null) {
688 nextNode = p;
689 nextItem = item;
690 return x;
691 } else {
692 // skip over nulls
693 Node<E> next = succ(p);
694 if (pred != null && next != null)
695 pred.casNext(p, next);
696 p = next;
697 }
698 }
699 }
700
701 public boolean hasNext() {
702 return nextNode != null;
703 }
704
705 public E next() {
706 if (nextNode == null) throw new NoSuchElementException();
707 return advance();
708 }
709
710 public void remove() {
711 Node<E> l = lastRet;
712 if (l == null) throw new IllegalStateException();
713 // rely on a future traversal to relink.
714 l.item = null;
715 lastRet = null;
716 }
717 }
718
719 /**
720 * Saves this queue to a stream (that is, serializes it).
721 *
722 * @param s the stream
723 * @throws java.io.IOException if an I/O error occurs
724 * @serialData All of the elements (each an {@code E}) in
725 * the proper order, followed by a null
726 */
727 private void writeObject(java.io.ObjectOutputStream s)
728 throws java.io.IOException {
729
730 // Write out any hidden stuff
731 s.defaultWriteObject();
732
733 // Write out all elements in the proper order.
734 for (Node<E> p = first(); p != null; p = succ(p)) {
735 Object item = p.item;
736 if (item != null)
737 s.writeObject(item);
738 }
739
740 // Use trailing null as sentinel
741 s.writeObject(null);
742 }
743
744 /**
745 * Reconstitutes this queue from a stream (that is, deserializes it).
746 * @param s the stream
747 * @throws ClassNotFoundException if the class of a serialized object
748 * could not be found
749 * @throws java.io.IOException if an I/O error occurs
750 */
751 private void readObject(java.io.ObjectInputStream s)
752 throws java.io.IOException, ClassNotFoundException {
753 s.defaultReadObject();
754
755 // Read in elements until trailing null sentinel found
756 Node<E> h = null, t = null;
757 Object item;
758 while ((item = s.readObject()) != null) {
759 @SuppressWarnings("unchecked")
760 Node<E> newNode = new Node<E>((E) item);
761 if (h == null)
762 h = t = newNode;
763 else {
764 t.lazySetNext(newNode);
765 t = newNode;
766 }
767 }
768 if (h == null)
769 h = t = new Node<E>(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 | Spliterator.NONNULL |
807 Spliterator.CONCURRENT);
808 }
809 }
810 return null;
811 }
812
813 public void forEachRemaining(Consumer<? super E> action) {
814 Node<E> p;
815 if (action == null) throw new NullPointerException();
816 final ConcurrentLinkedQueue<E> q = this.queue;
817 if (!exhausted &&
818 ((p = current) != null || (p = q.first()) != null)) {
819 exhausted = true;
820 do {
821 E e = p.item;
822 if (p == (p = p.next))
823 p = q.first();
824 if (e != null)
825 action.accept(e);
826 } while (p != null);
827 }
828 }
829
830 public boolean tryAdvance(Consumer<? super E> action) {
831 Node<E> p;
832 if (action == null) throw new NullPointerException();
833 final ConcurrentLinkedQueue<E> q = this.queue;
834 if (!exhausted &&
835 ((p = current) != null || (p = q.first()) != null)) {
836 E e;
837 do {
838 e = p.item;
839 if (p == (p = p.next))
840 p = q.first();
841 } while (e == null && p != null);
842 if ((current = p) == null)
843 exhausted = true;
844 if (e != null) {
845 action.accept(e);
846 return true;
847 }
848 }
849 return false;
850 }
851
852 public long estimateSize() { return Long.MAX_VALUE; }
853
854 public int characteristics() {
855 return Spliterator.ORDERED | Spliterator.NONNULL |
856 Spliterator.CONCURRENT;
857 }
858 }
859
860 /**
861 * Returns a {@link Spliterator} over the elements in this queue.
862 *
863 * <p>The returned spliterator is
864 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
865 *
866 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
867 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
868 *
869 * @implNote
870 * The {@code Spliterator} implements {@code trySplit} to permit limited
871 * parallelism.
872 *
873 * @return a {@code Spliterator} over the elements in this queue
874 * @since 1.8
875 */
876 @Override
877 public Spliterator<E> spliterator() {
878 return new CLQSpliterator<E>(this);
879 }
880
881 /**
882 * Throws NullPointerException if argument is null.
883 *
884 * @param v the element
885 */
886 private static void checkNotNull(Object v) {
887 if (v == null)
888 throw new NullPointerException();
889 }
890
891 private boolean casTail(Node<E> cmp, Node<E> val) {
892 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
893 }
894
895 private boolean casHead(Node<E> cmp, Node<E> val) {
896 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
897 }
898
899 // Unsafe mechanics
900
901 private static final sun.misc.Unsafe UNSAFE;
902 private static final long headOffset;
903 private static final long tailOffset;
904 static {
905 try {
906 UNSAFE = sun.misc.Unsafe.getUnsafe();
907 Class<?> k = ConcurrentLinkedQueue.class;
908 headOffset = UNSAFE.objectFieldOffset
909 (k.getDeclaredField("head"));
910 tailOffset = UNSAFE.objectFieldOffset
911 (k.getDeclaredField("tail"));
912 } catch (Exception e) {
913 throw new Error(e);
914 }
915 }
916 }