ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.62
Committed: Wed Feb 18 06:39:40 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.61: +1 -3 lines
Log Message:
use "standard" if (p == (p = p.next)) idiom

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