ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.88
Committed: Tue Jan 31 22:21:17 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.87: +5 -2 lines
Log Message:
better style, better bytecode, as suggested by psandoz

File Contents

# Content
1 /*
2 * Written by Doug Lea and Martin Buchholz with assistance from members of
3 * JCP JSR-166 Expert Group and released to the public domain, as explained
4 * at http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.util.AbstractCollection;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Deque;
15 import java.util.Iterator;
16 import java.util.NoSuchElementException;
17 import java.util.Objects;
18 import java.util.Queue;
19 import java.util.Spliterator;
20 import java.util.Spliterators;
21 import java.util.function.Consumer;
22 import java.util.function.Predicate;
23
24 /**
25 * An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
26 * Concurrent insertion, removal, and access operations execute safely
27 * across multiple threads.
28 * A {@code ConcurrentLinkedDeque} is an appropriate choice when
29 * many threads will share access to a common collection.
30 * Like most other concurrent collection implementations, this class
31 * does not permit the use of {@code null} elements.
32 *
33 * <p>Iterators and spliterators are
34 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
35 *
36 * <p>Beware that, unlike in most collections, the {@code size} method
37 * is <em>NOT</em> a constant-time operation. Because of the
38 * asynchronous nature of these deques, determining the current number
39 * of elements requires a traversal of the elements, and so may report
40 * inaccurate results if this collection is modified during traversal.
41 *
42 * <p>Bulk operations that add, remove, or examine multiple elements,
43 * such as {@link #addAll}, {@link #removeIf} or {@link #forEach},
44 * are <em>not</em> guaranteed to be performed atomically.
45 * For example, a {@code forEach} traversal concurrent with an {@code
46 * addAll} operation might observe only some of the added elements.
47 *
48 * <p>This class and its iterator implement all of the <em>optional</em>
49 * methods of the {@link Deque} and {@link Iterator} interfaces.
50 *
51 * <p>Memory consistency effects: As with other concurrent collections,
52 * actions in a thread prior to placing an object into a
53 * {@code ConcurrentLinkedDeque}
54 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
55 * actions subsequent to the access or removal of that element from
56 * the {@code ConcurrentLinkedDeque} in another thread.
57 *
58 * <p>This class is a member of the
59 * <a href="{@docRoot}/../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 if (p == (p = p.next))
658 p = first();
659 return p;
660 }
661
662 /**
663 * Returns the predecessor of p, or the last node if p.prev has been
664 * linked to self, which will only be true if traversing with a
665 * stale pointer that is now off the list.
666 */
667 final Node<E> pred(Node<E> p) {
668 Node<E> q = p.prev;
669 return (p == q) ? last() : q;
670 }
671
672 /**
673 * Returns the first node, the unique node p for which:
674 * p.prev == null && p.next != p
675 * The returned node may or may not be logically deleted.
676 * Guarantees that head is set to the returned node.
677 */
678 Node<E> first() {
679 restartFromHead:
680 for (;;)
681 for (Node<E> h = head, p = h, q;;) {
682 if ((q = p.prev) != null &&
683 (q = (p = q).prev) != null)
684 // Check for head updates every other hop.
685 // If p == q, we are sure to follow head instead.
686 p = (h != (h = head)) ? h : q;
687 else if (p == h
688 // It is possible that p is PREV_TERMINATOR,
689 // but if so, the CAS is guaranteed to fail.
690 || HEAD.compareAndSet(this, h, p))
691 return p;
692 else
693 continue restartFromHead;
694 }
695 }
696
697 /**
698 * Returns the last node, the unique node p for which:
699 * p.next == null && p.prev != p
700 * The returned node may or may not be logically deleted.
701 * Guarantees that tail is set to the returned node.
702 */
703 Node<E> last() {
704 restartFromTail:
705 for (;;)
706 for (Node<E> t = tail, p = t, q;;) {
707 if ((q = p.next) != null &&
708 (q = (p = q).next) != null)
709 // Check for tail updates every other hop.
710 // If p == q, we are sure to follow tail instead.
711 p = (t != (t = tail)) ? t : q;
712 else if (p == t
713 // It is possible that p is NEXT_TERMINATOR,
714 // but if so, the CAS is guaranteed to fail.
715 || TAIL.compareAndSet(this, t, p))
716 return p;
717 else
718 continue restartFromTail;
719 }
720 }
721
722 // Minor convenience utilities
723
724 /**
725 * Returns element unless it is null, in which case throws
726 * NoSuchElementException.
727 *
728 * @param v the element
729 * @return the element
730 */
731 private E screenNullResult(E v) {
732 if (v == null)
733 throw new NoSuchElementException();
734 return v;
735 }
736
737 /**
738 * Constructs an empty deque.
739 */
740 public ConcurrentLinkedDeque() {
741 head = tail = new Node<E>();
742 }
743
744 /**
745 * Constructs a deque initially containing the elements of
746 * the given collection, added in traversal order of the
747 * collection's iterator.
748 *
749 * @param c the collection of elements to initially contain
750 * @throws NullPointerException if the specified collection or any
751 * of its elements are null
752 */
753 public ConcurrentLinkedDeque(Collection<? extends E> c) {
754 // Copy c into a private chain of Nodes
755 Node<E> h = null, t = null;
756 for (E e : c) {
757 Node<E> newNode = newNode(Objects.requireNonNull(e));
758 if (h == null)
759 h = t = newNode;
760 else {
761 NEXT.set(t, newNode);
762 PREV.set(newNode, t);
763 t = newNode;
764 }
765 }
766 initHeadTail(h, t);
767 }
768
769 /**
770 * Initializes head and tail, ensuring invariants hold.
771 */
772 private void initHeadTail(Node<E> h, Node<E> t) {
773 if (h == t) {
774 if (h == null)
775 h = t = new Node<E>();
776 else {
777 // Avoid edge case of a single Node with non-null item.
778 Node<E> newNode = new Node<E>();
779 NEXT.set(t, newNode);
780 PREV.set(newNode, t);
781 t = newNode;
782 }
783 }
784 head = h;
785 tail = t;
786 }
787
788 /**
789 * Inserts the specified element at the front of this deque.
790 * As the deque is unbounded, this method will never throw
791 * {@link IllegalStateException}.
792 *
793 * @throws NullPointerException if the specified element is null
794 */
795 public void addFirst(E e) {
796 linkFirst(e);
797 }
798
799 /**
800 * Inserts the specified element at the end of this deque.
801 * As the deque is unbounded, this method will never throw
802 * {@link IllegalStateException}.
803 *
804 * <p>This method is equivalent to {@link #add}.
805 *
806 * @throws NullPointerException if the specified element is null
807 */
808 public void addLast(E e) {
809 linkLast(e);
810 }
811
812 /**
813 * Inserts the specified element at the front of this deque.
814 * As the deque is unbounded, this method will never return {@code false}.
815 *
816 * @return {@code true} (as specified by {@link Deque#offerFirst})
817 * @throws NullPointerException if the specified element is null
818 */
819 public boolean offerFirst(E e) {
820 linkFirst(e);
821 return true;
822 }
823
824 /**
825 * Inserts the specified element at the end of this deque.
826 * As the deque is unbounded, this method will never return {@code false}.
827 *
828 * <p>This method is equivalent to {@link #add}.
829 *
830 * @return {@code true} (as specified by {@link Deque#offerLast})
831 * @throws NullPointerException if the specified element is null
832 */
833 public boolean offerLast(E e) {
834 linkLast(e);
835 return true;
836 }
837
838 public E peekFirst() {
839 for (Node<E> p = first(); p != null; p = succ(p)) {
840 final E item;
841 if ((item = p.item) != null)
842 return item;
843 }
844 return null;
845 }
846
847 public E peekLast() {
848 for (Node<E> p = last(); p != null; p = pred(p)) {
849 final E item;
850 if ((item = p.item) != null)
851 return item;
852 }
853 return null;
854 }
855
856 /**
857 * @throws NoSuchElementException {@inheritDoc}
858 */
859 public E getFirst() {
860 return screenNullResult(peekFirst());
861 }
862
863 /**
864 * @throws NoSuchElementException {@inheritDoc}
865 */
866 public E getLast() {
867 return screenNullResult(peekLast());
868 }
869
870 public E pollFirst() {
871 for (Node<E> p = first(); p != null; p = succ(p)) {
872 final E item;
873 if ((item = p.item) != null
874 && ITEM.compareAndSet(p, item, null)) {
875 unlink(p);
876 return item;
877 }
878 }
879 return null;
880 }
881
882 public E pollLast() {
883 for (Node<E> p = last(); p != null; p = pred(p)) {
884 final E item;
885 if ((item = p.item) != null
886 && ITEM.compareAndSet(p, item, null)) {
887 unlink(p);
888 return item;
889 }
890 }
891 return null;
892 }
893
894 /**
895 * @throws NoSuchElementException {@inheritDoc}
896 */
897 public E removeFirst() {
898 return screenNullResult(pollFirst());
899 }
900
901 /**
902 * @throws NoSuchElementException {@inheritDoc}
903 */
904 public E removeLast() {
905 return screenNullResult(pollLast());
906 }
907
908 // *** Queue and stack methods ***
909
910 /**
911 * Inserts the specified element at the tail of this deque.
912 * As the deque is unbounded, this method will never return {@code false}.
913 *
914 * @return {@code true} (as specified by {@link Queue#offer})
915 * @throws NullPointerException if the specified element is null
916 */
917 public boolean offer(E e) {
918 return offerLast(e);
919 }
920
921 /**
922 * Inserts the specified element at the tail of this deque.
923 * As the deque is unbounded, this method will never throw
924 * {@link IllegalStateException} or return {@code false}.
925 *
926 * @return {@code true} (as specified by {@link Collection#add})
927 * @throws NullPointerException if the specified element is null
928 */
929 public boolean add(E e) {
930 return offerLast(e);
931 }
932
933 public E poll() { return pollFirst(); }
934 public E peek() { return peekFirst(); }
935
936 /**
937 * @throws NoSuchElementException {@inheritDoc}
938 */
939 public E remove() { return removeFirst(); }
940
941 /**
942 * @throws NoSuchElementException {@inheritDoc}
943 */
944 public E pop() { return removeFirst(); }
945
946 /**
947 * @throws NoSuchElementException {@inheritDoc}
948 */
949 public E element() { return getFirst(); }
950
951 /**
952 * @throws NullPointerException {@inheritDoc}
953 */
954 public void push(E e) { addFirst(e); }
955
956 /**
957 * Removes the first occurrence of the specified element from this deque.
958 * If the deque does not contain the element, it is unchanged.
959 * More formally, removes the first element {@code e} such that
960 * {@code o.equals(e)} (if such an element exists).
961 * Returns {@code true} if this deque contained the specified element
962 * (or equivalently, if this deque changed as a result of the call).
963 *
964 * @param o element to be removed from this deque, if present
965 * @return {@code true} if the deque contained the specified element
966 * @throws NullPointerException if the specified element is null
967 */
968 public boolean removeFirstOccurrence(Object o) {
969 Objects.requireNonNull(o);
970 for (Node<E> p = first(); p != null; p = succ(p)) {
971 final E item;
972 if ((item = p.item) != null
973 && o.equals(item)
974 && ITEM.compareAndSet(p, item, null)) {
975 unlink(p);
976 return true;
977 }
978 }
979 return false;
980 }
981
982 /**
983 * Removes the last occurrence of the specified element from this deque.
984 * If the deque does not contain the element, it is unchanged.
985 * More formally, removes the last element {@code e} such that
986 * {@code o.equals(e)} (if such an element exists).
987 * Returns {@code true} if this deque contained the specified element
988 * (or equivalently, if this deque changed as a result of the call).
989 *
990 * @param o element to be removed from this deque, if present
991 * @return {@code true} if the deque contained the specified element
992 * @throws NullPointerException if the specified element is null
993 */
994 public boolean removeLastOccurrence(Object o) {
995 Objects.requireNonNull(o);
996 for (Node<E> p = last(); p != null; p = pred(p)) {
997 final E item;
998 if ((item = p.item) != null
999 && o.equals(item)
1000 && ITEM.compareAndSet(p, item, null)) {
1001 unlink(p);
1002 return true;
1003 }
1004 }
1005 return false;
1006 }
1007
1008 /**
1009 * Returns {@code true} if this deque contains the specified element.
1010 * More formally, returns {@code true} if and only if this deque contains
1011 * at least one element {@code e} such that {@code o.equals(e)}.
1012 *
1013 * @param o element whose presence in this deque is to be tested
1014 * @return {@code true} if this deque contains the specified element
1015 */
1016 public boolean contains(Object o) {
1017 if (o != null) {
1018 for (Node<E> p = first(); p != null; p = succ(p)) {
1019 final E item;
1020 if ((item = p.item) != null && o.equals(item))
1021 return true;
1022 }
1023 }
1024 return false;
1025 }
1026
1027 /**
1028 * Returns {@code true} if this collection contains no elements.
1029 *
1030 * @return {@code true} if this collection contains no elements
1031 */
1032 public boolean isEmpty() {
1033 return peekFirst() == null;
1034 }
1035
1036 /**
1037 * Returns the number of elements in this deque. If this deque
1038 * contains more than {@code Integer.MAX_VALUE} elements, it
1039 * returns {@code Integer.MAX_VALUE}.
1040 *
1041 * <p>Beware that, unlike in most collections, this method is
1042 * <em>NOT</em> a constant-time operation. Because of the
1043 * asynchronous nature of these deques, determining the current
1044 * number of elements requires traversing them all to count them.
1045 * Additionally, it is possible for the size to change during
1046 * execution of this method, in which case the returned result
1047 * will be inaccurate. Thus, this method is typically not very
1048 * useful in concurrent applications.
1049 *
1050 * @return the number of elements in this deque
1051 */
1052 public int size() {
1053 restartFromHead: for (;;) {
1054 int count = 0;
1055 for (Node<E> p = first(); p != null;) {
1056 if (p.item != null)
1057 if (++count == Integer.MAX_VALUE)
1058 break; // @see Collection.size()
1059 if (p == (p = p.next))
1060 continue restartFromHead;
1061 }
1062 return count;
1063 }
1064 }
1065
1066 /**
1067 * Removes the first occurrence of the specified element from this deque.
1068 * If the deque does not contain the element, it is unchanged.
1069 * More formally, removes the first element {@code e} such that
1070 * {@code o.equals(e)} (if such an element exists).
1071 * Returns {@code true} if this deque contained the specified element
1072 * (or equivalently, if this deque changed as a result of the call).
1073 *
1074 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1075 *
1076 * @param o element to be removed from this deque, if present
1077 * @return {@code true} if the deque contained the specified element
1078 * @throws NullPointerException if the specified element is null
1079 */
1080 public boolean remove(Object o) {
1081 return removeFirstOccurrence(o);
1082 }
1083
1084 /**
1085 * Appends all of the elements in the specified collection to the end of
1086 * this deque, in the order that they are returned by the specified
1087 * collection's iterator. Attempts to {@code addAll} of a deque to
1088 * itself result in {@code IllegalArgumentException}.
1089 *
1090 * @param c the elements to be inserted into this deque
1091 * @return {@code true} if this deque changed as a result of the call
1092 * @throws NullPointerException if the specified collection or any
1093 * of its elements are null
1094 * @throws IllegalArgumentException if the collection is this deque
1095 */
1096 public boolean addAll(Collection<? extends E> c) {
1097 if (c == this)
1098 // As historically specified in AbstractQueue#addAll
1099 throw new IllegalArgumentException();
1100
1101 // Copy c into a private chain of Nodes
1102 Node<E> beginningOfTheEnd = null, last = null;
1103 for (E e : c) {
1104 Node<E> newNode = newNode(Objects.requireNonNull(e));
1105 if (beginningOfTheEnd == null)
1106 beginningOfTheEnd = last = newNode;
1107 else {
1108 NEXT.set(last, newNode);
1109 PREV.set(newNode, last);
1110 last = newNode;
1111 }
1112 }
1113 if (beginningOfTheEnd == null)
1114 return false;
1115
1116 // Atomically append the chain at the tail of this collection
1117 restartFromTail:
1118 for (;;)
1119 for (Node<E> t = tail, p = t, q;;) {
1120 if ((q = p.next) != null &&
1121 (q = (p = q).next) != null)
1122 // Check for tail updates every other hop.
1123 // If p == q, we are sure to follow tail instead.
1124 p = (t != (t = tail)) ? t : q;
1125 else if (p.prev == p) // NEXT_TERMINATOR
1126 continue restartFromTail;
1127 else {
1128 // p is last node
1129 PREV.set(beginningOfTheEnd, p); // CAS piggyback
1130 if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
1131 // Successful CAS is the linearization point
1132 // for all elements to be added to this deque.
1133 if (!TAIL.weakCompareAndSet(this, t, last)) {
1134 // Try a little harder to update tail,
1135 // since we may be adding many elements.
1136 t = tail;
1137 if (last.next == null)
1138 TAIL.weakCompareAndSet(this, t, last);
1139 }
1140 return true;
1141 }
1142 // Lost CAS race to another thread; re-read next
1143 }
1144 }
1145 }
1146
1147 /**
1148 * Removes all of the elements from this deque.
1149 */
1150 public void clear() {
1151 while (pollFirst() != null)
1152 ;
1153 }
1154
1155 public String toString() {
1156 String[] a = null;
1157 restartFromHead: for (;;) {
1158 int charLength = 0;
1159 int size = 0;
1160 for (Node<E> p = first(); p != null;) {
1161 final E item;
1162 if ((item = p.item) != null) {
1163 if (a == null)
1164 a = new String[4];
1165 else if (size == a.length)
1166 a = Arrays.copyOf(a, 2 * size);
1167 String s = item.toString();
1168 a[size++] = s;
1169 charLength += s.length();
1170 }
1171 if (p == (p = p.next))
1172 continue restartFromHead;
1173 }
1174
1175 if (size == 0)
1176 return "[]";
1177
1178 return Helpers.toString(a, size, charLength);
1179 }
1180 }
1181
1182 private Object[] toArrayInternal(Object[] a) {
1183 Object[] x = a;
1184 restartFromHead: for (;;) {
1185 int size = 0;
1186 for (Node<E> p = first(); p != null;) {
1187 final E item;
1188 if ((item = p.item) != null) {
1189 if (x == null)
1190 x = new Object[4];
1191 else if (size == x.length)
1192 x = Arrays.copyOf(x, 2 * (size + 4));
1193 x[size++] = item;
1194 }
1195 if (p == (p = p.next))
1196 continue restartFromHead;
1197 }
1198 if (x == null)
1199 return new Object[0];
1200 else if (a != null && size <= a.length) {
1201 if (a != x)
1202 System.arraycopy(x, 0, a, 0, size);
1203 if (size < a.length)
1204 a[size] = null;
1205 return a;
1206 }
1207 return (size == x.length) ? x : Arrays.copyOf(x, size);
1208 }
1209 }
1210
1211 /**
1212 * Returns an array containing all of the elements in this deque, in
1213 * proper sequence (from first to last element).
1214 *
1215 * <p>The returned array will be "safe" in that no references to it are
1216 * maintained by this deque. (In other words, this method must allocate
1217 * a new array). The caller is thus free to modify the returned array.
1218 *
1219 * <p>This method acts as bridge between array-based and collection-based
1220 * APIs.
1221 *
1222 * @return an array containing all of the elements in this deque
1223 */
1224 public Object[] toArray() {
1225 return toArrayInternal(null);
1226 }
1227
1228 /**
1229 * Returns an array containing all of the elements in this deque,
1230 * in proper sequence (from first to last element); the runtime
1231 * type of the returned array is that of the specified array. If
1232 * the deque fits in the specified array, it is returned therein.
1233 * Otherwise, a new array is allocated with the runtime type of
1234 * the specified array and the size of this deque.
1235 *
1236 * <p>If this deque fits in the specified array with room to spare
1237 * (i.e., the array has more elements than this deque), the element in
1238 * the array immediately following the end of the deque is set to
1239 * {@code null}.
1240 *
1241 * <p>Like the {@link #toArray()} method, this method acts as
1242 * bridge between array-based and collection-based APIs. Further,
1243 * this method allows precise control over the runtime type of the
1244 * output array, and may, under certain circumstances, be used to
1245 * save allocation costs.
1246 *
1247 * <p>Suppose {@code x} is a deque known to contain only strings.
1248 * The following code can be used to dump the deque into a newly
1249 * allocated array of {@code String}:
1250 *
1251 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1252 *
1253 * Note that {@code toArray(new Object[0])} is identical in function to
1254 * {@code toArray()}.
1255 *
1256 * @param a the array into which the elements of the deque are to
1257 * be stored, if it is big enough; otherwise, a new array of the
1258 * same runtime type is allocated for this purpose
1259 * @return an array containing all of the elements in this deque
1260 * @throws ArrayStoreException if the runtime type of the specified array
1261 * is not a supertype of the runtime type of every element in
1262 * this deque
1263 * @throws NullPointerException if the specified array is null
1264 */
1265 @SuppressWarnings("unchecked")
1266 public <T> T[] toArray(T[] a) {
1267 if (a == null) throw new NullPointerException();
1268 return (T[]) toArrayInternal(a);
1269 }
1270
1271 /**
1272 * Returns an iterator over the elements in this deque in proper sequence.
1273 * The elements will be returned in order from first (head) to last (tail).
1274 *
1275 * <p>The returned iterator is
1276 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1277 *
1278 * @return an iterator over the elements in this deque in proper sequence
1279 */
1280 public Iterator<E> iterator() {
1281 return new Itr();
1282 }
1283
1284 /**
1285 * Returns an iterator over the elements in this deque in reverse
1286 * sequential order. The elements will be returned in order from
1287 * last (tail) to first (head).
1288 *
1289 * <p>The returned iterator is
1290 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1291 *
1292 * @return an iterator over the elements in this deque in reverse order
1293 */
1294 public Iterator<E> descendingIterator() {
1295 return new DescendingItr();
1296 }
1297
1298 private abstract class AbstractItr implements Iterator<E> {
1299 /**
1300 * Next node to return item for.
1301 */
1302 private Node<E> nextNode;
1303
1304 /**
1305 * nextItem holds on to item fields because once we claim
1306 * that an element exists in hasNext(), we must return it in
1307 * the following next() call even if it was in the process of
1308 * being removed when hasNext() was called.
1309 */
1310 private E nextItem;
1311
1312 /**
1313 * Node returned by most recent call to next. Needed by remove.
1314 * Reset to null if this element is deleted by a call to remove.
1315 */
1316 private Node<E> lastRet;
1317
1318 abstract Node<E> startNode();
1319 abstract Node<E> nextNode(Node<E> p);
1320
1321 AbstractItr() {
1322 advance();
1323 }
1324
1325 /**
1326 * Sets nextNode and nextItem to next valid node, or to null
1327 * if no such.
1328 */
1329 private void advance() {
1330 lastRet = nextNode;
1331
1332 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1333 for (;; p = nextNode(p)) {
1334 if (p == null) {
1335 // might be at active end or TERMINATOR node; both are OK
1336 nextNode = null;
1337 nextItem = null;
1338 break;
1339 }
1340 final E item;
1341 if ((item = p.item) != null) {
1342 nextNode = p;
1343 nextItem = item;
1344 break;
1345 }
1346 }
1347 }
1348
1349 public boolean hasNext() {
1350 return nextItem != null;
1351 }
1352
1353 public E next() {
1354 E item = nextItem;
1355 if (item == null) throw new NoSuchElementException();
1356 advance();
1357 return item;
1358 }
1359
1360 public void remove() {
1361 Node<E> l = lastRet;
1362 if (l == null) throw new IllegalStateException();
1363 l.item = null;
1364 unlink(l);
1365 lastRet = null;
1366 }
1367 }
1368
1369 /** Forward iterator */
1370 private class Itr extends AbstractItr {
1371 Itr() {} // prevent access constructor creation
1372 Node<E> startNode() { return first(); }
1373 Node<E> nextNode(Node<E> p) { return succ(p); }
1374 }
1375
1376 /** Descending iterator */
1377 private class DescendingItr extends AbstractItr {
1378 DescendingItr() {} // prevent access constructor creation
1379 Node<E> startNode() { return last(); }
1380 Node<E> nextNode(Node<E> p) { return pred(p); }
1381 }
1382
1383 /** A customized variant of Spliterators.IteratorSpliterator */
1384 final class CLDSpliterator implements Spliterator<E> {
1385 static final int MAX_BATCH = 1 << 25; // max batch array size;
1386 Node<E> current; // current node; null until initialized
1387 int batch; // batch size for splits
1388 boolean exhausted; // true when no more nodes
1389
1390 public Spliterator<E> trySplit() {
1391 Node<E> p, q;
1392 if ((p = current()) == null || (q = p.next) == null)
1393 return null;
1394 int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
1395 Object[] a = null;
1396 do {
1397 final E e;
1398 if ((e = p.item) != null) {
1399 if (a == null)
1400 a = new Object[n];
1401 a[i++] = e;
1402 }
1403 if (p == (p = q))
1404 p = first();
1405 } while (p != null && (q = p.next) != null && i < n);
1406 setCurrent(p);
1407 return (i == 0) ? null :
1408 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
1409 Spliterator.NONNULL |
1410 Spliterator.CONCURRENT));
1411 }
1412
1413 public void forEachRemaining(Consumer<? super E> action) {
1414 Objects.requireNonNull(action);
1415 Node<E> p;
1416 if ((p = current()) != null) {
1417 current = null;
1418 exhausted = true;
1419 do {
1420 final E e;
1421 if ((e = p.item) != null)
1422 action.accept(e);
1423 if (p == (p = p.next))
1424 p = first();
1425 } while (p != null);
1426 }
1427 }
1428
1429 public boolean tryAdvance(Consumer<? super E> action) {
1430 Objects.requireNonNull(action);
1431 Node<E> p;
1432 if ((p = current()) != null) {
1433 E e;
1434 do {
1435 e = p.item;
1436 if (p == (p = p.next))
1437 p = first();
1438 } while (e == null && p != null);
1439 setCurrent(p);
1440 if (e != null) {
1441 action.accept(e);
1442 return true;
1443 }
1444 }
1445 return false;
1446 }
1447
1448 private void setCurrent(Node<E> p) {
1449 if ((current = p) == null)
1450 exhausted = true;
1451 }
1452
1453 private Node<E> current() {
1454 Node<E> p;
1455 if ((p = current) == null && !exhausted)
1456 setCurrent(p = first());
1457 return p;
1458 }
1459
1460 public long estimateSize() { return Long.MAX_VALUE; }
1461
1462 public int characteristics() {
1463 return (Spliterator.ORDERED |
1464 Spliterator.NONNULL |
1465 Spliterator.CONCURRENT);
1466 }
1467 }
1468
1469 /**
1470 * Returns a {@link Spliterator} over the elements in this deque.
1471 *
1472 * <p>The returned spliterator is
1473 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1474 *
1475 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1476 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1477 *
1478 * @implNote
1479 * The {@code Spliterator} implements {@code trySplit} to permit limited
1480 * parallelism.
1481 *
1482 * @return a {@code Spliterator} over the elements in this deque
1483 * @since 1.8
1484 */
1485 public Spliterator<E> spliterator() {
1486 return new CLDSpliterator();
1487 }
1488
1489 /**
1490 * Saves this deque to a stream (that is, serializes it).
1491 *
1492 * @param s the stream
1493 * @throws java.io.IOException if an I/O error occurs
1494 * @serialData All of the elements (each an {@code E}) in
1495 * the proper order, followed by a null
1496 */
1497 private void writeObject(java.io.ObjectOutputStream s)
1498 throws java.io.IOException {
1499
1500 // Write out any hidden stuff
1501 s.defaultWriteObject();
1502
1503 // Write out all elements in the proper order.
1504 for (Node<E> p = first(); p != null; p = succ(p)) {
1505 final E item;
1506 if ((item = p.item) != null)
1507 s.writeObject(item);
1508 }
1509
1510 // Use trailing null as sentinel
1511 s.writeObject(null);
1512 }
1513
1514 /**
1515 * Reconstitutes this deque from a stream (that is, deserializes it).
1516 * @param s the stream
1517 * @throws ClassNotFoundException if the class of a serialized object
1518 * could not be found
1519 * @throws java.io.IOException if an I/O error occurs
1520 */
1521 private void readObject(java.io.ObjectInputStream s)
1522 throws java.io.IOException, ClassNotFoundException {
1523 s.defaultReadObject();
1524
1525 // Read in elements until trailing null sentinel found
1526 Node<E> h = null, t = null;
1527 for (Object item; (item = s.readObject()) != null; ) {
1528 @SuppressWarnings("unchecked")
1529 Node<E> newNode = newNode((E) item);
1530 if (h == null)
1531 h = t = newNode;
1532 else {
1533 NEXT.set(t, newNode);
1534 PREV.set(newNode, t);
1535 t = newNode;
1536 }
1537 }
1538 initHeadTail(h, t);
1539 }
1540
1541 /**
1542 * @throws NullPointerException {@inheritDoc}
1543 */
1544 public boolean removeIf(Predicate<? super E> filter) {
1545 Objects.requireNonNull(filter);
1546 return bulkRemove(filter);
1547 }
1548
1549 /**
1550 * @throws NullPointerException {@inheritDoc}
1551 */
1552 public boolean removeAll(Collection<?> c) {
1553 Objects.requireNonNull(c);
1554 return bulkRemove(e -> c.contains(e));
1555 }
1556
1557 /**
1558 * @throws NullPointerException {@inheritDoc}
1559 */
1560 public boolean retainAll(Collection<?> c) {
1561 Objects.requireNonNull(c);
1562 return bulkRemove(e -> !c.contains(e));
1563 }
1564
1565 /** Implementation of bulk remove methods. */
1566 private boolean bulkRemove(Predicate<? super E> filter) {
1567 boolean removed = false;
1568 for (Node<E> p = first(), succ; p != null; p = succ) {
1569 succ = succ(p);
1570 final E item;
1571 if ((item = p.item) != null
1572 && filter.test(item)
1573 && ITEM.compareAndSet(p, item, null)) {
1574 unlink(p);
1575 removed = true;
1576 }
1577 }
1578 return removed;
1579 }
1580
1581 /**
1582 * @throws NullPointerException {@inheritDoc}
1583 */
1584 public void forEach(Consumer<? super E> action) {
1585 Objects.requireNonNull(action);
1586 E item;
1587 for (Node<E> p = first(); p != null; p = succ(p))
1588 if ((item = p.item) != null)
1589 action.accept(item);
1590 }
1591
1592 // VarHandle mechanics
1593 private static final VarHandle HEAD;
1594 private static final VarHandle TAIL;
1595 private static final VarHandle PREV;
1596 private static final VarHandle NEXT;
1597 private static final VarHandle ITEM;
1598 static {
1599 PREV_TERMINATOR = new Node<Object>();
1600 PREV_TERMINATOR.next = PREV_TERMINATOR;
1601 NEXT_TERMINATOR = new Node<Object>();
1602 NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1603 try {
1604 MethodHandles.Lookup l = MethodHandles.lookup();
1605 HEAD = l.findVarHandle(ConcurrentLinkedDeque.class, "head",
1606 Node.class);
1607 TAIL = l.findVarHandle(ConcurrentLinkedDeque.class, "tail",
1608 Node.class);
1609 PREV = l.findVarHandle(Node.class, "prev", Node.class);
1610 NEXT = l.findVarHandle(Node.class, "next", Node.class);
1611 ITEM = l.findVarHandle(Node.class, "item", Object.class);
1612 } catch (ReflectiveOperationException e) {
1613 throw new Error(e);
1614 }
1615 }
1616 }