ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.61
Committed: Tue Feb 17 18:55:39 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +1 -1 lines
Log Message:
standardize code sample idiom: * <pre> {@code

File Contents

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