ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.85
Committed: Wed Mar 13 12:39:01 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.84: +1 -10 lines
Log Message:
Synch with lambda Spliterator API

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