ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.80
Committed: Tue Dec 20 22:37:31 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.79: +2 -0 lines
Log Message:
prevent access constructor tag anonymous class creation

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