ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.24
Committed: Wed Feb 23 15:57:48 2011 UTC (13 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.23: +1 -1 lines
Log Message:
Whitespace

File Contents

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