ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.51
Committed: Tue Nov 11 04:39:30 2014 UTC (9 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.50: +13 -7 lines
Log Message:
improve accuracy of concurrent queue size methods

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) return false;
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 return false;
1078 }
1079
1080 /**
1081 * Returns {@code true} if this collection contains no elements.
1082 *
1083 * @return {@code true} if this collection contains no elements
1084 */
1085 public boolean isEmpty() {
1086 return peekFirst() == null;
1087 }
1088
1089 /**
1090 * Returns the number of elements in this deque. If this deque
1091 * contains more than {@code Integer.MAX_VALUE} elements, it
1092 * returns {@code Integer.MAX_VALUE}.
1093 *
1094 * <p>Beware that, unlike in most collections, this method is
1095 * <em>NOT</em> a constant-time operation. Because of the
1096 * asynchronous nature of these deques, determining the current
1097 * number of elements requires traversing them all to count them.
1098 * Additionally, it is possible for the size to change during
1099 * execution of this method, in which case the returned result
1100 * will be inaccurate. Thus, this method is typically not very
1101 * useful in concurrent applications.
1102 *
1103 * @return the number of elements in this deque
1104 */
1105 public int size() {
1106 restartFromHead: for (;;) {
1107 int count = 0;
1108 for (Node<E> p = first(); p != null;) {
1109 if (p.item != null)
1110 if (++count == Integer.MAX_VALUE)
1111 break; // @see Collection.size()
1112 Node<E> next = p.next;
1113 if (p == next)
1114 continue restartFromHead;
1115 p = next;
1116 }
1117 return count;
1118 }
1119 }
1120
1121 /**
1122 * Removes the first element {@code e} such that
1123 * {@code o.equals(e)}, if such an element exists in this deque.
1124 * If the deque does not contain the element, it is unchanged.
1125 *
1126 * @param o element to be removed from this deque, if present
1127 * @return {@code true} if the deque contained the specified element
1128 * @throws NullPointerException if the specified element is null
1129 */
1130 public boolean remove(Object o) {
1131 return removeFirstOccurrence(o);
1132 }
1133
1134 /**
1135 * Appends all of the elements in the specified collection to the end of
1136 * this deque, in the order that they are returned by the specified
1137 * collection's iterator. Attempts to {@code addAll} of a deque to
1138 * itself result in {@code IllegalArgumentException}.
1139 *
1140 * @param c the elements to be inserted into this deque
1141 * @return {@code true} if this deque changed as a result of the call
1142 * @throws NullPointerException if the specified collection or any
1143 * of its elements are null
1144 * @throws IllegalArgumentException if the collection is this deque
1145 */
1146 public boolean addAll(Collection<? extends E> c) {
1147 if (c == this)
1148 // As historically specified in AbstractQueue#addAll
1149 throw new IllegalArgumentException();
1150
1151 // Copy c into a private chain of Nodes
1152 Node<E> beginningOfTheEnd = null, last = null;
1153 for (E e : c) {
1154 checkNotNull(e);
1155 Node<E> newNode = new Node<E>(e);
1156 if (beginningOfTheEnd == null)
1157 beginningOfTheEnd = last = newNode;
1158 else {
1159 last.lazySetNext(newNode);
1160 newNode.lazySetPrev(last);
1161 last = newNode;
1162 }
1163 }
1164 if (beginningOfTheEnd == null)
1165 return false;
1166
1167 // Atomically append the chain at the tail of this collection
1168 restartFromTail:
1169 for (;;)
1170 for (Node<E> t = tail, p = t, q;;) {
1171 if ((q = p.next) != null &&
1172 (q = (p = q).next) != null)
1173 // Check for tail updates every other hop.
1174 // If p == q, we are sure to follow tail instead.
1175 p = (t != (t = tail)) ? t : q;
1176 else if (p.prev == p) // NEXT_TERMINATOR
1177 continue restartFromTail;
1178 else {
1179 // p is last node
1180 beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
1181 if (p.casNext(null, beginningOfTheEnd)) {
1182 // Successful CAS is the linearization point
1183 // for all elements to be added to this deque.
1184 if (!casTail(t, last)) {
1185 // Try a little harder to update tail,
1186 // since we may be adding many elements.
1187 t = tail;
1188 if (last.next == null)
1189 casTail(t, last);
1190 }
1191 return true;
1192 }
1193 // Lost CAS race to another thread; re-read next
1194 }
1195 }
1196 }
1197
1198 /**
1199 * Removes all of the elements from this deque.
1200 */
1201 public void clear() {
1202 while (pollFirst() != null)
1203 ;
1204 }
1205
1206 /**
1207 * Returns an array containing all of the elements in this deque, in
1208 * proper sequence (from first to last element).
1209 *
1210 * <p>The returned array will be "safe" in that no references to it are
1211 * maintained by this deque. (In other words, this method must allocate
1212 * a new array). The caller is thus free to modify the returned array.
1213 *
1214 * <p>This method acts as bridge between array-based and collection-based
1215 * APIs.
1216 *
1217 * @return an array containing all of the elements in this deque
1218 */
1219 public Object[] toArray() {
1220 return toArrayList().toArray();
1221 }
1222
1223 /**
1224 * Returns an array containing all of the elements in this deque,
1225 * in proper sequence (from first to last element); the runtime
1226 * type of the returned array is that of the specified array. If
1227 * the deque fits in the specified array, it is returned therein.
1228 * Otherwise, a new array is allocated with the runtime type of
1229 * the specified array and the size of this deque.
1230 *
1231 * <p>If this deque fits in the specified array with room to spare
1232 * (i.e., the array has more elements than this deque), the element in
1233 * the array immediately following the end of the deque is set to
1234 * {@code null}.
1235 *
1236 * <p>Like the {@link #toArray()} method, this method acts as
1237 * bridge between array-based and collection-based APIs. Further,
1238 * this method allows precise control over the runtime type of the
1239 * output array, and may, under certain circumstances, be used to
1240 * save allocation costs.
1241 *
1242 * <p>Suppose {@code x} is a deque known to contain only strings.
1243 * The following code can be used to dump the deque into a newly
1244 * allocated array of {@code String}:
1245 *
1246 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1247 *
1248 * Note that {@code toArray(new Object[0])} is identical in function to
1249 * {@code toArray()}.
1250 *
1251 * @param a the array into which the elements of the deque are to
1252 * be stored, if it is big enough; otherwise, a new array of the
1253 * same runtime type is allocated for this purpose
1254 * @return an array containing all of the elements in this deque
1255 * @throws ArrayStoreException if the runtime type of the specified array
1256 * is not a supertype of the runtime type of every element in
1257 * this deque
1258 * @throws NullPointerException if the specified array is null
1259 */
1260 public <T> T[] toArray(T[] a) {
1261 return toArrayList().toArray(a);
1262 }
1263
1264 /**
1265 * Returns an iterator over the elements in this deque in proper sequence.
1266 * The elements will be returned in order from first (head) to last (tail).
1267 *
1268 * <p>The returned iterator is
1269 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1270 *
1271 * @return an iterator over the elements in this deque in proper sequence
1272 */
1273 public Iterator<E> iterator() {
1274 return new Itr();
1275 }
1276
1277 /**
1278 * Returns an iterator over the elements in this deque in reverse
1279 * sequential order. The elements will be returned in order from
1280 * last (tail) to first (head).
1281 *
1282 * <p>The returned iterator is
1283 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1284 *
1285 * @return an iterator over the elements in this deque in reverse order
1286 */
1287 public Iterator<E> descendingIterator() {
1288 return new DescendingItr();
1289 }
1290
1291 private abstract class AbstractItr implements Iterator<E> {
1292 /**
1293 * Next node to return item for.
1294 */
1295 private Node<E> nextNode;
1296
1297 /**
1298 * nextItem holds on to item fields because once we claim
1299 * that an element exists in hasNext(), we must return it in
1300 * the following next() call even if it was in the process of
1301 * being removed when hasNext() was called.
1302 */
1303 private E nextItem;
1304
1305 /**
1306 * Node returned by most recent call to next. Needed by remove.
1307 * Reset to null if this element is deleted by a call to remove.
1308 */
1309 private Node<E> lastRet;
1310
1311 abstract Node<E> startNode();
1312 abstract Node<E> nextNode(Node<E> p);
1313
1314 AbstractItr() {
1315 advance();
1316 }
1317
1318 /**
1319 * Sets nextNode and nextItem to next valid node, or to null
1320 * if no such.
1321 */
1322 private void advance() {
1323 lastRet = nextNode;
1324
1325 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1326 for (;; p = nextNode(p)) {
1327 if (p == null) {
1328 // p might be active end or TERMINATOR node; both are OK
1329 nextNode = null;
1330 nextItem = null;
1331 break;
1332 }
1333 E item = p.item;
1334 if (item != null) {
1335 nextNode = p;
1336 nextItem = item;
1337 break;
1338 }
1339 }
1340 }
1341
1342 public boolean hasNext() {
1343 return nextItem != null;
1344 }
1345
1346 public E next() {
1347 E item = nextItem;
1348 if (item == null) throw new NoSuchElementException();
1349 advance();
1350 return item;
1351 }
1352
1353 public void remove() {
1354 Node<E> l = lastRet;
1355 if (l == null) throw new IllegalStateException();
1356 l.item = null;
1357 unlink(l);
1358 lastRet = null;
1359 }
1360 }
1361
1362 /** Forward iterator */
1363 private class Itr extends AbstractItr {
1364 Node<E> startNode() { return first(); }
1365 Node<E> nextNode(Node<E> p) { return succ(p); }
1366 }
1367
1368 /** Descending iterator */
1369 private class DescendingItr extends AbstractItr {
1370 Node<E> startNode() { return last(); }
1371 Node<E> nextNode(Node<E> p) { return pred(p); }
1372 }
1373
1374 /** A customized variant of Spliterators.IteratorSpliterator */
1375 static final class CLDSpliterator<E> implements Spliterator<E> {
1376 static final int MAX_BATCH = 1 << 25; // max batch array size;
1377 final ConcurrentLinkedDeque<E> queue;
1378 Node<E> current; // current node; null until initialized
1379 int batch; // batch size for splits
1380 boolean exhausted; // true when no more nodes
1381 CLDSpliterator(ConcurrentLinkedDeque<E> queue) {
1382 this.queue = queue;
1383 }
1384
1385 public Spliterator<E> trySplit() {
1386 Node<E> p;
1387 final ConcurrentLinkedDeque<E> q = this.queue;
1388 int b = batch;
1389 int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1390 if (!exhausted &&
1391 ((p = current) != null || (p = q.first()) != null)) {
1392 if (p.item == null && p == (p = p.next))
1393 current = p = q.first();
1394 if (p != null && p.next != null) {
1395 Object[] a = new Object[n];
1396 int i = 0;
1397 do {
1398 if ((a[i] = p.item) != null)
1399 ++i;
1400 if (p == (p = p.next))
1401 p = q.first();
1402 } while (p != null && i < n);
1403 if ((current = p) == null)
1404 exhausted = true;
1405 if (i > 0) {
1406 batch = i;
1407 return Spliterators.spliterator
1408 (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
1409 Spliterator.CONCURRENT);
1410 }
1411 }
1412 }
1413 return null;
1414 }
1415
1416 public void forEachRemaining(Consumer<? super E> action) {
1417 Node<E> p;
1418 if (action == null) throw new NullPointerException();
1419 final ConcurrentLinkedDeque<E> q = this.queue;
1420 if (!exhausted &&
1421 ((p = current) != null || (p = q.first()) != null)) {
1422 exhausted = true;
1423 do {
1424 E e = p.item;
1425 if (p == (p = p.next))
1426 p = q.first();
1427 if (e != null)
1428 action.accept(e);
1429 } while (p != null);
1430 }
1431 }
1432
1433 public boolean tryAdvance(Consumer<? super E> action) {
1434 Node<E> p;
1435 if (action == null) throw new NullPointerException();
1436 final ConcurrentLinkedDeque<E> q = this.queue;
1437 if (!exhausted &&
1438 ((p = current) != null || (p = q.first()) != null)) {
1439 E e;
1440 do {
1441 e = p.item;
1442 if (p == (p = p.next))
1443 p = q.first();
1444 } while (e == null && p != null);
1445 if ((current = p) == null)
1446 exhausted = true;
1447 if (e != null) {
1448 action.accept(e);
1449 return true;
1450 }
1451 }
1452 return false;
1453 }
1454
1455 public long estimateSize() { return Long.MAX_VALUE; }
1456
1457 public int characteristics() {
1458 return Spliterator.ORDERED | Spliterator.NONNULL |
1459 Spliterator.CONCURRENT;
1460 }
1461 }
1462
1463 /**
1464 * Returns a {@link Spliterator} over the elements in this deque.
1465 *
1466 * <p>The returned spliterator is
1467 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1468 *
1469 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1470 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1471 *
1472 * @implNote
1473 * The {@code Spliterator} implements {@code trySplit} to permit limited
1474 * parallelism.
1475 *
1476 * @return a {@code Spliterator} over the elements in this deque
1477 * @since 1.8
1478 */
1479 public Spliterator<E> spliterator() {
1480 return new CLDSpliterator<E>(this);
1481 }
1482
1483 /**
1484 * Saves this deque to a stream (that is, serializes it).
1485 *
1486 * @param s the stream
1487 * @throws java.io.IOException if an I/O error occurs
1488 * @serialData All of the elements (each an {@code E}) in
1489 * the proper order, followed by a null
1490 */
1491 private void writeObject(java.io.ObjectOutputStream s)
1492 throws java.io.IOException {
1493
1494 // Write out any hidden stuff
1495 s.defaultWriteObject();
1496
1497 // Write out all elements in the proper order.
1498 for (Node<E> p = first(); p != null; p = succ(p)) {
1499 E item = p.item;
1500 if (item != null)
1501 s.writeObject(item);
1502 }
1503
1504 // Use trailing null as sentinel
1505 s.writeObject(null);
1506 }
1507
1508 /**
1509 * Reconstitutes this deque from a stream (that is, deserializes it).
1510 * @param s the stream
1511 * @throws ClassNotFoundException if the class of a serialized object
1512 * could not be found
1513 * @throws java.io.IOException if an I/O error occurs
1514 */
1515 private void readObject(java.io.ObjectInputStream s)
1516 throws java.io.IOException, ClassNotFoundException {
1517 s.defaultReadObject();
1518
1519 // Read in elements until trailing null sentinel found
1520 Node<E> h = null, t = null;
1521 Object item;
1522 while ((item = s.readObject()) != null) {
1523 @SuppressWarnings("unchecked")
1524 Node<E> newNode = new Node<E>((E) item);
1525 if (h == null)
1526 h = t = newNode;
1527 else {
1528 t.lazySetNext(newNode);
1529 newNode.lazySetPrev(t);
1530 t = newNode;
1531 }
1532 }
1533 initHeadTail(h, t);
1534 }
1535
1536 private boolean casHead(Node<E> cmp, Node<E> val) {
1537 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
1538 }
1539
1540 private boolean casTail(Node<E> cmp, Node<E> val) {
1541 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
1542 }
1543
1544 // Unsafe mechanics
1545
1546 private static final sun.misc.Unsafe UNSAFE;
1547 private static final long headOffset;
1548 private static final long tailOffset;
1549 static {
1550 PREV_TERMINATOR = new Node<Object>();
1551 PREV_TERMINATOR.next = PREV_TERMINATOR;
1552 NEXT_TERMINATOR = new Node<Object>();
1553 NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1554 try {
1555 UNSAFE = sun.misc.Unsafe.getUnsafe();
1556 Class<?> k = ConcurrentLinkedDeque.class;
1557 headOffset = UNSAFE.objectFieldOffset
1558 (k.getDeclaredField("head"));
1559 tailOffset = UNSAFE.objectFieldOffset
1560 (k.getDeclaredField("tail"));
1561 } catch (Exception e) {
1562 throw new Error(e);
1563 }
1564 }
1565 }