ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.6
Committed: Sat Sep 11 18:56:18 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.5: +8 -1 lines
Log Message:
Clarify linearization point of element insertion

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