ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.34
Committed: Sun Feb 17 23:36:34 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.33: +19 -0 lines
Log Message:
Spliterator sync

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