ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.94
Committed: Mon Oct 1 00:10:53 2018 UTC (5 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.93: +1 -1 lines
Log Message:
update to using jdk11 by default, except link to jdk10 javadocs;
sync @docRoot references in javadoc with upstream

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.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.util.AbstractCollection;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Deque;
15 import java.util.Iterator;
16 import java.util.NoSuchElementException;
17 import java.util.Objects;
18 import java.util.Queue;
19 import java.util.Spliterator;
20 import java.util.Spliterators;
21 import java.util.function.Consumer;
22 import java.util.function.Predicate;
23
24 /**
25 * An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
26 * Concurrent insertion, removal, and access operations execute safely
27 * across multiple threads.
28 * A {@code ConcurrentLinkedDeque} is an appropriate choice when
29 * many threads will share access to a common collection.
30 * Like most other concurrent collection implementations, this class
31 * does not permit the use of {@code null} elements.
32 *
33 * <p>Iterators and spliterators are
34 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
35 *
36 * <p>Beware that, unlike in most collections, the {@code size} method
37 * is <em>NOT</em> a constant-time operation. Because of the
38 * asynchronous nature of these deques, determining the current number
39 * of elements requires a traversal of the elements, and so may report
40 * inaccurate results if this collection is modified during traversal.
41 *
42 * <p>Bulk operations that add, remove, or examine multiple elements,
43 * such as {@link #addAll}, {@link #removeIf} or {@link #forEach},
44 * are <em>not</em> guaranteed to be performed atomically.
45 * For example, a {@code forEach} traversal concurrent with an {@code
46 * addAll} operation might observe only some of the added elements.
47 *
48 * <p>This class and its iterator implement all of the <em>optional</em>
49 * methods of the {@link Deque} and {@link Iterator} interfaces.
50 *
51 * <p>Memory consistency effects: As with other concurrent collections,
52 * actions in a thread prior to placing an object into a
53 * {@code ConcurrentLinkedDeque}
54 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
55 * actions subsequent to the access or removal of that element from
56 * the {@code ConcurrentLinkedDeque} in another thread.
57 *
58 * <p>This class is a member of the
59 * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
60 * Java Collections Framework</a>.
61 *
62 * @since 1.7
63 * @author Doug Lea
64 * @author Martin Buchholz
65 * @param <E> the type of elements held in this deque
66 */
67 public class ConcurrentLinkedDeque<E>
68 extends AbstractCollection<E>
69 implements Deque<E>, java.io.Serializable {
70
71 /*
72 * This is an implementation of a concurrent lock-free deque
73 * supporting interior removes but not interior insertions, as
74 * required to support the entire Deque interface.
75 *
76 * We extend the techniques developed for ConcurrentLinkedQueue and
77 * LinkedTransferQueue (see the internal docs for those classes).
78 * Understanding the ConcurrentLinkedQueue implementation is a
79 * prerequisite for understanding the implementation of this class.
80 *
81 * The data structure is a symmetrical doubly-linked "GC-robust"
82 * linked list of nodes. We minimize the number of volatile writes
83 * using two techniques: advancing multiple hops with a single CAS
84 * and mixing volatile and non-volatile writes of the same memory
85 * locations.
86 *
87 * A node contains the expected E ("item") and links to predecessor
88 * ("prev") and successor ("next") nodes:
89 *
90 * class Node<E> { volatile Node<E> prev, next; volatile E item; }
91 *
92 * A node p is considered "live" if it contains a non-null item
93 * (p.item != null). When an item is CASed to null, the item is
94 * atomically logically deleted from the collection.
95 *
96 * At any time, there is precisely one "first" node with a null
97 * prev reference that terminates any chain of prev references
98 * starting at a live node. Similarly there is precisely one
99 * "last" node terminating any chain of next references starting at
100 * a live node. The "first" and "last" nodes may or may not be live.
101 * The "first" and "last" nodes are always mutually reachable.
102 *
103 * A new element is added atomically by CASing the null prev or
104 * next reference in the first or last node to a fresh node
105 * containing the element. The element's node atomically becomes
106 * "live" at that point.
107 *
108 * A node is considered "active" if it is a live node, or the
109 * first or last node. Active nodes cannot be unlinked.
110 *
111 * A "self-link" is a next or prev reference that is the same node:
112 * p.prev == p or p.next == p
113 * Self-links are used in the node unlinking process. Active nodes
114 * never have self-links.
115 *
116 * A node p is active if and only if:
117 *
118 * p.item != null ||
119 * (p.prev == null && p.next != p) ||
120 * (p.next == null && p.prev != p)
121 *
122 * The deque object has two node references, "head" and "tail".
123 * The head and tail are only approximations to the first and last
124 * nodes of the deque. The first node can always be found by
125 * following prev pointers from head; likewise for tail. However,
126 * it is permissible for head and tail to be referring to deleted
127 * nodes that have been unlinked and so may not be reachable from
128 * any live node.
129 *
130 * There are 3 stages of node deletion;
131 * "logical deletion", "unlinking", and "gc-unlinking".
132 *
133 * 1. "logical deletion" by CASing item to null atomically removes
134 * the element from the collection, and makes the containing node
135 * eligible for unlinking.
136 *
137 * 2. "unlinking" makes a deleted node unreachable from active
138 * nodes, and thus eventually reclaimable by GC. Unlinked nodes
139 * may remain reachable indefinitely from an iterator.
140 *
141 * Physical node unlinking is merely an optimization (albeit a
142 * critical one), and so can be performed at our convenience. At
143 * any time, the set of live nodes maintained by prev and next
144 * links are identical, that is, the live nodes found via next
145 * links from the first node is equal to the elements found via
146 * prev links from the last node. However, this is not true for
147 * nodes that have already been logically deleted - such nodes may
148 * be reachable in one direction only.
149 *
150 * 3. "gc-unlinking" takes unlinking further by making active
151 * nodes unreachable from deleted nodes, making it easier for the
152 * GC to reclaim future deleted nodes. This step makes the data
153 * structure "gc-robust", as first described in detail by Boehm
154 * (http://portal.acm.org/citation.cfm?doid=503272.503282).
155 *
156 * GC-unlinked nodes may remain reachable indefinitely from an
157 * iterator, but unlike unlinked nodes, are never reachable from
158 * head or tail.
159 *
160 * Making the data structure GC-robust will eliminate the risk of
161 * unbounded memory retention with conservative GCs and is likely
162 * to improve performance with generational GCs.
163 *
164 * When a node is dequeued at either end, e.g. via poll(), we would
165 * like to break any references from the node to active nodes. We
166 * develop further the use of self-links that was very effective in
167 * other concurrent collection classes. The idea is to replace
168 * prev and next pointers with special values that are interpreted
169 * to mean off-the-list-at-one-end. These are approximations, but
170 * good enough to preserve the properties we want in our
171 * traversals, e.g. we guarantee that a traversal will never visit
172 * the same element twice, but we don't guarantee whether a
173 * traversal that runs out of elements will be able to see more
174 * elements later after enqueues at that end. Doing gc-unlinking
175 * safely is particularly tricky, since any node can be in use
176 * indefinitely (for example by an iterator). We must ensure that
177 * the nodes pointed at by head/tail never get gc-unlinked, since
178 * head/tail are needed to get "back on track" by other nodes that
179 * are gc-unlinked. gc-unlinking accounts for much of the
180 * implementation complexity.
181 *
182 * Since neither unlinking nor gc-unlinking are necessary for
183 * correctness, there are many implementation choices regarding
184 * frequency (eagerness) of these operations. Since volatile
185 * reads are likely to be much cheaper than CASes, saving CASes by
186 * unlinking multiple adjacent nodes at a time may be a win.
187 * gc-unlinking can be performed rarely and still be effective,
188 * since it is most important that long chains of deleted nodes
189 * are occasionally broken.
190 *
191 * The actual representation we use is that p.next == p means to
192 * goto the first node (which in turn is reached by following prev
193 * pointers from head), and p.next == null && p.prev == p means
194 * that the iteration is at an end and that p is a (static final)
195 * dummy node, NEXT_TERMINATOR, and not the last active node.
196 * Finishing the iteration when encountering such a TERMINATOR is
197 * good enough for read-only traversals, so such traversals can use
198 * p.next == null as the termination condition. When we need to
199 * find the last (active) node, for enqueueing a new node, we need
200 * to check whether we have reached a TERMINATOR node; if so,
201 * restart traversal from tail.
202 *
203 * The implementation is completely directionally symmetrical,
204 * except that most public methods that iterate through the list
205 * follow next pointers, in the "forward" direction.
206 *
207 * We believe (without full proof) that all single-element Deque
208 * operations that operate directly at the two ends of the Deque
209 * (e.g., addFirst, peekLast, pollLast) are linearizable (see
210 * Herlihy and Shavit's book). However, some combinations of
211 * operations are known not to be linearizable. In particular,
212 * when an addFirst(A) is racing with pollFirst() removing B, it
213 * is possible for an observer iterating over the elements to
214 * observe first [A B C] and then [A C], even though no interior
215 * removes are ever performed. Nevertheless, iterators behave
216 * reasonably, providing the "weakly consistent" guarantees.
217 *
218 * Empirically, microbenchmarks suggest that this class adds about
219 * 40% overhead relative to ConcurrentLinkedQueue, which feels as
220 * good as we can hope for.
221 */
222
223 private static final long serialVersionUID = 876323262645176354L;
224
225 /**
226 * A node from which the first node on list (that is, the unique node p
227 * with p.prev == null && p.next != p) can be reached in O(1) time.
228 * Invariants:
229 * - the first node is always O(1) reachable from head via prev links
230 * - all live nodes are reachable from the first node via succ()
231 * - head != null
232 * - (tmp = head).next != tmp || tmp != head
233 * - head is never gc-unlinked (but may be unlinked)
234 * Non-invariants:
235 * - head.item may or may not be null
236 * - head may not be reachable from the first or last node, or from tail
237 */
238 private transient volatile Node<E> head;
239
240 /**
241 * A node from which the last node on list (that is, the unique node p
242 * with p.next == null && p.prev != p) can be reached in O(1) time.
243 * Invariants:
244 * - the last node is always O(1) reachable from tail via next links
245 * - all live nodes are reachable from the last node via pred()
246 * - tail != null
247 * - tail is never gc-unlinked (but may be unlinked)
248 * Non-invariants:
249 * - tail.item may or may not be null
250 * - tail may not be reachable from the first or last node, or from head
251 */
252 private transient volatile Node<E> tail;
253
254 private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR;
255
256 @SuppressWarnings("unchecked")
257 Node<E> prevTerminator() {
258 return (Node<E>) PREV_TERMINATOR;
259 }
260
261 @SuppressWarnings("unchecked")
262 Node<E> nextTerminator() {
263 return (Node<E>) NEXT_TERMINATOR;
264 }
265
266 static final class Node<E> {
267 volatile Node<E> prev;
268 volatile E item;
269 volatile Node<E> next;
270 }
271
272 /**
273 * Returns a new node holding item. Uses relaxed write because item
274 * can only be seen after piggy-backing publication via CAS.
275 */
276 static <E> Node<E> newNode(E item) {
277 Node<E> node = new Node<E>();
278 ITEM.set(node, item);
279 return node;
280 }
281
282 /**
283 * Links e as first element.
284 */
285 private void linkFirst(E e) {
286 final Node<E> newNode = newNode(Objects.requireNonNull(e));
287
288 restartFromHead:
289 for (;;)
290 for (Node<E> h = head, p = h, q;;) {
291 if ((q = p.prev) != null &&
292 (q = (p = q).prev) != null)
293 // Check for head updates every other hop.
294 // If p == q, we are sure to follow head instead.
295 p = (h != (h = head)) ? h : q;
296 else if (p.next == p) // PREV_TERMINATOR
297 continue restartFromHead;
298 else {
299 // p is first node
300 NEXT.set(newNode, p); // CAS piggyback
301 if (PREV.compareAndSet(p, null, newNode)) {
302 // Successful CAS is the linearization point
303 // for e to become an element of this deque,
304 // and for newNode to become "live".
305 if (p != h) // hop two nodes at a time; failure is OK
306 HEAD.weakCompareAndSet(this, h, newNode);
307 return;
308 }
309 // Lost CAS race to another thread; re-read prev
310 }
311 }
312 }
313
314 /**
315 * Links e as last element.
316 */
317 private void linkLast(E e) {
318 final Node<E> newNode = newNode(Objects.requireNonNull(e));
319
320 restartFromTail:
321 for (;;)
322 for (Node<E> t = tail, p = t, q;;) {
323 if ((q = p.next) != null &&
324 (q = (p = q).next) != null)
325 // Check for tail updates every other hop.
326 // If p == q, we are sure to follow tail instead.
327 p = (t != (t = tail)) ? t : q;
328 else if (p.prev == p) // NEXT_TERMINATOR
329 continue restartFromTail;
330 else {
331 // p is last node
332 PREV.set(newNode, p); // CAS piggyback
333 if (NEXT.compareAndSet(p, null, newNode)) {
334 // Successful CAS is the linearization point
335 // for e to become an element of this deque,
336 // and for newNode to become "live".
337 if (p != t) // hop two nodes at a time; failure is OK
338 TAIL.weakCompareAndSet(this, t, newNode);
339 return;
340 }
341 // Lost CAS race to another thread; re-read next
342 }
343 }
344 }
345
346 private static final int HOPS = 2;
347
348 /**
349 * Unlinks non-null node x.
350 */
351 void unlink(Node<E> x) {
352 // assert x != null;
353 // assert x.item == null;
354 // assert x != PREV_TERMINATOR;
355 // assert x != NEXT_TERMINATOR;
356
357 final Node<E> prev = x.prev;
358 final Node<E> next = x.next;
359 if (prev == null) {
360 unlinkFirst(x, next);
361 } else if (next == null) {
362 unlinkLast(x, prev);
363 } else {
364 // Unlink interior node.
365 //
366 // This is the common case, since a series of polls at the
367 // same end will be "interior" removes, except perhaps for
368 // the first one, since end nodes cannot be unlinked.
369 //
370 // At any time, all active nodes are mutually reachable by
371 // following a sequence of either next or prev pointers.
372 //
373 // Our strategy is to find the unique active predecessor
374 // and successor of x. Try to fix up their links so that
375 // they point to each other, leaving x unreachable from
376 // active nodes. If successful, and if x has no live
377 // predecessor/successor, we additionally try to gc-unlink,
378 // leaving active nodes unreachable from x, by rechecking
379 // that the status of predecessor and successor are
380 // unchanged and ensuring that x is not reachable from
381 // tail/head, before setting x's prev/next links to their
382 // logical approximate replacements, self/TERMINATOR.
383 Node<E> activePred, activeSucc;
384 boolean isFirst, isLast;
385 int hops = 1;
386
387 // Find active predecessor
388 for (Node<E> p = prev; ; ++hops) {
389 if (p.item != null) {
390 activePred = p;
391 isFirst = false;
392 break;
393 }
394 Node<E> q = p.prev;
395 if (q == null) {
396 if (p.next == p)
397 return;
398 activePred = p;
399 isFirst = true;
400 break;
401 }
402 else if (p == q)
403 return;
404 else
405 p = q;
406 }
407
408 // Find active successor
409 for (Node<E> p = next; ; ++hops) {
410 if (p.item != null) {
411 activeSucc = p;
412 isLast = false;
413 break;
414 }
415 Node<E> q = p.next;
416 if (q == null) {
417 if (p.prev == p)
418 return;
419 activeSucc = p;
420 isLast = true;
421 break;
422 }
423 else if (p == q)
424 return;
425 else
426 p = q;
427 }
428
429 // TODO: better HOP heuristics
430 if (hops < HOPS
431 // always squeeze out interior deleted nodes
432 && (isFirst | isLast))
433 return;
434
435 // Squeeze out deleted nodes between activePred and
436 // activeSucc, including x.
437 skipDeletedSuccessors(activePred);
438 skipDeletedPredecessors(activeSucc);
439
440 // Try to gc-unlink, if possible
441 if ((isFirst | isLast) &&
442
443 // Recheck expected state of predecessor and successor
444 (activePred.next == activeSucc) &&
445 (activeSucc.prev == activePred) &&
446 (isFirst ? activePred.prev == null : activePred.item != null) &&
447 (isLast ? activeSucc.next == null : activeSucc.item != null)) {
448
449 updateHead(); // Ensure x is not reachable from head
450 updateTail(); // Ensure x is not reachable from tail
451
452 // Finally, actually gc-unlink
453 PREV.setRelease(x, isFirst ? prevTerminator() : x);
454 NEXT.setRelease(x, isLast ? nextTerminator() : x);
455 }
456 }
457 }
458
459 /**
460 * Unlinks non-null first node.
461 */
462 private void unlinkFirst(Node<E> first, Node<E> next) {
463 // assert first != null;
464 // assert next != null;
465 // assert first.item == null;
466 for (Node<E> o = null, p = next, q;;) {
467 if (p.item != null || (q = p.next) == null) {
468 if (o != null && p.prev != p &&
469 NEXT.compareAndSet(first, next, p)) {
470 skipDeletedPredecessors(p);
471 if (first.prev == null &&
472 (p.next == null || p.item != null) &&
473 p.prev == first) {
474
475 updateHead(); // Ensure o is not reachable from head
476 updateTail(); // Ensure o is not reachable from tail
477
478 // Finally, actually gc-unlink
479 NEXT.setRelease(o, o);
480 PREV.setRelease(o, prevTerminator());
481 }
482 }
483 return;
484 }
485 else if (p == q)
486 return;
487 else {
488 o = p;
489 p = q;
490 }
491 }
492 }
493
494 /**
495 * Unlinks non-null last node.
496 */
497 private void unlinkLast(Node<E> last, Node<E> prev) {
498 // assert last != null;
499 // assert prev != null;
500 // assert last.item == null;
501 for (Node<E> o = null, p = prev, q;;) {
502 if (p.item != null || (q = p.prev) == null) {
503 if (o != null && p.next != p &&
504 PREV.compareAndSet(last, prev, p)) {
505 skipDeletedSuccessors(p);
506 if (last.next == null &&
507 (p.prev == null || p.item != null) &&
508 p.next == last) {
509
510 updateHead(); // Ensure o is not reachable from head
511 updateTail(); // Ensure o is not reachable from tail
512
513 // Finally, actually gc-unlink
514 PREV.setRelease(o, o);
515 NEXT.setRelease(o, nextTerminator());
516 }
517 }
518 return;
519 }
520 else if (p == q)
521 return;
522 else {
523 o = p;
524 p = q;
525 }
526 }
527 }
528
529 /**
530 * Guarantees that any node which was unlinked before a call to
531 * this method will be unreachable from head after it returns.
532 * Does not guarantee to eliminate slack, only that head will
533 * point to a node that was active while this method was running.
534 */
535 private final void updateHead() {
536 // Either head already points to an active node, or we keep
537 // trying to cas it to the first node until it does.
538 Node<E> h, p, q;
539 restartFromHead:
540 while ((h = head).item == null && (p = h.prev) != null) {
541 for (;;) {
542 if ((q = p.prev) == null ||
543 (q = (p = q).prev) == null) {
544 // It is possible that p is PREV_TERMINATOR,
545 // but if so, the CAS is guaranteed to fail.
546 if (HEAD.compareAndSet(this, h, p))
547 return;
548 else
549 continue restartFromHead;
550 }
551 else if (h != head)
552 continue restartFromHead;
553 else
554 p = q;
555 }
556 }
557 }
558
559 /**
560 * Guarantees that any node which was unlinked before a call to
561 * this method will be unreachable from tail after it returns.
562 * Does not guarantee to eliminate slack, only that tail will
563 * point to a node that was active while this method was running.
564 */
565 private final void updateTail() {
566 // Either tail already points to an active node, or we keep
567 // trying to cas it to the last node until it does.
568 Node<E> t, p, q;
569 restartFromTail:
570 while ((t = tail).item == null && (p = t.next) != null) {
571 for (;;) {
572 if ((q = p.next) == null ||
573 (q = (p = q).next) == null) {
574 // It is possible that p is NEXT_TERMINATOR,
575 // but if so, the CAS is guaranteed to fail.
576 if (TAIL.compareAndSet(this, t, p))
577 return;
578 else
579 continue restartFromTail;
580 }
581 else if (t != tail)
582 continue restartFromTail;
583 else
584 p = q;
585 }
586 }
587 }
588
589 private void skipDeletedPredecessors(Node<E> x) {
590 whileActive:
591 do {
592 Node<E> prev = x.prev;
593 // assert prev != null;
594 // assert x != NEXT_TERMINATOR;
595 // assert x != PREV_TERMINATOR;
596 Node<E> p = prev;
597 findActive:
598 for (;;) {
599 if (p.item != null)
600 break findActive;
601 Node<E> q = p.prev;
602 if (q == null) {
603 if (p.next == p)
604 continue whileActive;
605 break findActive;
606 }
607 else if (p == q)
608 continue whileActive;
609 else
610 p = q;
611 }
612
613 // found active CAS target
614 if (prev == p || PREV.compareAndSet(x, prev, p))
615 return;
616
617 } while (x.item != null || x.next == null);
618 }
619
620 private void skipDeletedSuccessors(Node<E> x) {
621 whileActive:
622 do {
623 Node<E> next = x.next;
624 // assert next != null;
625 // assert x != NEXT_TERMINATOR;
626 // assert x != PREV_TERMINATOR;
627 Node<E> p = next;
628 findActive:
629 for (;;) {
630 if (p.item != null)
631 break findActive;
632 Node<E> q = p.next;
633 if (q == null) {
634 if (p.prev == p)
635 continue whileActive;
636 break findActive;
637 }
638 else if (p == q)
639 continue whileActive;
640 else
641 p = q;
642 }
643
644 // found active CAS target
645 if (next == p || NEXT.compareAndSet(x, next, p))
646 return;
647
648 } while (x.item != null || x.prev == null);
649 }
650
651 /**
652 * Returns the successor of p, or the first node if p.next has been
653 * linked to self, which will only be true if traversing with a
654 * stale pointer that is now off the list.
655 */
656 final Node<E> succ(Node<E> p) {
657 // TODO: should we skip deleted nodes here?
658 if (p == (p = p.next))
659 p = first();
660 return p;
661 }
662
663 /**
664 * Returns the predecessor of p, or the last node if p.prev has been
665 * linked to self, which will only be true if traversing with a
666 * stale pointer that is now off the list.
667 */
668 final Node<E> pred(Node<E> p) {
669 if (p == (p = p.prev))
670 p = last();
671 return p;
672 }
673
674 /**
675 * Returns the first node, the unique node p for which:
676 * p.prev == null && p.next != p
677 * The returned node may or may not be logically deleted.
678 * Guarantees that head is set to the returned node.
679 */
680 Node<E> first() {
681 restartFromHead:
682 for (;;)
683 for (Node<E> h = head, p = h, q;;) {
684 if ((q = p.prev) != null &&
685 (q = (p = q).prev) != null)
686 // Check for head updates every other hop.
687 // If p == q, we are sure to follow head instead.
688 p = (h != (h = head)) ? h : q;
689 else if (p == h
690 // It is possible that p is PREV_TERMINATOR,
691 // but if so, the CAS is guaranteed to fail.
692 || HEAD.compareAndSet(this, h, p))
693 return p;
694 else
695 continue restartFromHead;
696 }
697 }
698
699 /**
700 * Returns the last node, the unique node p for which:
701 * p.next == null && p.prev != p
702 * The returned node may or may not be logically deleted.
703 * Guarantees that tail is set to the returned node.
704 */
705 Node<E> last() {
706 restartFromTail:
707 for (;;)
708 for (Node<E> t = tail, p = t, q;;) {
709 if ((q = p.next) != null &&
710 (q = (p = q).next) != null)
711 // Check for tail updates every other hop.
712 // If p == q, we are sure to follow tail instead.
713 p = (t != (t = tail)) ? t : q;
714 else if (p == t
715 // It is possible that p is NEXT_TERMINATOR,
716 // but if so, the CAS is guaranteed to fail.
717 || TAIL.compareAndSet(this, t, p))
718 return p;
719 else
720 continue restartFromTail;
721 }
722 }
723
724 // Minor convenience utilities
725
726 /**
727 * Returns element unless it is null, in which case throws
728 * NoSuchElementException.
729 *
730 * @param v the element
731 * @return the element
732 */
733 private E screenNullResult(E v) {
734 if (v == null)
735 throw new NoSuchElementException();
736 return v;
737 }
738
739 /**
740 * Constructs an empty deque.
741 */
742 public ConcurrentLinkedDeque() {
743 head = tail = new Node<E>();
744 }
745
746 /**
747 * Constructs a deque initially containing the elements of
748 * the given collection, added in traversal order of the
749 * collection's iterator.
750 *
751 * @param c the collection of elements to initially contain
752 * @throws NullPointerException if the specified collection or any
753 * of its elements are null
754 */
755 public ConcurrentLinkedDeque(Collection<? extends E> c) {
756 // Copy c into a private chain of Nodes
757 Node<E> h = null, t = null;
758 for (E e : c) {
759 Node<E> newNode = newNode(Objects.requireNonNull(e));
760 if (h == null)
761 h = t = newNode;
762 else {
763 NEXT.set(t, newNode);
764 PREV.set(newNode, t);
765 t = newNode;
766 }
767 }
768 initHeadTail(h, t);
769 }
770
771 /**
772 * Initializes head and tail, ensuring invariants hold.
773 */
774 private void initHeadTail(Node<E> h, Node<E> t) {
775 if (h == t) {
776 if (h == null)
777 h = t = new Node<E>();
778 else {
779 // Avoid edge case of a single Node with non-null item.
780 Node<E> newNode = new Node<E>();
781 NEXT.set(t, newNode);
782 PREV.set(newNode, t);
783 t = newNode;
784 }
785 }
786 head = h;
787 tail = t;
788 }
789
790 /**
791 * Inserts the specified element at the front of this deque.
792 * As the deque is unbounded, this method will never throw
793 * {@link IllegalStateException}.
794 *
795 * @throws NullPointerException if the specified element is null
796 */
797 public void addFirst(E e) {
798 linkFirst(e);
799 }
800
801 /**
802 * Inserts the specified element at the end of this deque.
803 * As the deque is unbounded, this method will never throw
804 * {@link IllegalStateException}.
805 *
806 * <p>This method is equivalent to {@link #add}.
807 *
808 * @throws NullPointerException if the specified element is null
809 */
810 public void addLast(E e) {
811 linkLast(e);
812 }
813
814 /**
815 * Inserts the specified element at the front of this deque.
816 * As the deque is unbounded, this method will never return {@code false}.
817 *
818 * @return {@code true} (as specified by {@link Deque#offerFirst})
819 * @throws NullPointerException if the specified element is null
820 */
821 public boolean offerFirst(E e) {
822 linkFirst(e);
823 return true;
824 }
825
826 /**
827 * Inserts the specified element at the end of this deque.
828 * As the deque is unbounded, this method will never return {@code false}.
829 *
830 * <p>This method is equivalent to {@link #add}.
831 *
832 * @return {@code true} (as specified by {@link Deque#offerLast})
833 * @throws NullPointerException if the specified element is null
834 */
835 public boolean offerLast(E e) {
836 linkLast(e);
837 return true;
838 }
839
840 public E peekFirst() {
841 restart: for (;;) {
842 E item;
843 Node<E> first = first(), p = first;
844 while ((item = p.item) == null) {
845 if (p == (p = p.next)) continue restart;
846 if (p == null)
847 break;
848 }
849 // recheck for linearizability
850 if (first.prev != null) continue restart;
851 return item;
852 }
853 }
854
855 public E peekLast() {
856 restart: for (;;) {
857 E item;
858 Node<E> last = last(), p = last;
859 while ((item = p.item) == null) {
860 if (p == (p = p.prev)) continue restart;
861 if (p == null)
862 break;
863 }
864 // recheck for linearizability
865 if (last.next != null) continue restart;
866 return item;
867 }
868 }
869
870 /**
871 * @throws NoSuchElementException {@inheritDoc}
872 */
873 public E getFirst() {
874 return screenNullResult(peekFirst());
875 }
876
877 /**
878 * @throws NoSuchElementException {@inheritDoc}
879 */
880 public E getLast() {
881 return screenNullResult(peekLast());
882 }
883
884 public E pollFirst() {
885 restart: for (;;) {
886 for (Node<E> first = first(), p = first;;) {
887 final E item;
888 if ((item = p.item) != null) {
889 // recheck for linearizability
890 if (first.prev != null) continue restart;
891 if (ITEM.compareAndSet(p, item, null)) {
892 unlink(p);
893 return item;
894 }
895 }
896 if (p == (p = p.next)) continue restart;
897 if (p == null) {
898 if (first.prev != null) continue restart;
899 return null;
900 }
901 }
902 }
903 }
904
905 public E pollLast() {
906 restart: for (;;) {
907 for (Node<E> last = last(), p = last;;) {
908 final E item;
909 if ((item = p.item) != null) {
910 // recheck for linearizability
911 if (last.next != null) continue restart;
912 if (ITEM.compareAndSet(p, item, null)) {
913 unlink(p);
914 return item;
915 }
916 }
917 if (p == (p = p.prev)) continue restart;
918 if (p == null) {
919 if (last.next != null) continue restart;
920 return null;
921 }
922 }
923 }
924 }
925
926 /**
927 * @throws NoSuchElementException {@inheritDoc}
928 */
929 public E removeFirst() {
930 return screenNullResult(pollFirst());
931 }
932
933 /**
934 * @throws NoSuchElementException {@inheritDoc}
935 */
936 public E removeLast() {
937 return screenNullResult(pollLast());
938 }
939
940 // *** Queue and stack methods ***
941
942 /**
943 * Inserts the specified element at the tail of this deque.
944 * As the deque is unbounded, this method will never return {@code false}.
945 *
946 * @return {@code true} (as specified by {@link Queue#offer})
947 * @throws NullPointerException if the specified element is null
948 */
949 public boolean offer(E e) {
950 return offerLast(e);
951 }
952
953 /**
954 * Inserts the specified element at the tail of this deque.
955 * As the deque is unbounded, this method will never throw
956 * {@link IllegalStateException} or return {@code false}.
957 *
958 * @return {@code true} (as specified by {@link Collection#add})
959 * @throws NullPointerException if the specified element is null
960 */
961 public boolean add(E e) {
962 return offerLast(e);
963 }
964
965 public E poll() { return pollFirst(); }
966 public E peek() { return peekFirst(); }
967
968 /**
969 * @throws NoSuchElementException {@inheritDoc}
970 */
971 public E remove() { return removeFirst(); }
972
973 /**
974 * @throws NoSuchElementException {@inheritDoc}
975 */
976 public E pop() { return removeFirst(); }
977
978 /**
979 * @throws NoSuchElementException {@inheritDoc}
980 */
981 public E element() { return getFirst(); }
982
983 /**
984 * @throws NullPointerException {@inheritDoc}
985 */
986 public void push(E e) { addFirst(e); }
987
988 /**
989 * Removes the first occurrence of the specified element from this deque.
990 * If the deque does not contain the element, it is unchanged.
991 * More formally, removes the first element {@code e} such that
992 * {@code o.equals(e)} (if such an element exists).
993 * Returns {@code true} if this deque contained the specified element
994 * (or equivalently, if this deque changed as a result of the call).
995 *
996 * @param o element to be removed from this deque, if present
997 * @return {@code true} if the deque contained the specified element
998 * @throws NullPointerException if the specified element is null
999 */
1000 public boolean removeFirstOccurrence(Object o) {
1001 Objects.requireNonNull(o);
1002 for (Node<E> p = first(); p != null; p = succ(p)) {
1003 final E item;
1004 if ((item = p.item) != null
1005 && o.equals(item)
1006 && ITEM.compareAndSet(p, item, null)) {
1007 unlink(p);
1008 return true;
1009 }
1010 }
1011 return false;
1012 }
1013
1014 /**
1015 * Removes the last occurrence of the specified element from this deque.
1016 * If the deque does not contain the element, it is unchanged.
1017 * More formally, removes the last element {@code e} such that
1018 * {@code o.equals(e)} (if such an element exists).
1019 * Returns {@code true} if this deque contained the specified element
1020 * (or equivalently, if this deque changed as a result of the call).
1021 *
1022 * @param o element to be removed from this deque, if present
1023 * @return {@code true} if the deque contained the specified element
1024 * @throws NullPointerException if the specified element is null
1025 */
1026 public boolean removeLastOccurrence(Object o) {
1027 Objects.requireNonNull(o);
1028 for (Node<E> p = last(); p != null; p = pred(p)) {
1029 final E item;
1030 if ((item = p.item) != null
1031 && o.equals(item)
1032 && ITEM.compareAndSet(p, item, null)) {
1033 unlink(p);
1034 return true;
1035 }
1036 }
1037 return false;
1038 }
1039
1040 /**
1041 * Returns {@code true} if this deque contains the specified element.
1042 * More formally, returns {@code true} if and only if this deque contains
1043 * at least one element {@code e} such that {@code o.equals(e)}.
1044 *
1045 * @param o element whose presence in this deque is to be tested
1046 * @return {@code true} if this deque contains the specified element
1047 */
1048 public boolean contains(Object o) {
1049 if (o != null) {
1050 for (Node<E> p = first(); p != null; p = succ(p)) {
1051 final E item;
1052 if ((item = p.item) != null && o.equals(item))
1053 return true;
1054 }
1055 }
1056 return false;
1057 }
1058
1059 /**
1060 * Returns {@code true} if this collection contains no elements.
1061 *
1062 * @return {@code true} if this collection contains no elements
1063 */
1064 public boolean isEmpty() {
1065 return peekFirst() == null;
1066 }
1067
1068 /**
1069 * Returns the number of elements in this deque. If this deque
1070 * contains more than {@code Integer.MAX_VALUE} elements, it
1071 * returns {@code Integer.MAX_VALUE}.
1072 *
1073 * <p>Beware that, unlike in most collections, this method is
1074 * <em>NOT</em> a constant-time operation. Because of the
1075 * asynchronous nature of these deques, determining the current
1076 * number of elements requires traversing them all to count them.
1077 * Additionally, it is possible for the size to change during
1078 * execution of this method, in which case the returned result
1079 * will be inaccurate. Thus, this method is typically not very
1080 * useful in concurrent applications.
1081 *
1082 * @return the number of elements in this deque
1083 */
1084 public int size() {
1085 restart: for (;;) {
1086 int count = 0;
1087 for (Node<E> p = first(); p != null;) {
1088 if (p.item != null)
1089 if (++count == Integer.MAX_VALUE)
1090 break; // @see Collection.size()
1091 if (p == (p = p.next))
1092 continue restart;
1093 }
1094 return count;
1095 }
1096 }
1097
1098 /**
1099 * Removes the first occurrence of the specified element from this deque.
1100 * If the deque does not contain the element, it is unchanged.
1101 * More formally, removes the first element {@code e} such that
1102 * {@code o.equals(e)} (if such an element exists).
1103 * Returns {@code true} if this deque contained the specified element
1104 * (or equivalently, if this deque changed as a result of the call).
1105 *
1106 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1107 *
1108 * @param o element to be removed from this deque, if present
1109 * @return {@code true} if the deque contained the specified element
1110 * @throws NullPointerException if the specified element is null
1111 */
1112 public boolean remove(Object o) {
1113 return removeFirstOccurrence(o);
1114 }
1115
1116 /**
1117 * Appends all of the elements in the specified collection to the end of
1118 * this deque, in the order that they are returned by the specified
1119 * collection's iterator. Attempts to {@code addAll} of a deque to
1120 * itself result in {@code IllegalArgumentException}.
1121 *
1122 * @param c the elements to be inserted into this deque
1123 * @return {@code true} if this deque changed as a result of the call
1124 * @throws NullPointerException if the specified collection or any
1125 * of its elements are null
1126 * @throws IllegalArgumentException if the collection is this deque
1127 */
1128 public boolean addAll(Collection<? extends E> c) {
1129 if (c == this)
1130 // As historically specified in AbstractQueue#addAll
1131 throw new IllegalArgumentException();
1132
1133 // Copy c into a private chain of Nodes
1134 Node<E> beginningOfTheEnd = null, last = null;
1135 for (E e : c) {
1136 Node<E> newNode = newNode(Objects.requireNonNull(e));
1137 if (beginningOfTheEnd == null)
1138 beginningOfTheEnd = last = newNode;
1139 else {
1140 NEXT.set(last, newNode);
1141 PREV.set(newNode, last);
1142 last = newNode;
1143 }
1144 }
1145 if (beginningOfTheEnd == null)
1146 return false;
1147
1148 // Atomically append the chain at the tail of this collection
1149 restartFromTail:
1150 for (;;)
1151 for (Node<E> t = tail, p = t, q;;) {
1152 if ((q = p.next) != null &&
1153 (q = (p = q).next) != null)
1154 // Check for tail updates every other hop.
1155 // If p == q, we are sure to follow tail instead.
1156 p = (t != (t = tail)) ? t : q;
1157 else if (p.prev == p) // NEXT_TERMINATOR
1158 continue restartFromTail;
1159 else {
1160 // p is last node
1161 PREV.set(beginningOfTheEnd, p); // CAS piggyback
1162 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
1163 // Successful CAS is the linearization point
1164 // for all elements to be added to this deque.
1165 if (!TAIL.weakCompareAndSet(this, t, last)) {
1166 // Try a little harder to update tail,
1167 // since we may be adding many elements.
1168 t = tail;
1169 if (last.next == null)
1170 TAIL.weakCompareAndSet(this, t, last);
1171 }
1172 return true;
1173 }
1174 // Lost CAS race to another thread; re-read next
1175 }
1176 }
1177 }
1178
1179 /**
1180 * Removes all of the elements from this deque.
1181 */
1182 public void clear() {
1183 while (pollFirst() != null)
1184 ;
1185 }
1186
1187 public String toString() {
1188 String[] a = null;
1189 restart: for (;;) {
1190 int charLength = 0;
1191 int size = 0;
1192 for (Node<E> p = first(); p != null;) {
1193 final E item;
1194 if ((item = p.item) != null) {
1195 if (a == null)
1196 a = new String[4];
1197 else if (size == a.length)
1198 a = Arrays.copyOf(a, 2 * size);
1199 String s = item.toString();
1200 a[size++] = s;
1201 charLength += s.length();
1202 }
1203 if (p == (p = p.next))
1204 continue restart;
1205 }
1206
1207 if (size == 0)
1208 return "[]";
1209
1210 return Helpers.toString(a, size, charLength);
1211 }
1212 }
1213
1214 private Object[] toArrayInternal(Object[] a) {
1215 Object[] x = a;
1216 restart: for (;;) {
1217 int size = 0;
1218 for (Node<E> p = first(); p != null;) {
1219 final E item;
1220 if ((item = p.item) != null) {
1221 if (x == null)
1222 x = new Object[4];
1223 else if (size == x.length)
1224 x = Arrays.copyOf(x, 2 * (size + 4));
1225 x[size++] = item;
1226 }
1227 if (p == (p = p.next))
1228 continue restart;
1229 }
1230 if (x == null)
1231 return new Object[0];
1232 else if (a != null && size <= a.length) {
1233 if (a != x)
1234 System.arraycopy(x, 0, a, 0, size);
1235 if (size < a.length)
1236 a[size] = null;
1237 return a;
1238 }
1239 return (size == x.length) ? x : Arrays.copyOf(x, size);
1240 }
1241 }
1242
1243 /**
1244 * Returns an array containing all of the elements in this deque, in
1245 * proper sequence (from first to last element).
1246 *
1247 * <p>The returned array will be "safe" in that no references to it are
1248 * maintained by this deque. (In other words, this method must allocate
1249 * a new array). The caller is thus free to modify the returned array.
1250 *
1251 * <p>This method acts as bridge between array-based and collection-based
1252 * APIs.
1253 *
1254 * @return an array containing all of the elements in this deque
1255 */
1256 public Object[] toArray() {
1257 return toArrayInternal(null);
1258 }
1259
1260 /**
1261 * Returns an array containing all of the elements in this deque,
1262 * in proper sequence (from first to last element); the runtime
1263 * type of the returned array is that of the specified array. If
1264 * the deque fits in the specified array, it is returned therein.
1265 * Otherwise, a new array is allocated with the runtime type of
1266 * the specified array and the size of this deque.
1267 *
1268 * <p>If this deque fits in the specified array with room to spare
1269 * (i.e., the array has more elements than this deque), the element in
1270 * the array immediately following the end of the deque is set to
1271 * {@code null}.
1272 *
1273 * <p>Like the {@link #toArray()} method, this method acts as
1274 * bridge between array-based and collection-based APIs. Further,
1275 * this method allows precise control over the runtime type of the
1276 * output array, and may, under certain circumstances, be used to
1277 * save allocation costs.
1278 *
1279 * <p>Suppose {@code x} is a deque known to contain only strings.
1280 * The following code can be used to dump the deque into a newly
1281 * allocated array of {@code String}:
1282 *
1283 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1284 *
1285 * Note that {@code toArray(new Object[0])} is identical in function to
1286 * {@code toArray()}.
1287 *
1288 * @param a the array into which the elements of the deque are to
1289 * be stored, if it is big enough; otherwise, a new array of the
1290 * same runtime type is allocated for this purpose
1291 * @return an array containing all of the elements in this deque
1292 * @throws ArrayStoreException if the runtime type of the specified array
1293 * is not a supertype of the runtime type of every element in
1294 * this deque
1295 * @throws NullPointerException if the specified array is null
1296 */
1297 @SuppressWarnings("unchecked")
1298 public <T> T[] toArray(T[] a) {
1299 if (a == null) throw new NullPointerException();
1300 return (T[]) toArrayInternal(a);
1301 }
1302
1303 /**
1304 * Returns an iterator over the elements in this deque in proper sequence.
1305 * The elements will be returned in order from first (head) to last (tail).
1306 *
1307 * <p>The returned iterator is
1308 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1309 *
1310 * @return an iterator over the elements in this deque in proper sequence
1311 */
1312 public Iterator<E> iterator() {
1313 return new Itr();
1314 }
1315
1316 /**
1317 * Returns an iterator over the elements in this deque in reverse
1318 * sequential order. The elements will be returned in order from
1319 * last (tail) to first (head).
1320 *
1321 * <p>The returned iterator is
1322 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1323 *
1324 * @return an iterator over the elements in this deque in reverse order
1325 */
1326 public Iterator<E> descendingIterator() {
1327 return new DescendingItr();
1328 }
1329
1330 private abstract class AbstractItr implements Iterator<E> {
1331 /**
1332 * Next node to return item for.
1333 */
1334 private Node<E> nextNode;
1335
1336 /**
1337 * nextItem holds on to item fields because once we claim
1338 * that an element exists in hasNext(), we must return it in
1339 * the following next() call even if it was in the process of
1340 * being removed when hasNext() was called.
1341 */
1342 private E nextItem;
1343
1344 /**
1345 * Node returned by most recent call to next. Needed by remove.
1346 * Reset to null if this element is deleted by a call to remove.
1347 */
1348 private Node<E> lastRet;
1349
1350 abstract Node<E> startNode();
1351 abstract Node<E> nextNode(Node<E> p);
1352
1353 AbstractItr() {
1354 advance();
1355 }
1356
1357 /**
1358 * Sets nextNode and nextItem to next valid node, or to null
1359 * if no such.
1360 */
1361 private void advance() {
1362 lastRet = nextNode;
1363
1364 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1365 for (;; p = nextNode(p)) {
1366 if (p == null) {
1367 // might be at active end or TERMINATOR node; both are OK
1368 nextNode = null;
1369 nextItem = null;
1370 break;
1371 }
1372 final E item;
1373 if ((item = p.item) != null) {
1374 nextNode = p;
1375 nextItem = item;
1376 break;
1377 }
1378 }
1379 }
1380
1381 public boolean hasNext() {
1382 return nextItem != null;
1383 }
1384
1385 public E next() {
1386 E item = nextItem;
1387 if (item == null) throw new NoSuchElementException();
1388 advance();
1389 return item;
1390 }
1391
1392 public void remove() {
1393 Node<E> l = lastRet;
1394 if (l == null) throw new IllegalStateException();
1395 l.item = null;
1396 unlink(l);
1397 lastRet = null;
1398 }
1399 }
1400
1401 /** Forward iterator */
1402 private class Itr extends AbstractItr {
1403 Itr() {} // prevent access constructor creation
1404 Node<E> startNode() { return first(); }
1405 Node<E> nextNode(Node<E> p) { return succ(p); }
1406 }
1407
1408 /** Descending iterator */
1409 private class DescendingItr extends AbstractItr {
1410 DescendingItr() {} // prevent access constructor creation
1411 Node<E> startNode() { return last(); }
1412 Node<E> nextNode(Node<E> p) { return pred(p); }
1413 }
1414
1415 /** A customized variant of Spliterators.IteratorSpliterator */
1416 final class CLDSpliterator implements Spliterator<E> {
1417 static final int MAX_BATCH = 1 << 25; // max batch array size;
1418 Node<E> current; // current node; null until initialized
1419 int batch; // batch size for splits
1420 boolean exhausted; // true when no more nodes
1421
1422 public Spliterator<E> trySplit() {
1423 Node<E> p, q;
1424 if ((p = current()) == null || (q = p.next) == null)
1425 return null;
1426 int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
1427 Object[] a = null;
1428 do {
1429 final E e;
1430 if ((e = p.item) != null) {
1431 if (a == null)
1432 a = new Object[n];
1433 a[i++] = e;
1434 }
1435 if (p == (p = q))
1436 p = first();
1437 } while (p != null && (q = p.next) != null && i < n);
1438 setCurrent(p);
1439 return (i == 0) ? null :
1440 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
1441 Spliterator.NONNULL |
1442 Spliterator.CONCURRENT));
1443 }
1444
1445 public void forEachRemaining(Consumer<? super E> action) {
1446 Objects.requireNonNull(action);
1447 Node<E> p;
1448 if ((p = current()) != null) {
1449 current = null;
1450 exhausted = true;
1451 do {
1452 final E e;
1453 if ((e = p.item) != null)
1454 action.accept(e);
1455 if (p == (p = p.next))
1456 p = first();
1457 } while (p != null);
1458 }
1459 }
1460
1461 public boolean tryAdvance(Consumer<? super E> action) {
1462 Objects.requireNonNull(action);
1463 Node<E> p;
1464 if ((p = current()) != null) {
1465 E e;
1466 do {
1467 e = p.item;
1468 if (p == (p = p.next))
1469 p = first();
1470 } while (e == null && p != null);
1471 setCurrent(p);
1472 if (e != null) {
1473 action.accept(e);
1474 return true;
1475 }
1476 }
1477 return false;
1478 }
1479
1480 private void setCurrent(Node<E> p) {
1481 if ((current = p) == null)
1482 exhausted = true;
1483 }
1484
1485 private Node<E> current() {
1486 Node<E> p;
1487 if ((p = current) == null && !exhausted)
1488 setCurrent(p = first());
1489 return p;
1490 }
1491
1492 public long estimateSize() { return Long.MAX_VALUE; }
1493
1494 public int characteristics() {
1495 return (Spliterator.ORDERED |
1496 Spliterator.NONNULL |
1497 Spliterator.CONCURRENT);
1498 }
1499 }
1500
1501 /**
1502 * Returns a {@link Spliterator} over the elements in this deque.
1503 *
1504 * <p>The returned spliterator is
1505 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1506 *
1507 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1508 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1509 *
1510 * @implNote
1511 * The {@code Spliterator} implements {@code trySplit} to permit limited
1512 * parallelism.
1513 *
1514 * @return a {@code Spliterator} over the elements in this deque
1515 * @since 1.8
1516 */
1517 public Spliterator<E> spliterator() {
1518 return new CLDSpliterator();
1519 }
1520
1521 /**
1522 * Saves this deque to a stream (that is, serializes it).
1523 *
1524 * @param s the stream
1525 * @throws java.io.IOException if an I/O error occurs
1526 * @serialData All of the elements (each an {@code E}) in
1527 * the proper order, followed by a null
1528 */
1529 private void writeObject(java.io.ObjectOutputStream s)
1530 throws java.io.IOException {
1531
1532 // Write out any hidden stuff
1533 s.defaultWriteObject();
1534
1535 // Write out all elements in the proper order.
1536 for (Node<E> p = first(); p != null; p = succ(p)) {
1537 final E item;
1538 if ((item = p.item) != null)
1539 s.writeObject(item);
1540 }
1541
1542 // Use trailing null as sentinel
1543 s.writeObject(null);
1544 }
1545
1546 /**
1547 * Reconstitutes this deque from a stream (that is, deserializes it).
1548 * @param s the stream
1549 * @throws ClassNotFoundException if the class of a serialized object
1550 * could not be found
1551 * @throws java.io.IOException if an I/O error occurs
1552 */
1553 private void readObject(java.io.ObjectInputStream s)
1554 throws java.io.IOException, ClassNotFoundException {
1555 s.defaultReadObject();
1556
1557 // Read in elements until trailing null sentinel found
1558 Node<E> h = null, t = null;
1559 for (Object item; (item = s.readObject()) != null; ) {
1560 @SuppressWarnings("unchecked")
1561 Node<E> newNode = newNode((E) item);
1562 if (h == null)
1563 h = t = newNode;
1564 else {
1565 NEXT.set(t, newNode);
1566 PREV.set(newNode, t);
1567 t = newNode;
1568 }
1569 }
1570 initHeadTail(h, t);
1571 }
1572
1573 /**
1574 * @throws NullPointerException {@inheritDoc}
1575 */
1576 public boolean removeIf(Predicate<? super E> filter) {
1577 Objects.requireNonNull(filter);
1578 return bulkRemove(filter);
1579 }
1580
1581 /**
1582 * @throws NullPointerException {@inheritDoc}
1583 */
1584 public boolean removeAll(Collection<?> c) {
1585 Objects.requireNonNull(c);
1586 return bulkRemove(e -> c.contains(e));
1587 }
1588
1589 /**
1590 * @throws NullPointerException {@inheritDoc}
1591 */
1592 public boolean retainAll(Collection<?> c) {
1593 Objects.requireNonNull(c);
1594 return bulkRemove(e -> !c.contains(e));
1595 }
1596
1597 /** Implementation of bulk remove methods. */
1598 private boolean bulkRemove(Predicate<? super E> filter) {
1599 boolean removed = false;
1600 for (Node<E> p = first(), succ; p != null; p = succ) {
1601 succ = succ(p);
1602 final E item;
1603 if ((item = p.item) != null
1604 && filter.test(item)
1605 && ITEM.compareAndSet(p, item, null)) {
1606 unlink(p);
1607 removed = true;
1608 }
1609 }
1610 return removed;
1611 }
1612
1613 /**
1614 * @throws NullPointerException {@inheritDoc}
1615 */
1616 public void forEach(Consumer<? super E> action) {
1617 Objects.requireNonNull(action);
1618 E item;
1619 for (Node<E> p = first(); p != null; p = succ(p))
1620 if ((item = p.item) != null)
1621 action.accept(item);
1622 }
1623
1624 // VarHandle mechanics
1625 private static final VarHandle HEAD;
1626 private static final VarHandle TAIL;
1627 private static final VarHandle PREV;
1628 private static final VarHandle NEXT;
1629 private static final VarHandle ITEM;
1630 static {
1631 PREV_TERMINATOR = new Node<Object>();
1632 PREV_TERMINATOR.next = PREV_TERMINATOR;
1633 NEXT_TERMINATOR = new Node<Object>();
1634 NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1635 try {
1636 MethodHandles.Lookup l = MethodHandles.lookup();
1637 HEAD = l.findVarHandle(ConcurrentLinkedDeque.class, "head",
1638 Node.class);
1639 TAIL = l.findVarHandle(ConcurrentLinkedDeque.class, "tail",
1640 Node.class);
1641 PREV = l.findVarHandle(Node.class, "prev", Node.class);
1642 NEXT = l.findVarHandle(Node.class, "next", Node.class);
1643 ITEM = l.findVarHandle(Node.class, "item", Object.class);
1644 } catch (ReflectiveOperationException e) {
1645 throw new ExceptionInInitializerError(e);
1646 }
1647 }
1648 }