ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.77
Committed: Mon Dec 5 03:02:49 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.76: +57 -6 lines
Log Message:
implement forEach removeIf removeAll retainAll

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 E item = p.item;
840 if (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 E item = p.item;
849 if (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 E item = p.item;
872 if (item != null && ITEM.compareAndSet(p, item, null)) {
873 unlink(p);
874 return item;
875 }
876 }
877 return null;
878 }
879
880 public E pollLast() {
881 for (Node<E> p = last(); p != null; p = pred(p)) {
882 E item = p.item;
883 if (item != null && ITEM.compareAndSet(p, item, null)) {
884 unlink(p);
885 return item;
886 }
887 }
888 return null;
889 }
890
891 /**
892 * @throws NoSuchElementException {@inheritDoc}
893 */
894 public E removeFirst() {
895 return screenNullResult(pollFirst());
896 }
897
898 /**
899 * @throws NoSuchElementException {@inheritDoc}
900 */
901 public E removeLast() {
902 return screenNullResult(pollLast());
903 }
904
905 // *** Queue and stack methods ***
906
907 /**
908 * Inserts the specified element at the tail of this deque.
909 * As the deque is unbounded, this method will never return {@code false}.
910 *
911 * @return {@code true} (as specified by {@link Queue#offer})
912 * @throws NullPointerException if the specified element is null
913 */
914 public boolean offer(E e) {
915 return offerLast(e);
916 }
917
918 /**
919 * Inserts the specified element at the tail of this deque.
920 * As the deque is unbounded, this method will never throw
921 * {@link IllegalStateException} or return {@code false}.
922 *
923 * @return {@code true} (as specified by {@link Collection#add})
924 * @throws NullPointerException if the specified element is null
925 */
926 public boolean add(E e) {
927 return offerLast(e);
928 }
929
930 public E poll() { return pollFirst(); }
931 public E peek() { return peekFirst(); }
932
933 /**
934 * @throws NoSuchElementException {@inheritDoc}
935 */
936 public E remove() { return removeFirst(); }
937
938 /**
939 * @throws NoSuchElementException {@inheritDoc}
940 */
941 public E pop() { return removeFirst(); }
942
943 /**
944 * @throws NoSuchElementException {@inheritDoc}
945 */
946 public E element() { return getFirst(); }
947
948 /**
949 * @throws NullPointerException {@inheritDoc}
950 */
951 public void push(E e) { addFirst(e); }
952
953 /**
954 * Removes the first occurrence of the specified element from this deque.
955 * If the deque does not contain the element, it is unchanged.
956 * More formally, removes the first element {@code e} such that
957 * {@code o.equals(e)} (if such an element exists).
958 * Returns {@code true} if this deque contained the specified element
959 * (or equivalently, if this deque changed as a result of the call).
960 *
961 * @param o element to be removed from this deque, if present
962 * @return {@code true} if the deque contained the specified element
963 * @throws NullPointerException if the specified element is null
964 */
965 public boolean removeFirstOccurrence(Object o) {
966 Objects.requireNonNull(o);
967 for (Node<E> p = first(); p != null; p = succ(p)) {
968 final E item;
969 if ((item = p.item) != null
970 && o.equals(item)
971 && ITEM.compareAndSet(p, item, null)) {
972 unlink(p);
973 return true;
974 }
975 }
976 return false;
977 }
978
979 /**
980 * Removes the last occurrence of the specified element from this deque.
981 * If the deque does not contain the element, it is unchanged.
982 * More formally, removes the last element {@code e} such that
983 * {@code o.equals(e)} (if such an element exists).
984 * Returns {@code true} if this deque contained the specified element
985 * (or equivalently, if this deque changed as a result of the call).
986 *
987 * @param o element to be removed from this deque, if present
988 * @return {@code true} if the deque contained the specified element
989 * @throws NullPointerException if the specified element is null
990 */
991 public boolean removeLastOccurrence(Object o) {
992 Objects.requireNonNull(o);
993 for (Node<E> p = last(); p != null; p = pred(p)) {
994 final E item;
995 if ((item = p.item) != null
996 && o.equals(item)
997 && ITEM.compareAndSet(p, item, null)) {
998 unlink(p);
999 return true;
1000 }
1001 }
1002 return false;
1003 }
1004
1005 /**
1006 * Returns {@code true} if this deque contains the specified element.
1007 * More formally, returns {@code true} if and only if this deque contains
1008 * at least one element {@code e} such that {@code o.equals(e)}.
1009 *
1010 * @param o element whose presence in this deque is to be tested
1011 * @return {@code true} if this deque contains the specified element
1012 */
1013 public boolean contains(Object o) {
1014 if (o != null) {
1015 for (Node<E> p = first(); p != null; p = succ(p)) {
1016 E item = p.item;
1017 if (item != null && o.equals(item))
1018 return true;
1019 }
1020 }
1021 return false;
1022 }
1023
1024 /**
1025 * Returns {@code true} if this collection contains no elements.
1026 *
1027 * @return {@code true} if this collection contains no elements
1028 */
1029 public boolean isEmpty() {
1030 return peekFirst() == null;
1031 }
1032
1033 /**
1034 * Returns the number of elements in this deque. If this deque
1035 * contains more than {@code Integer.MAX_VALUE} elements, it
1036 * returns {@code Integer.MAX_VALUE}.
1037 *
1038 * <p>Beware that, unlike in most collections, this method is
1039 * <em>NOT</em> a constant-time operation. Because of the
1040 * asynchronous nature of these deques, determining the current
1041 * number of elements requires traversing them all to count them.
1042 * Additionally, it is possible for the size to change during
1043 * execution of this method, in which case the returned result
1044 * will be inaccurate. Thus, this method is typically not very
1045 * useful in concurrent applications.
1046 *
1047 * @return the number of elements in this deque
1048 */
1049 public int size() {
1050 restartFromHead: for (;;) {
1051 int count = 0;
1052 for (Node<E> p = first(); p != null;) {
1053 if (p.item != null)
1054 if (++count == Integer.MAX_VALUE)
1055 break; // @see Collection.size()
1056 if (p == (p = p.next))
1057 continue restartFromHead;
1058 }
1059 return count;
1060 }
1061 }
1062
1063 /**
1064 * Removes the first occurrence of the specified element from this deque.
1065 * If the deque does not contain the element, it is unchanged.
1066 * More formally, removes the first element {@code e} such that
1067 * {@code o.equals(e)} (if such an element exists).
1068 * Returns {@code true} if this deque contained the specified element
1069 * (or equivalently, if this deque changed as a result of the call).
1070 *
1071 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1072 *
1073 * @param o element to be removed from this deque, if present
1074 * @return {@code true} if the deque contained the specified element
1075 * @throws NullPointerException if the specified element is null
1076 */
1077 public boolean remove(Object o) {
1078 return removeFirstOccurrence(o);
1079 }
1080
1081 /**
1082 * Appends all of the elements in the specified collection to the end of
1083 * this deque, in the order that they are returned by the specified
1084 * collection's iterator. Attempts to {@code addAll} of a deque to
1085 * itself result in {@code IllegalArgumentException}.
1086 *
1087 * @param c the elements to be inserted into this deque
1088 * @return {@code true} if this deque changed as a result of the call
1089 * @throws NullPointerException if the specified collection or any
1090 * of its elements are null
1091 * @throws IllegalArgumentException if the collection is this deque
1092 */
1093 public boolean addAll(Collection<? extends E> c) {
1094 if (c == this)
1095 // As historically specified in AbstractQueue#addAll
1096 throw new IllegalArgumentException();
1097
1098 // Copy c into a private chain of Nodes
1099 Node<E> beginningOfTheEnd = null, last = null;
1100 for (E e : c) {
1101 Node<E> newNode = newNode(Objects.requireNonNull(e));
1102 if (beginningOfTheEnd == null)
1103 beginningOfTheEnd = last = newNode;
1104 else {
1105 NEXT.set(last, newNode);
1106 PREV.set(newNode, last);
1107 last = newNode;
1108 }
1109 }
1110 if (beginningOfTheEnd == null)
1111 return false;
1112
1113 // Atomically append the chain at the tail of this collection
1114 restartFromTail:
1115 for (;;)
1116 for (Node<E> t = tail, p = t, q;;) {
1117 if ((q = p.next) != null &&
1118 (q = (p = q).next) != null)
1119 // Check for tail updates every other hop.
1120 // If p == q, we are sure to follow tail instead.
1121 p = (t != (t = tail)) ? t : q;
1122 else if (p.prev == p) // NEXT_TERMINATOR
1123 continue restartFromTail;
1124 else {
1125 // p is last node
1126 PREV.set(beginningOfTheEnd, p); // CAS piggyback
1127 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
1128 // Successful CAS is the linearization point
1129 // for all elements to be added to this deque.
1130 if (!TAIL.weakCompareAndSet(this, t, last)) {
1131 // Try a little harder to update tail,
1132 // since we may be adding many elements.
1133 t = tail;
1134 if (last.next == null)
1135 TAIL.weakCompareAndSet(this, t, last);
1136 }
1137 return true;
1138 }
1139 // Lost CAS race to another thread; re-read next
1140 }
1141 }
1142 }
1143
1144 /**
1145 * Removes all of the elements from this deque.
1146 */
1147 public void clear() {
1148 while (pollFirst() != null)
1149 ;
1150 }
1151
1152 public String toString() {
1153 String[] a = null;
1154 restartFromHead: for (;;) {
1155 int charLength = 0;
1156 int size = 0;
1157 for (Node<E> p = first(); p != null;) {
1158 E item = p.item;
1159 if (item != null) {
1160 if (a == null)
1161 a = new String[4];
1162 else if (size == a.length)
1163 a = Arrays.copyOf(a, 2 * size);
1164 String s = item.toString();
1165 a[size++] = s;
1166 charLength += s.length();
1167 }
1168 if (p == (p = p.next))
1169 continue restartFromHead;
1170 }
1171
1172 if (size == 0)
1173 return "[]";
1174
1175 return Helpers.toString(a, size, charLength);
1176 }
1177 }
1178
1179 private Object[] toArrayInternal(Object[] a) {
1180 Object[] x = a;
1181 restartFromHead: for (;;) {
1182 int size = 0;
1183 for (Node<E> p = first(); p != null;) {
1184 E item = p.item;
1185 if (item != null) {
1186 if (x == null)
1187 x = new Object[4];
1188 else if (size == x.length)
1189 x = Arrays.copyOf(x, 2 * (size + 4));
1190 x[size++] = item;
1191 }
1192 if (p == (p = p.next))
1193 continue restartFromHead;
1194 }
1195 if (x == null)
1196 return new Object[0];
1197 else if (a != null && size <= a.length) {
1198 if (a != x)
1199 System.arraycopy(x, 0, a, 0, size);
1200 if (size < a.length)
1201 a[size] = null;
1202 return a;
1203 }
1204 return (size == x.length) ? x : Arrays.copyOf(x, size);
1205 }
1206 }
1207
1208 /**
1209 * Returns an array containing all of the elements in this deque, in
1210 * proper sequence (from first to last element).
1211 *
1212 * <p>The returned array will be "safe" in that no references to it are
1213 * maintained by this deque. (In other words, this method must allocate
1214 * a new array). The caller is thus free to modify the returned array.
1215 *
1216 * <p>This method acts as bridge between array-based and collection-based
1217 * APIs.
1218 *
1219 * @return an array containing all of the elements in this deque
1220 */
1221 public Object[] toArray() {
1222 return toArrayInternal(null);
1223 }
1224
1225 /**
1226 * Returns an array containing all of the elements in this deque,
1227 * in proper sequence (from first to last element); the runtime
1228 * type of the returned array is that of the specified array. If
1229 * the deque fits in the specified array, it is returned therein.
1230 * Otherwise, a new array is allocated with the runtime type of
1231 * the specified array and the size of this deque.
1232 *
1233 * <p>If this deque fits in the specified array with room to spare
1234 * (i.e., the array has more elements than this deque), the element in
1235 * the array immediately following the end of the deque is set to
1236 * {@code null}.
1237 *
1238 * <p>Like the {@link #toArray()} method, this method acts as
1239 * bridge between array-based and collection-based APIs. Further,
1240 * this method allows precise control over the runtime type of the
1241 * output array, and may, under certain circumstances, be used to
1242 * save allocation costs.
1243 *
1244 * <p>Suppose {@code x} is a deque known to contain only strings.
1245 * The following code can be used to dump the deque into a newly
1246 * allocated array of {@code String}:
1247 *
1248 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1249 *
1250 * Note that {@code toArray(new Object[0])} is identical in function to
1251 * {@code toArray()}.
1252 *
1253 * @param a the array into which the elements of the deque are to
1254 * be stored, if it is big enough; otherwise, a new array of the
1255 * same runtime type is allocated for this purpose
1256 * @return an array containing all of the elements in this deque
1257 * @throws ArrayStoreException if the runtime type of the specified array
1258 * is not a supertype of the runtime type of every element in
1259 * this deque
1260 * @throws NullPointerException if the specified array is null
1261 */
1262 @SuppressWarnings("unchecked")
1263 public <T> T[] toArray(T[] a) {
1264 if (a == null) throw new NullPointerException();
1265 return (T[]) toArrayInternal(a);
1266 }
1267
1268 /**
1269 * Returns an iterator over the elements in this deque in proper sequence.
1270 * The elements will be returned in order from first (head) to last (tail).
1271 *
1272 * <p>The returned iterator is
1273 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1274 *
1275 * @return an iterator over the elements in this deque in proper sequence
1276 */
1277 public Iterator<E> iterator() {
1278 return new Itr();
1279 }
1280
1281 /**
1282 * Returns an iterator over the elements in this deque in reverse
1283 * sequential order. The elements will be returned in order from
1284 * last (tail) to first (head).
1285 *
1286 * <p>The returned iterator is
1287 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1288 *
1289 * @return an iterator over the elements in this deque in reverse order
1290 */
1291 public Iterator<E> descendingIterator() {
1292 return new DescendingItr();
1293 }
1294
1295 private abstract class AbstractItr implements Iterator<E> {
1296 /**
1297 * Next node to return item for.
1298 */
1299 private Node<E> nextNode;
1300
1301 /**
1302 * nextItem holds on to item fields because once we claim
1303 * that an element exists in hasNext(), we must return it in
1304 * the following next() call even if it was in the process of
1305 * being removed when hasNext() was called.
1306 */
1307 private E nextItem;
1308
1309 /**
1310 * Node returned by most recent call to next. Needed by remove.
1311 * Reset to null if this element is deleted by a call to remove.
1312 */
1313 private Node<E> lastRet;
1314
1315 abstract Node<E> startNode();
1316 abstract Node<E> nextNode(Node<E> p);
1317
1318 AbstractItr() {
1319 advance();
1320 }
1321
1322 /**
1323 * Sets nextNode and nextItem to next valid node, or to null
1324 * if no such.
1325 */
1326 private void advance() {
1327 lastRet = nextNode;
1328
1329 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1330 for (;; p = nextNode(p)) {
1331 if (p == null) {
1332 // might be at active end or TERMINATOR node; both are OK
1333 nextNode = null;
1334 nextItem = null;
1335 break;
1336 }
1337 E item = p.item;
1338 if (item != null) {
1339 nextNode = p;
1340 nextItem = item;
1341 break;
1342 }
1343 }
1344 }
1345
1346 public boolean hasNext() {
1347 return nextItem != null;
1348 }
1349
1350 public E next() {
1351 E item = nextItem;
1352 if (item == null) throw new NoSuchElementException();
1353 advance();
1354 return item;
1355 }
1356
1357 public void remove() {
1358 Node<E> l = lastRet;
1359 if (l == null) throw new IllegalStateException();
1360 l.item = null;
1361 unlink(l);
1362 lastRet = null;
1363 }
1364 }
1365
1366 /** Forward iterator */
1367 private class Itr extends AbstractItr {
1368 Node<E> startNode() { return first(); }
1369 Node<E> nextNode(Node<E> p) { return succ(p); }
1370 }
1371
1372 /** Descending iterator */
1373 private class DescendingItr extends AbstractItr {
1374 Node<E> startNode() { return last(); }
1375 Node<E> nextNode(Node<E> p) { return pred(p); }
1376 }
1377
1378 /** A customized variant of Spliterators.IteratorSpliterator */
1379 final class CLDSpliterator implements Spliterator<E> {
1380 static final int MAX_BATCH = 1 << 25; // max batch array size;
1381 Node<E> current; // current node; null until initialized
1382 int batch; // batch size for splits
1383 boolean exhausted; // true when no more nodes
1384
1385 public Spliterator<E> trySplit() {
1386 Node<E> p;
1387 int b = batch;
1388 int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1389 if (!exhausted &&
1390 ((p = current) != null || (p = first()) != null)) {
1391 if (p.item == null && p == (p = p.next))
1392 current = p = first();
1393 if (p != null && p.next != null) {
1394 Object[] a = new Object[n];
1395 int i = 0;
1396 do {
1397 if ((a[i] = p.item) != null)
1398 ++i;
1399 if (p == (p = p.next))
1400 p = first();
1401 } while (p != null && i < n);
1402 if ((current = p) == null)
1403 exhausted = true;
1404 if (i > 0) {
1405 batch = i;
1406 return Spliterators.spliterator
1407 (a, 0, i, (Spliterator.ORDERED |
1408 Spliterator.NONNULL |
1409 Spliterator.CONCURRENT));
1410 }
1411 }
1412 }
1413 return null;
1414 }
1415
1416 public void forEachRemaining(Consumer<? super E> action) {
1417 Node<E> p;
1418 if (action == null) throw new NullPointerException();
1419 if (!exhausted &&
1420 ((p = current) != null || (p = first()) != null)) {
1421 exhausted = true;
1422 do {
1423 E e = p.item;
1424 if (p == (p = p.next))
1425 p = first();
1426 if (e != null)
1427 action.accept(e);
1428 } while (p != null);
1429 }
1430 }
1431
1432 public boolean tryAdvance(Consumer<? super E> action) {
1433 Node<E> p;
1434 if (action == null) throw new NullPointerException();
1435 if (!exhausted &&
1436 ((p = current) != null || (p = first()) != null)) {
1437 E e;
1438 do {
1439 e = p.item;
1440 if (p == (p = p.next))
1441 p = first();
1442 } while (e == null && p != null);
1443 if ((current = p) == null)
1444 exhausted = true;
1445 if (e != null) {
1446 action.accept(e);
1447 return true;
1448 }
1449 }
1450 return false;
1451 }
1452
1453 public long estimateSize() { return Long.MAX_VALUE; }
1454
1455 public int characteristics() {
1456 return Spliterator.ORDERED | Spliterator.NONNULL |
1457 Spliterator.CONCURRENT;
1458 }
1459 }
1460
1461 /**
1462 * Returns a {@link Spliterator} over the elements in this deque.
1463 *
1464 * <p>The returned spliterator is
1465 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1466 *
1467 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1468 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1469 *
1470 * @implNote
1471 * The {@code Spliterator} implements {@code trySplit} to permit limited
1472 * parallelism.
1473 *
1474 * @return a {@code Spliterator} over the elements in this deque
1475 * @since 1.8
1476 */
1477 public Spliterator<E> spliterator() {
1478 return new CLDSpliterator();
1479 }
1480
1481 /**
1482 * Saves this deque to a stream (that is, serializes it).
1483 *
1484 * @param s the stream
1485 * @throws java.io.IOException if an I/O error occurs
1486 * @serialData All of the elements (each an {@code E}) in
1487 * the proper order, followed by a null
1488 */
1489 private void writeObject(java.io.ObjectOutputStream s)
1490 throws java.io.IOException {
1491
1492 // Write out any hidden stuff
1493 s.defaultWriteObject();
1494
1495 // Write out all elements in the proper order.
1496 for (Node<E> p = first(); p != null; p = succ(p)) {
1497 E item = p.item;
1498 if (item != null)
1499 s.writeObject(item);
1500 }
1501
1502 // Use trailing null as sentinel
1503 s.writeObject(null);
1504 }
1505
1506 /**
1507 * Reconstitutes this deque from a stream (that is, deserializes it).
1508 * @param s the stream
1509 * @throws ClassNotFoundException if the class of a serialized object
1510 * could not be found
1511 * @throws java.io.IOException if an I/O error occurs
1512 */
1513 private void readObject(java.io.ObjectInputStream s)
1514 throws java.io.IOException, ClassNotFoundException {
1515 s.defaultReadObject();
1516
1517 // Read in elements until trailing null sentinel found
1518 Node<E> h = null, t = null;
1519 for (Object item; (item = s.readObject()) != null; ) {
1520 @SuppressWarnings("unchecked")
1521 Node<E> newNode = newNode((E) item);
1522 if (h == null)
1523 h = t = newNode;
1524 else {
1525 NEXT.set(t, newNode);
1526 PREV.set(newNode, t);
1527 t = newNode;
1528 }
1529 }
1530 initHeadTail(h, t);
1531 }
1532
1533 /**
1534 * @throws NullPointerException {@inheritDoc}
1535 */
1536 public boolean removeIf(Predicate<? super E> filter) {
1537 Objects.requireNonNull(filter);
1538 return bulkRemove(filter);
1539 }
1540
1541 /**
1542 * @throws NullPointerException {@inheritDoc}
1543 */
1544 public boolean removeAll(Collection<?> c) {
1545 Objects.requireNonNull(c);
1546 return bulkRemove(e -> c.contains(e));
1547 }
1548
1549 /**
1550 * @throws NullPointerException {@inheritDoc}
1551 */
1552 public boolean retainAll(Collection<?> c) {
1553 Objects.requireNonNull(c);
1554 return bulkRemove(e -> !c.contains(e));
1555 }
1556
1557 /** Implementation of bulk remove methods. */
1558 private boolean bulkRemove(Predicate<? super E> filter) {
1559 boolean removed = false;
1560 for (Node<E> p = first(), succ; p != null; p = succ) {
1561 succ = succ(p);
1562 final E item;
1563 if ((item = p.item) != null
1564 && filter.test(item)
1565 && ITEM.compareAndSet(p, item, null)) {
1566 unlink(p);
1567 removed = true;
1568 }
1569 }
1570 return removed;
1571 }
1572
1573 public void forEach(Consumer<? super E> action) {
1574 Objects.requireNonNull(action);
1575 E item;
1576 for (Node<E> p = first(); p != null; p = succ(p))
1577 if ((item = p.item) != null)
1578 action.accept(item);
1579 }
1580
1581 // VarHandle mechanics
1582 private static final VarHandle HEAD;
1583 private static final VarHandle TAIL;
1584 private static final VarHandle PREV;
1585 private static final VarHandle NEXT;
1586 private static final VarHandle ITEM;
1587 static {
1588 PREV_TERMINATOR = new Node<Object>();
1589 PREV_TERMINATOR.next = PREV_TERMINATOR;
1590 NEXT_TERMINATOR = new Node<Object>();
1591 NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1592 try {
1593 MethodHandles.Lookup l = MethodHandles.lookup();
1594 HEAD = l.findVarHandle(ConcurrentLinkedDeque.class, "head",
1595 Node.class);
1596 TAIL = l.findVarHandle(ConcurrentLinkedDeque.class, "tail",
1597 Node.class);
1598 PREV = l.findVarHandle(Node.class, "prev", Node.class);
1599 NEXT = l.findVarHandle(Node.class, "next", Node.class);
1600 ITEM = l.findVarHandle(Node.class, "item", Object.class);
1601 } catch (ReflectiveOperationException e) {
1602 throw new Error(e);
1603 }
1604 }
1605 }