ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.93
Committed: Mon Jun 17 17:17:05 2013 UTC (10 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.92: +1 -1 lines
Log Message:
inaccurate terminology; s/wait-free/non-blocking/

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 <a
38 * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
39 * 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 a "weakly consistent" iterator that
632 * will never throw {@link java.util.ConcurrentModificationException
633 * ConcurrentModificationException}, and guarantees to traverse
634 * elements as they existed upon construction of the iterator, and
635 * may (but is not guaranteed to) reflect any modifications
636 * subsequent to construction.
637 *
638 * @return an iterator over the elements in this queue in proper sequence
639 */
640 public Iterator<E> iterator() {
641 return new Itr();
642 }
643
644 private class Itr implements Iterator<E> {
645 /**
646 * Next node to return item for.
647 */
648 private Node<E> nextNode;
649
650 /**
651 * nextItem holds on to item fields because once we claim
652 * that an element exists in hasNext(), we must return it in
653 * the following next() call even if it was in the process of
654 * being removed when hasNext() was called.
655 */
656 private E nextItem;
657
658 /**
659 * Node of the last returned item, to support remove.
660 */
661 private Node<E> lastRet;
662
663 Itr() {
664 advance();
665 }
666
667 /**
668 * Moves to next valid node and returns item to return for
669 * next(), or null if no such.
670 */
671 private E advance() {
672 lastRet = nextNode;
673 E x = nextItem;
674
675 Node<E> pred, p;
676 if (nextNode == null) {
677 p = first();
678 pred = null;
679 } else {
680 pred = nextNode;
681 p = succ(nextNode);
682 }
683
684 for (;;) {
685 if (p == null) {
686 nextNode = null;
687 nextItem = null;
688 return x;
689 }
690 E item = p.item;
691 if (item != null) {
692 nextNode = p;
693 nextItem = item;
694 return x;
695 } else {
696 // skip over nulls
697 Node<E> next = succ(p);
698 if (pred != null && next != null)
699 pred.casNext(p, next);
700 p = next;
701 }
702 }
703 }
704
705 public boolean hasNext() {
706 return nextNode != null;
707 }
708
709 public E next() {
710 if (nextNode == null) throw new NoSuchElementException();
711 return advance();
712 }
713
714 public void remove() {
715 Node<E> l = lastRet;
716 if (l == null) throw new IllegalStateException();
717 // rely on a future traversal to relink.
718 l.item = null;
719 lastRet = null;
720 }
721 }
722
723 /**
724 * Saves this queue to a stream (that is, serializes it).
725 *
726 * @serialData All of the elements (each an {@code E}) in
727 * the proper order, followed by a null
728 */
729 private void writeObject(java.io.ObjectOutputStream s)
730 throws java.io.IOException {
731
732 // Write out any hidden stuff
733 s.defaultWriteObject();
734
735 // Write out all elements in the proper order.
736 for (Node<E> p = first(); p != null; p = succ(p)) {
737 Object item = p.item;
738 if (item != null)
739 s.writeObject(item);
740 }
741
742 // Use trailing null as sentinel
743 s.writeObject(null);
744 }
745
746 /**
747 * Reconstitutes this queue from a stream (that is, deserializes it).
748 */
749 private void readObject(java.io.ObjectInputStream s)
750 throws java.io.IOException, ClassNotFoundException {
751 s.defaultReadObject();
752
753 // Read in elements until trailing null sentinel found
754 Node<E> h = null, t = null;
755 Object item;
756 while ((item = s.readObject()) != null) {
757 @SuppressWarnings("unchecked")
758 Node<E> newNode = new Node<E>((E) item);
759 if (h == null)
760 h = t = newNode;
761 else {
762 t.lazySetNext(newNode);
763 t = newNode;
764 }
765 }
766 if (h == null)
767 h = t = new Node<E>(null);
768 head = h;
769 tail = t;
770 }
771
772 /** A customized variant of Spliterators.IteratorSpliterator */
773 static final class CLQSpliterator<E> implements Spliterator<E> {
774 static final int MAX_BATCH = 1 << 25; // max batch array size;
775 final ConcurrentLinkedQueue<E> queue;
776 Node<E> current; // current node; null until initialized
777 int batch; // batch size for splits
778 boolean exhausted; // true when no more nodes
779 CLQSpliterator(ConcurrentLinkedQueue<E> queue) {
780 this.queue = queue;
781 }
782
783 public Spliterator<E> trySplit() {
784 Node<E> p;
785 final ConcurrentLinkedQueue<E> q = this.queue;
786 int b = batch;
787 int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
788 if (!exhausted &&
789 ((p = current) != null || (p = q.first()) != null) &&
790 p.next != null) {
791 Object[] a = new Object[n];
792 int i = 0;
793 do {
794 if ((a[i] = p.item) != null)
795 ++i;
796 if (p == (p = p.next))
797 p = q.first();
798 } while (p != null && i < n);
799 if ((current = p) == null)
800 exhausted = true;
801 if (i > 0) {
802 batch = i;
803 return Spliterators.spliterator
804 (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
805 Spliterator.CONCURRENT);
806 }
807 }
808 return null;
809 }
810
811 public void forEachRemaining(Consumer<? super E> action) {
812 Node<E> p;
813 if (action == null) throw new NullPointerException();
814 final ConcurrentLinkedQueue<E> q = this.queue;
815 if (!exhausted &&
816 ((p = current) != null || (p = q.first()) != null)) {
817 exhausted = true;
818 do {
819 E e = p.item;
820 if (p == (p = p.next))
821 p = q.first();
822 if (e != null)
823 action.accept(e);
824 } while (p != null);
825 }
826 }
827
828 public boolean tryAdvance(Consumer<? super E> action) {
829 Node<E> p;
830 if (action == null) throw new NullPointerException();
831 final ConcurrentLinkedQueue<E> q = this.queue;
832 if (!exhausted &&
833 ((p = current) != null || (p = q.first()) != null)) {
834 E e;
835 do {
836 e = p.item;
837 if (p == (p = p.next))
838 p = q.first();
839 } while (e == null && p != null);
840 if ((current = p) == null)
841 exhausted = true;
842 if (e != null) {
843 action.accept(e);
844 return true;
845 }
846 }
847 return false;
848 }
849
850 public long estimateSize() { return Long.MAX_VALUE; }
851
852 public int characteristics() {
853 return Spliterator.ORDERED | Spliterator.NONNULL |
854 Spliterator.CONCURRENT;
855 }
856 }
857
858
859 public Spliterator<E> spliterator() {
860 return new CLQSpliterator<E>(this);
861 }
862
863 /**
864 * Throws NullPointerException if argument is null.
865 *
866 * @param v the element
867 */
868 private static void checkNotNull(Object v) {
869 if (v == null)
870 throw new NullPointerException();
871 }
872
873 private boolean casTail(Node<E> cmp, Node<E> val) {
874 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
875 }
876
877 private boolean casHead(Node<E> cmp, Node<E> val) {
878 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
879 }
880
881 // Unsafe mechanics
882
883 private static final sun.misc.Unsafe UNSAFE;
884 private static final long headOffset;
885 private static final long tailOffset;
886 static {
887 try {
888 UNSAFE = sun.misc.Unsafe.getUnsafe();
889 Class<?> k = ConcurrentLinkedQueue.class;
890 headOffset = UNSAFE.objectFieldOffset
891 (k.getDeclaredField("head"));
892 tailOffset = UNSAFE.objectFieldOffset
893 (k.getDeclaredField("tail"));
894 } catch (Exception e) {
895 throw new Error(e);
896 }
897 }
898 }