ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.117
Committed: Fri Feb 20 03:09:08 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.116: +75 -30 lines
Log Message:
improve toArray and toString implementations

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