ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.52
Committed: Sun Nov 23 17:44:51 2014 UTC (9 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.51: +6 -5 lines
Log Message:
save a few bytes of bytecode

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