ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.59
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.58: +2 -2 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

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.4 UNSAFE.putObject(this, itemOffset, item);
275 jsr166 1.1 }
276    
277     boolean casItem(E cmp, E val) {
278     return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
279     }
280    
281     void lazySetNext(Node<E> val) {
282     UNSAFE.putOrderedObject(this, nextOffset, val);
283     }
284    
285     boolean casNext(Node<E> cmp, Node<E> val) {
286     return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
287     }
288    
289     void lazySetPrev(Node<E> val) {
290     UNSAFE.putOrderedObject(this, prevOffset, val);
291     }
292    
293     boolean casPrev(Node<E> cmp, Node<E> val) {
294     return UNSAFE.compareAndSwapObject(this, prevOffset, cmp, val);
295     }
296    
297     // Unsafe mechanics
298 dl 1.24
299 dl 1.23 private static final sun.misc.Unsafe UNSAFE;
300     private static final long prevOffset;
301     private static final long itemOffset;
302     private static final long nextOffset;
303    
304     static {
305     try {
306     UNSAFE = sun.misc.Unsafe.getUnsafe();
307 jsr166 1.28 Class<?> k = Node.class;
308 dl 1.23 prevOffset = UNSAFE.objectFieldOffset
309     (k.getDeclaredField("prev"));
310     itemOffset = UNSAFE.objectFieldOffset
311     (k.getDeclaredField("item"));
312     nextOffset = UNSAFE.objectFieldOffset
313     (k.getDeclaredField("next"));
314 jsr166 1.59 } catch (ReflectiveOperationException e) {
315 dl 1.23 throw new Error(e);
316     }
317     }
318 jsr166 1.1 }
319    
320     /**
321     * Links e as first element.
322     */
323     private void linkFirst(E e) {
324     checkNotNull(e);
325     final Node<E> newNode = new Node<E>(e);
326    
327 jsr166 1.7 restartFromHead:
328 jsr166 1.15 for (;;)
329     for (Node<E> h = head, p = h, q;;) {
330     if ((q = p.prev) != null &&
331     (q = (p = q).prev) != null)
332     // Check for head updates every other hop.
333     // If p == q, we are sure to follow head instead.
334     p = (h != (h = head)) ? h : q;
335     else if (p.next == p) // PREV_TERMINATOR
336     continue restartFromHead;
337     else {
338 jsr166 1.3 // p is first node
339 jsr166 1.1 newNode.lazySetNext(p); // CAS piggyback
340     if (p.casPrev(null, newNode)) {
341 jsr166 1.6 // Successful CAS is the linearization point
342     // for e to become an element of this deque,
343     // and for newNode to become "live".
344 jsr166 1.1 if (p != h) // hop two nodes at a time
345 jsr166 1.10 casHead(h, newNode); // Failure is OK.
346 jsr166 1.1 return;
347     }
348 jsr166 1.11 // Lost CAS race to another thread; re-read prev
349 jsr166 1.1 }
350     }
351     }
352    
353     /**
354     * Links e as last element.
355     */
356     private void linkLast(E e) {
357     checkNotNull(e);
358     final Node<E> newNode = new Node<E>(e);
359    
360 jsr166 1.7 restartFromTail:
361 jsr166 1.15 for (;;)
362     for (Node<E> t = tail, p = t, q;;) {
363     if ((q = p.next) != null &&
364     (q = (p = q).next) != null)
365     // Check for tail updates every other hop.
366     // If p == q, we are sure to follow tail instead.
367     p = (t != (t = tail)) ? t : q;
368     else if (p.prev == p) // NEXT_TERMINATOR
369     continue restartFromTail;
370     else {
371 jsr166 1.3 // p is last node
372 jsr166 1.1 newNode.lazySetPrev(p); // CAS piggyback
373     if (p.casNext(null, newNode)) {
374 jsr166 1.6 // Successful CAS is the linearization point
375     // for e to become an element of this deque,
376     // and for newNode to become "live".
377 jsr166 1.1 if (p != t) // hop two nodes at a time
378 jsr166 1.10 casTail(t, newNode); // Failure is OK.
379 jsr166 1.1 return;
380     }
381 jsr166 1.11 // Lost CAS race to another thread; re-read next
382 jsr166 1.1 }
383     }
384     }
385    
386 jsr166 1.18 private static final int HOPS = 2;
387 jsr166 1.1
388     /**
389     * Unlinks non-null node x.
390     */
391     void unlink(Node<E> x) {
392 jsr166 1.3 // assert x != null;
393     // assert x.item == null;
394     // assert x != PREV_TERMINATOR;
395     // assert x != NEXT_TERMINATOR;
396 jsr166 1.1
397     final Node<E> prev = x.prev;
398     final Node<E> next = x.next;
399     if (prev == null) {
400     unlinkFirst(x, next);
401     } else if (next == null) {
402     unlinkLast(x, prev);
403     } else {
404     // Unlink interior node.
405     //
406     // This is the common case, since a series of polls at the
407     // same end will be "interior" removes, except perhaps for
408 jsr166 1.3 // the first one, since end nodes cannot be unlinked.
409 jsr166 1.1 //
410     // At any time, all active nodes are mutually reachable by
411     // following a sequence of either next or prev pointers.
412     //
413     // Our strategy is to find the unique active predecessor
414     // and successor of x. Try to fix up their links so that
415     // they point to each other, leaving x unreachable from
416     // active nodes. If successful, and if x has no live
417 jsr166 1.3 // predecessor/successor, we additionally try to gc-unlink,
418     // leaving active nodes unreachable from x, by rechecking
419     // that the status of predecessor and successor are
420     // unchanged and ensuring that x is not reachable from
421     // tail/head, before setting x's prev/next links to their
422     // logical approximate replacements, self/TERMINATOR.
423 jsr166 1.1 Node<E> activePred, activeSucc;
424     boolean isFirst, isLast;
425     int hops = 1;
426    
427     // Find active predecessor
428 jsr166 1.3 for (Node<E> p = prev; ; ++hops) {
429 jsr166 1.1 if (p.item != null) {
430     activePred = p;
431     isFirst = false;
432     break;
433     }
434     Node<E> q = p.prev;
435     if (q == null) {
436 jsr166 1.3 if (p.next == p)
437 jsr166 1.1 return;
438     activePred = p;
439     isFirst = true;
440     break;
441     }
442     else if (p == q)
443     return;
444     else
445     p = q;
446     }
447    
448     // Find active successor
449 jsr166 1.3 for (Node<E> p = next; ; ++hops) {
450 jsr166 1.1 if (p.item != null) {
451     activeSucc = p;
452     isLast = false;
453     break;
454     }
455     Node<E> q = p.next;
456     if (q == null) {
457 jsr166 1.3 if (p.prev == p)
458 jsr166 1.1 return;
459     activeSucc = p;
460     isLast = true;
461     break;
462     }
463     else if (p == q)
464     return;
465     else
466     p = q;
467     }
468    
469     // TODO: better HOP heuristics
470     if (hops < HOPS
471     // always squeeze out interior deleted nodes
472     && (isFirst | isLast))
473     return;
474    
475     // Squeeze out deleted nodes between activePred and
476     // activeSucc, including x.
477     skipDeletedSuccessors(activePred);
478     skipDeletedPredecessors(activeSucc);
479    
480     // Try to gc-unlink, if possible
481     if ((isFirst | isLast) &&
482    
483     // Recheck expected state of predecessor and successor
484     (activePred.next == activeSucc) &&
485     (activeSucc.prev == activePred) &&
486     (isFirst ? activePred.prev == null : activePred.item != null) &&
487     (isLast ? activeSucc.next == null : activeSucc.item != null)) {
488    
489 jsr166 1.5 updateHead(); // Ensure x is not reachable from head
490     updateTail(); // Ensure x is not reachable from tail
491 jsr166 1.3
492     // Finally, actually gc-unlink
493 jsr166 1.1 x.lazySetPrev(isFirst ? prevTerminator() : x);
494     x.lazySetNext(isLast ? nextTerminator() : x);
495     }
496     }
497     }
498    
499     /**
500     * Unlinks non-null first node.
501     */
502     private void unlinkFirst(Node<E> first, Node<E> next) {
503 jsr166 1.9 // assert first != null;
504     // assert next != null;
505     // assert first.item == null;
506 jsr166 1.15 for (Node<E> o = null, p = next, q;;) {
507 jsr166 1.1 if (p.item != null || (q = p.next) == null) {
508 jsr166 1.15 if (o != null && p.prev != p && first.casNext(next, p)) {
509 jsr166 1.3 skipDeletedPredecessors(p);
510     if (first.prev == null &&
511     (p.next == null || p.item != null) &&
512     p.prev == first) {
513    
514 jsr166 1.5 updateHead(); // Ensure o is not reachable from head
515     updateTail(); // Ensure o is not reachable from tail
516    
517     // Finally, actually gc-unlink
518 jsr166 1.3 o.lazySetNext(o);
519     o.lazySetPrev(prevTerminator());
520 jsr166 1.1 }
521     }
522     return;
523     }
524     else if (p == q)
525     return;
526     else {
527     o = p;
528     p = q;
529     }
530     }
531     }
532    
533     /**
534     * Unlinks non-null last node.
535     */
536     private void unlinkLast(Node<E> last, Node<E> prev) {
537 jsr166 1.9 // assert last != null;
538     // assert prev != null;
539     // assert last.item == null;
540 jsr166 1.15 for (Node<E> o = null, p = prev, q;;) {
541 jsr166 1.1 if (p.item != null || (q = p.prev) == null) {
542 jsr166 1.15 if (o != null && p.next != p && last.casPrev(prev, p)) {
543 jsr166 1.3 skipDeletedSuccessors(p);
544     if (last.next == null &&
545     (p.prev == null || p.item != null) &&
546     p.next == last) {
547    
548 jsr166 1.5 updateHead(); // Ensure o is not reachable from head
549     updateTail(); // Ensure o is not reachable from tail
550    
551     // Finally, actually gc-unlink
552 jsr166 1.3 o.lazySetPrev(o);
553     o.lazySetNext(nextTerminator());
554 jsr166 1.1 }
555     }
556     return;
557     }
558     else if (p == q)
559     return;
560     else {
561     o = p;
562     p = q;
563     }
564     }
565     }
566    
567 jsr166 1.3 /**
568 jsr166 1.15 * Guarantees that any node which was unlinked before a call to
569     * this method will be unreachable from head after it returns.
570     * Does not guarantee to eliminate slack, only that head will
571 jsr166 1.17 * point to a node that was active while this method was running.
572 jsr166 1.3 */
573 jsr166 1.1 private final void updateHead() {
574 jsr166 1.17 // Either head already points to an active node, or we keep
575     // trying to cas it to the first node until it does.
576     Node<E> h, p, q;
577     restartFromHead:
578     while ((h = head).item == null && (p = h.prev) != null) {
579     for (;;) {
580     if ((q = p.prev) == null ||
581     (q = (p = q).prev) == null) {
582     // It is possible that p is PREV_TERMINATOR,
583     // but if so, the CAS is guaranteed to fail.
584     if (casHead(h, p))
585     return;
586     else
587     continue restartFromHead;
588     }
589     else if (h != head)
590     continue restartFromHead;
591     else
592     p = q;
593 jsr166 1.15 }
594     }
595 jsr166 1.1 }
596    
597 jsr166 1.3 /**
598 jsr166 1.15 * Guarantees that any node which was unlinked before a call to
599     * this method will be unreachable from tail after it returns.
600     * Does not guarantee to eliminate slack, only that tail will
601 jsr166 1.17 * point to a node that was active while this method was running.
602 jsr166 1.3 */
603 jsr166 1.1 private final void updateTail() {
604 jsr166 1.17 // Either tail already points to an active node, or we keep
605     // trying to cas it to the last node until it does.
606     Node<E> t, p, q;
607     restartFromTail:
608     while ((t = tail).item == null && (p = t.next) != null) {
609     for (;;) {
610     if ((q = p.next) == null ||
611     (q = (p = q).next) == null) {
612     // It is possible that p is NEXT_TERMINATOR,
613     // but if so, the CAS is guaranteed to fail.
614     if (casTail(t, p))
615     return;
616     else
617     continue restartFromTail;
618     }
619     else if (t != tail)
620     continue restartFromTail;
621     else
622     p = q;
623 jsr166 1.15 }
624     }
625 jsr166 1.1 }
626    
627     private void skipDeletedPredecessors(Node<E> x) {
628     whileActive:
629     do {
630     Node<E> prev = x.prev;
631 jsr166 1.3 // assert prev != null;
632     // assert x != NEXT_TERMINATOR;
633     // assert x != PREV_TERMINATOR;
634 jsr166 1.1 Node<E> p = prev;
635     findActive:
636     for (;;) {
637     if (p.item != null)
638     break findActive;
639     Node<E> q = p.prev;
640     if (q == null) {
641     if (p.next == p)
642     continue whileActive;
643     break findActive;
644     }
645     else if (p == q)
646     continue whileActive;
647     else
648     p = q;
649     }
650    
651     // found active CAS target
652     if (prev == p || x.casPrev(prev, p))
653     return;
654    
655     } while (x.item != null || x.next == null);
656     }
657    
658     private void skipDeletedSuccessors(Node<E> x) {
659     whileActive:
660     do {
661     Node<E> next = x.next;
662 jsr166 1.3 // assert next != null;
663     // assert x != NEXT_TERMINATOR;
664     // assert x != PREV_TERMINATOR;
665 jsr166 1.1 Node<E> p = next;
666     findActive:
667     for (;;) {
668     if (p.item != null)
669     break findActive;
670     Node<E> q = p.next;
671     if (q == null) {
672     if (p.prev == p)
673     continue whileActive;
674     break findActive;
675     }
676     else if (p == q)
677     continue whileActive;
678     else
679     p = q;
680     }
681    
682     // found active CAS target
683     if (next == p || x.casNext(next, p))
684     return;
685    
686     } while (x.item != null || x.prev == null);
687     }
688    
689     /**
690     * Returns the successor of p, or the first node if p.next has been
691     * linked to self, which will only be true if traversing with a
692     * stale pointer that is now off the list.
693     */
694     final Node<E> succ(Node<E> p) {
695     // TODO: should we skip deleted nodes here?
696     Node<E> q = p.next;
697     return (p == q) ? first() : q;
698     }
699    
700     /**
701     * Returns the predecessor of p, or the last node if p.prev has been
702     * linked to self, which will only be true if traversing with a
703     * stale pointer that is now off the list.
704     */
705     final Node<E> pred(Node<E> p) {
706     Node<E> q = p.prev;
707     return (p == q) ? last() : q;
708     }
709    
710     /**
711 jsr166 1.3 * Returns the first node, the unique node p for which:
712     * p.prev == null && p.next != p
713 jsr166 1.1 * The returned node may or may not be logically deleted.
714     * Guarantees that head is set to the returned node.
715     */
716     Node<E> first() {
717 jsr166 1.7 restartFromHead:
718 jsr166 1.15 for (;;)
719     for (Node<E> h = head, p = h, q;;) {
720     if ((q = p.prev) != null &&
721     (q = (p = q).prev) != null)
722     // Check for head updates every other hop.
723     // If p == q, we are sure to follow head instead.
724     p = (h != (h = head)) ? h : q;
725     else if (p == h
726     // It is possible that p is PREV_TERMINATOR,
727     // but if so, the CAS is guaranteed to fail.
728     || casHead(h, p))
729     return p;
730     else
731 jsr166 1.7 continue restartFromHead;
732 jsr166 1.1 }
733     }
734    
735     /**
736 jsr166 1.3 * Returns the last node, the unique node p for which:
737     * p.next == null && p.prev != p
738 jsr166 1.1 * The returned node may or may not be logically deleted.
739     * Guarantees that tail is set to the returned node.
740     */
741     Node<E> last() {
742 jsr166 1.7 restartFromTail:
743 jsr166 1.15 for (;;)
744     for (Node<E> t = tail, p = t, q;;) {
745     if ((q = p.next) != null &&
746     (q = (p = q).next) != null)
747     // Check for tail updates every other hop.
748     // If p == q, we are sure to follow tail instead.
749     p = (t != (t = tail)) ? t : q;
750     else if (p == t
751     // It is possible that p is NEXT_TERMINATOR,
752     // but if so, the CAS is guaranteed to fail.
753     || casTail(t, p))
754     return p;
755     else
756 jsr166 1.7 continue restartFromTail;
757 jsr166 1.1 }
758     }
759    
760     // Minor convenience utilities
761    
762     /**
763     * Throws NullPointerException if argument is null.
764     *
765     * @param v the element
766     */
767     private static void checkNotNull(Object v) {
768     if (v == null)
769     throw new NullPointerException();
770     }
771    
772     /**
773     * Returns element unless it is null, in which case throws
774     * NoSuchElementException.
775     *
776     * @param v the element
777     * @return the element
778     */
779     private E screenNullResult(E v) {
780     if (v == null)
781     throw new NoSuchElementException();
782     return v;
783     }
784    
785     /**
786     * Creates an array list and fills it with elements of this list.
787     * Used by toArray.
788     *
789 jsr166 1.33 * @return the array list
790 jsr166 1.1 */
791     private ArrayList<E> toArrayList() {
792 jsr166 1.3 ArrayList<E> list = new ArrayList<E>();
793 jsr166 1.1 for (Node<E> p = first(); p != null; p = succ(p)) {
794     E item = p.item;
795     if (item != null)
796 jsr166 1.3 list.add(item);
797 jsr166 1.1 }
798 jsr166 1.3 return list;
799 jsr166 1.1 }
800    
801     /**
802     * Constructs an empty deque.
803     */
804 jsr166 1.3 public ConcurrentLinkedDeque() {
805     head = tail = new Node<E>(null);
806     }
807 jsr166 1.1
808     /**
809     * Constructs a deque initially containing the elements of
810     * the given collection, added in traversal order of the
811     * collection's iterator.
812     *
813     * @param c the collection of elements to initially contain
814     * @throws NullPointerException if the specified collection or any
815     * of its elements are null
816     */
817 jsr166 1.3 public ConcurrentLinkedDeque(Collection<? extends E> c) {
818     // Copy c into a private chain of Nodes
819     Node<E> h = null, t = null;
820     for (E e : c) {
821     checkNotNull(e);
822     Node<E> newNode = new Node<E>(e);
823     if (h == null)
824     h = t = newNode;
825     else {
826 jsr166 1.8 t.lazySetNext(newNode);
827     newNode.lazySetPrev(t);
828 jsr166 1.3 t = newNode;
829     }
830     }
831 jsr166 1.9 initHeadTail(h, t);
832     }
833    
834     /**
835     * Initializes head and tail, ensuring invariants hold.
836     */
837     private void initHeadTail(Node<E> h, Node<E> t) {
838     if (h == t) {
839     if (h == null)
840     h = t = new Node<E>(null);
841     else {
842     // Avoid edge case of a single Node with non-null item.
843     Node<E> newNode = new Node<E>(null);
844     t.lazySetNext(newNode);
845     newNode.lazySetPrev(t);
846     t = newNode;
847     }
848     }
849 jsr166 1.3 head = h;
850     tail = t;
851     }
852 jsr166 1.1
853     /**
854     * Inserts the specified element at the front of this deque.
855 jsr166 1.19 * As the deque is unbounded, this method will never throw
856     * {@link IllegalStateException}.
857 jsr166 1.1 *
858 jsr166 1.19 * @throws NullPointerException if the specified element is null
859 jsr166 1.1 */
860     public void addFirst(E e) {
861     linkFirst(e);
862     }
863    
864     /**
865     * Inserts the specified element at the end of this deque.
866 jsr166 1.19 * As the deque is unbounded, this method will never throw
867     * {@link IllegalStateException}.
868 jsr166 1.3 *
869     * <p>This method is equivalent to {@link #add}.
870 jsr166 1.1 *
871 jsr166 1.19 * @throws NullPointerException if the specified element is null
872 jsr166 1.1 */
873     public void addLast(E e) {
874     linkLast(e);
875     }
876    
877     /**
878     * Inserts the specified element at the front of this deque.
879 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
880 jsr166 1.1 *
881 jsr166 1.19 * @return {@code true} (as specified by {@link Deque#offerFirst})
882     * @throws NullPointerException if the specified element is null
883 jsr166 1.1 */
884     public boolean offerFirst(E e) {
885     linkFirst(e);
886     return true;
887     }
888    
889     /**
890     * Inserts the specified element at the end of this deque.
891 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
892 jsr166 1.1 *
893     * <p>This method is equivalent to {@link #add}.
894     *
895 jsr166 1.19 * @return {@code true} (as specified by {@link Deque#offerLast})
896     * @throws NullPointerException if the specified element is null
897 jsr166 1.1 */
898     public boolean offerLast(E e) {
899     linkLast(e);
900     return true;
901     }
902    
903     public E peekFirst() {
904     for (Node<E> p = first(); p != null; p = succ(p)) {
905     E item = p.item;
906     if (item != null)
907     return item;
908     }
909     return null;
910     }
911    
912     public E peekLast() {
913     for (Node<E> p = last(); p != null; p = pred(p)) {
914     E item = p.item;
915     if (item != null)
916     return item;
917     }
918     return null;
919     }
920    
921     /**
922     * @throws NoSuchElementException {@inheritDoc}
923     */
924     public E getFirst() {
925     return screenNullResult(peekFirst());
926     }
927    
928     /**
929     * @throws NoSuchElementException {@inheritDoc}
930     */
931 jsr166 1.21 public E getLast() {
932 jsr166 1.1 return screenNullResult(peekLast());
933     }
934    
935     public E pollFirst() {
936     for (Node<E> p = first(); p != null; p = succ(p)) {
937     E item = p.item;
938     if (item != null && p.casItem(item, null)) {
939     unlink(p);
940     return item;
941     }
942     }
943     return null;
944     }
945    
946     public E pollLast() {
947     for (Node<E> p = last(); p != null; p = pred(p)) {
948     E item = p.item;
949     if (item != null && p.casItem(item, null)) {
950     unlink(p);
951     return item;
952     }
953     }
954     return null;
955     }
956    
957     /**
958     * @throws NoSuchElementException {@inheritDoc}
959     */
960     public E removeFirst() {
961     return screenNullResult(pollFirst());
962     }
963    
964     /**
965     * @throws NoSuchElementException {@inheritDoc}
966     */
967     public E removeLast() {
968     return screenNullResult(pollLast());
969     }
970    
971     // *** Queue and stack methods ***
972    
973     /**
974     * Inserts the specified element at the tail of this deque.
975 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
976 jsr166 1.1 *
977     * @return {@code true} (as specified by {@link Queue#offer})
978     * @throws NullPointerException if the specified element is null
979     */
980     public boolean offer(E e) {
981     return offerLast(e);
982     }
983    
984     /**
985     * Inserts the specified element at the tail of this deque.
986 jsr166 1.19 * As the deque is unbounded, this method will never throw
987     * {@link IllegalStateException} or return {@code false}.
988 jsr166 1.1 *
989     * @return {@code true} (as specified by {@link Collection#add})
990     * @throws NullPointerException if the specified element is null
991     */
992     public boolean add(E e) {
993     return offerLast(e);
994     }
995    
996     public E poll() { return pollFirst(); }
997 jsr166 1.45 public E peek() { return peekFirst(); }
998    
999     /**
1000     * @throws NoSuchElementException {@inheritDoc}
1001     */
1002 jsr166 1.1 public E remove() { return removeFirst(); }
1003 jsr166 1.45
1004     /**
1005     * @throws NoSuchElementException {@inheritDoc}
1006     */
1007     public E pop() { return removeFirst(); }
1008    
1009     /**
1010     * @throws NoSuchElementException {@inheritDoc}
1011     */
1012 jsr166 1.1 public E element() { return getFirst(); }
1013 jsr166 1.45
1014     /**
1015     * @throws NullPointerException {@inheritDoc}
1016     */
1017 jsr166 1.1 public void push(E e) { addFirst(e); }
1018    
1019     /**
1020 jsr166 1.54 * Removes the first occurrence of the specified element from this deque.
1021 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1022 jsr166 1.54 * More formally, removes the first element {@code e} such that
1023     * {@code o.equals(e)} (if such an element exists).
1024     * Returns {@code true} if this deque contained the specified element
1025     * (or equivalently, if this deque changed as a result of the call).
1026 jsr166 1.1 *
1027     * @param o element to be removed from this deque, if present
1028     * @return {@code true} if the deque contained the specified element
1029 jsr166 1.19 * @throws NullPointerException if the specified element is null
1030 jsr166 1.1 */
1031     public boolean removeFirstOccurrence(Object o) {
1032     checkNotNull(o);
1033     for (Node<E> p = first(); p != null; p = succ(p)) {
1034     E item = p.item;
1035     if (item != null && o.equals(item) && p.casItem(item, null)) {
1036     unlink(p);
1037     return true;
1038     }
1039     }
1040     return false;
1041     }
1042    
1043     /**
1044 jsr166 1.54 * Removes the last occurrence of the specified element from this deque.
1045 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1046 jsr166 1.54 * More formally, removes the last element {@code e} such that
1047     * {@code o.equals(e)} (if such an element exists).
1048     * Returns {@code true} if this deque contained the specified element
1049     * (or equivalently, if this deque changed as a result of the call).
1050 jsr166 1.1 *
1051     * @param o element to be removed from this deque, if present
1052     * @return {@code true} if the deque contained the specified element
1053 jsr166 1.19 * @throws NullPointerException if the specified element is null
1054 jsr166 1.1 */
1055     public boolean removeLastOccurrence(Object o) {
1056     checkNotNull(o);
1057     for (Node<E> p = last(); p != null; p = pred(p)) {
1058     E item = p.item;
1059     if (item != null && o.equals(item) && p.casItem(item, null)) {
1060     unlink(p);
1061     return true;
1062     }
1063     }
1064     return false;
1065     }
1066    
1067     /**
1068 jsr166 1.54 * Returns {@code true} if this deque contains the specified element.
1069     * More formally, returns {@code true} if and only if this deque contains
1070     * at least one element {@code e} such that {@code o.equals(e)}.
1071 jsr166 1.1 *
1072     * @param o element whose presence in this deque is to be tested
1073     * @return {@code true} if this deque contains the specified element
1074     */
1075     public boolean contains(Object o) {
1076 jsr166 1.52 if (o != null) {
1077     for (Node<E> p = first(); p != null; p = succ(p)) {
1078     E item = p.item;
1079     if (item != null && o.equals(item))
1080     return true;
1081     }
1082 jsr166 1.1 }
1083     return false;
1084     }
1085    
1086     /**
1087     * Returns {@code true} if this collection contains no elements.
1088     *
1089     * @return {@code true} if this collection contains no elements
1090     */
1091     public boolean isEmpty() {
1092     return peekFirst() == null;
1093     }
1094    
1095     /**
1096     * Returns the number of elements in this deque. If this deque
1097     * contains more than {@code Integer.MAX_VALUE} elements, it
1098     * returns {@code Integer.MAX_VALUE}.
1099     *
1100     * <p>Beware that, unlike in most collections, this method is
1101     * <em>NOT</em> a constant-time operation. Because of the
1102     * asynchronous nature of these deques, determining the current
1103     * number of elements requires traversing them all to count them.
1104     * Additionally, it is possible for the size to change during
1105     * execution of this method, in which case the returned result
1106     * will be inaccurate. Thus, this method is typically not very
1107     * useful in concurrent applications.
1108     *
1109     * @return the number of elements in this deque
1110     */
1111     public int size() {
1112 jsr166 1.51 restartFromHead: for (;;) {
1113     int count = 0;
1114     for (Node<E> p = first(); p != null;) {
1115     if (p.item != null)
1116     if (++count == Integer.MAX_VALUE)
1117     break; // @see Collection.size()
1118     Node<E> next = p.next;
1119     if (p == next)
1120     continue restartFromHead;
1121     p = next;
1122     }
1123     return count;
1124     }
1125 jsr166 1.1 }
1126    
1127     /**
1128 jsr166 1.54 * Removes the first occurrence of the specified element from this deque.
1129 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1130 jsr166 1.54 * More formally, removes the first element {@code e} such that
1131     * {@code o.equals(e)} (if such an element exists).
1132     * Returns {@code true} if this deque contained the specified element
1133     * (or equivalently, if this deque changed as a result of the call).
1134     *
1135     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1136 jsr166 1.1 *
1137     * @param o element to be removed from this deque, if present
1138     * @return {@code true} if the deque contained the specified element
1139 jsr166 1.19 * @throws NullPointerException if the specified element is null
1140 jsr166 1.1 */
1141     public boolean remove(Object o) {
1142     return removeFirstOccurrence(o);
1143     }
1144    
1145     /**
1146     * Appends all of the elements in the specified collection to the end of
1147     * this deque, in the order that they are returned by the specified
1148 jsr166 1.3 * collection's iterator. Attempts to {@code addAll} of a deque to
1149     * itself result in {@code IllegalArgumentException}.
1150 jsr166 1.1 *
1151     * @param c the elements to be inserted into this deque
1152     * @return {@code true} if this deque changed as a result of the call
1153 jsr166 1.3 * @throws NullPointerException if the specified collection or any
1154     * of its elements are null
1155     * @throws IllegalArgumentException if the collection is this deque
1156 jsr166 1.1 */
1157     public boolean addAll(Collection<? extends E> c) {
1158 jsr166 1.3 if (c == this)
1159     // As historically specified in AbstractQueue#addAll
1160     throw new IllegalArgumentException();
1161    
1162     // Copy c into a private chain of Nodes
1163 jsr166 1.14 Node<E> beginningOfTheEnd = null, last = null;
1164 jsr166 1.3 for (E e : c) {
1165     checkNotNull(e);
1166     Node<E> newNode = new Node<E>(e);
1167 jsr166 1.14 if (beginningOfTheEnd == null)
1168     beginningOfTheEnd = last = newNode;
1169 jsr166 1.3 else {
1170 jsr166 1.8 last.lazySetNext(newNode);
1171     newNode.lazySetPrev(last);
1172 jsr166 1.3 last = newNode;
1173     }
1174     }
1175 jsr166 1.14 if (beginningOfTheEnd == null)
1176 jsr166 1.1 return false;
1177 jsr166 1.3
1178 jsr166 1.14 // Atomically append the chain at the tail of this collection
1179 jsr166 1.7 restartFromTail:
1180 jsr166 1.15 for (;;)
1181     for (Node<E> t = tail, p = t, q;;) {
1182     if ((q = p.next) != null &&
1183     (q = (p = q).next) != null)
1184     // Check for tail updates every other hop.
1185     // If p == q, we are sure to follow tail instead.
1186     p = (t != (t = tail)) ? t : q;
1187     else if (p.prev == p) // NEXT_TERMINATOR
1188     continue restartFromTail;
1189     else {
1190 jsr166 1.3 // p is last node
1191 jsr166 1.14 beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
1192     if (p.casNext(null, beginningOfTheEnd)) {
1193     // Successful CAS is the linearization point
1194 jsr166 1.20 // for all elements to be added to this deque.
1195 jsr166 1.14 if (!casTail(t, last)) {
1196 jsr166 1.3 // Try a little harder to update tail,
1197     // since we may be adding many elements.
1198     t = tail;
1199     if (last.next == null)
1200     casTail(t, last);
1201     }
1202     return true;
1203     }
1204 jsr166 1.11 // Lost CAS race to another thread; re-read next
1205 jsr166 1.3 }
1206     }
1207 jsr166 1.1 }
1208    
1209     /**
1210     * Removes all of the elements from this deque.
1211     */
1212     public void clear() {
1213     while (pollFirst() != null)
1214     ;
1215     }
1216    
1217     /**
1218     * Returns an array containing all of the elements in this deque, in
1219     * proper sequence (from first to last element).
1220     *
1221     * <p>The returned array will be "safe" in that no references to it are
1222     * maintained by this deque. (In other words, this method must allocate
1223     * a new array). The caller is thus free to modify the returned array.
1224     *
1225     * <p>This method acts as bridge between array-based and collection-based
1226     * APIs.
1227     *
1228     * @return an array containing all of the elements in this deque
1229     */
1230     public Object[] toArray() {
1231     return toArrayList().toArray();
1232     }
1233    
1234     /**
1235     * Returns an array containing all of the elements in this deque,
1236     * in proper sequence (from first to last element); the runtime
1237     * type of the returned array is that of the specified array. If
1238     * the deque fits in the specified array, it is returned therein.
1239     * Otherwise, a new array is allocated with the runtime type of
1240     * the specified array and the size of this deque.
1241     *
1242     * <p>If this deque fits in the specified array with room to spare
1243     * (i.e., the array has more elements than this deque), the element in
1244     * the array immediately following the end of the deque is set to
1245     * {@code null}.
1246     *
1247 jsr166 1.3 * <p>Like the {@link #toArray()} method, this method acts as
1248     * bridge between array-based and collection-based APIs. Further,
1249     * this method allows precise control over the runtime type of the
1250     * output array, and may, under certain circumstances, be used to
1251     * save allocation costs.
1252 jsr166 1.1 *
1253     * <p>Suppose {@code x} is a deque known to contain only strings.
1254     * The following code can be used to dump the deque into a newly
1255     * allocated array of {@code String}:
1256     *
1257 jsr166 1.29 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1258 jsr166 1.1 *
1259     * Note that {@code toArray(new Object[0])} is identical in function to
1260     * {@code toArray()}.
1261     *
1262     * @param a the array into which the elements of the deque are to
1263     * be stored, if it is big enough; otherwise, a new array of the
1264     * same runtime type is allocated for this purpose
1265     * @return an array containing all of the elements in this deque
1266     * @throws ArrayStoreException if the runtime type of the specified array
1267     * is not a supertype of the runtime type of every element in
1268     * this deque
1269     * @throws NullPointerException if the specified array is null
1270     */
1271     public <T> T[] toArray(T[] a) {
1272     return toArrayList().toArray(a);
1273     }
1274    
1275     /**
1276     * Returns an iterator over the elements in this deque in proper sequence.
1277     * The elements will be returned in order from first (head) to last (tail).
1278     *
1279 jsr166 1.50 * <p>The returned iterator is
1280     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1281 jsr166 1.1 *
1282     * @return an iterator over the elements in this deque in proper sequence
1283     */
1284     public Iterator<E> iterator() {
1285     return new Itr();
1286     }
1287    
1288     /**
1289     * Returns an iterator over the elements in this deque in reverse
1290     * sequential order. The elements will be returned in order from
1291     * last (tail) to first (head).
1292     *
1293 jsr166 1.50 * <p>The returned iterator is
1294     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1295 jsr166 1.3 *
1296     * @return an iterator over the elements in this deque in reverse order
1297 jsr166 1.1 */
1298     public Iterator<E> descendingIterator() {
1299     return new DescendingItr();
1300     }
1301    
1302     private abstract class AbstractItr implements Iterator<E> {
1303     /**
1304     * Next node to return item for.
1305     */
1306     private Node<E> nextNode;
1307    
1308     /**
1309     * nextItem holds on to item fields because once we claim
1310     * that an element exists in hasNext(), we must return it in
1311     * the following next() call even if it was in the process of
1312     * being removed when hasNext() was called.
1313     */
1314     private E nextItem;
1315    
1316     /**
1317     * Node returned by most recent call to next. Needed by remove.
1318     * Reset to null if this element is deleted by a call to remove.
1319     */
1320     private Node<E> lastRet;
1321    
1322     abstract Node<E> startNode();
1323     abstract Node<E> nextNode(Node<E> p);
1324    
1325     AbstractItr() {
1326     advance();
1327     }
1328    
1329     /**
1330     * Sets nextNode and nextItem to next valid node, or to null
1331     * if no such.
1332     */
1333     private void advance() {
1334     lastRet = nextNode;
1335    
1336     Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1337     for (;; p = nextNode(p)) {
1338     if (p == null) {
1339 jsr166 1.56 // might be at active end or TERMINATOR node; both are OK
1340 jsr166 1.1 nextNode = null;
1341     nextItem = null;
1342     break;
1343     }
1344     E item = p.item;
1345     if (item != null) {
1346     nextNode = p;
1347     nextItem = item;
1348     break;
1349     }
1350     }
1351     }
1352    
1353     public boolean hasNext() {
1354     return nextItem != null;
1355     }
1356    
1357     public E next() {
1358     E item = nextItem;
1359     if (item == null) throw new NoSuchElementException();
1360     advance();
1361     return item;
1362     }
1363    
1364     public void remove() {
1365     Node<E> l = lastRet;
1366     if (l == null) throw new IllegalStateException();
1367     l.item = null;
1368     unlink(l);
1369     lastRet = null;
1370     }
1371     }
1372    
1373     /** Forward iterator */
1374     private class Itr extends AbstractItr {
1375     Node<E> startNode() { return first(); }
1376     Node<E> nextNode(Node<E> p) { return succ(p); }
1377     }
1378    
1379     /** Descending iterator */
1380     private class DescendingItr extends AbstractItr {
1381     Node<E> startNode() { return last(); }
1382     Node<E> nextNode(Node<E> p) { return pred(p); }
1383     }
1384    
1385 dl 1.39 /** A customized variant of Spliterators.IteratorSpliterator */
1386 dl 1.35 static final class CLDSpliterator<E> implements Spliterator<E> {
1387 dl 1.42 static final int MAX_BATCH = 1 << 25; // max batch array size;
1388 dl 1.35 final ConcurrentLinkedDeque<E> queue;
1389     Node<E> current; // current node; null until initialized
1390     int batch; // batch size for splits
1391     boolean exhausted; // true when no more nodes
1392     CLDSpliterator(ConcurrentLinkedDeque<E> queue) {
1393     this.queue = queue;
1394     }
1395    
1396     public Spliterator<E> trySplit() {
1397 dl 1.42 Node<E> p;
1398 dl 1.35 final ConcurrentLinkedDeque<E> q = this.queue;
1399 dl 1.42 int b = batch;
1400     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1401 jsr166 1.40 if (!exhausted &&
1402 dl 1.37 ((p = current) != null || (p = q.first()) != null)) {
1403     if (p.item == null && p == (p = p.next))
1404     current = p = q.first();
1405 dl 1.42 if (p != null && p.next != null) {
1406 dl 1.46 Object[] a = new Object[n];
1407 dl 1.37 int i = 0;
1408     do {
1409     if ((a[i] = p.item) != null)
1410     ++i;
1411     if (p == (p = p.next))
1412     p = q.first();
1413     } while (p != null && i < n);
1414     if ((current = p) == null)
1415     exhausted = true;
1416 dl 1.42 if (i > 0) {
1417     batch = i;
1418     return Spliterators.spliterator
1419     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
1420     Spliterator.CONCURRENT);
1421     }
1422 dl 1.37 }
1423 dl 1.35 }
1424     return null;
1425     }
1426    
1427 dl 1.43 public void forEachRemaining(Consumer<? super E> action) {
1428 dl 1.35 Node<E> p;
1429     if (action == null) throw new NullPointerException();
1430     final ConcurrentLinkedDeque<E> q = this.queue;
1431     if (!exhausted &&
1432     ((p = current) != null || (p = q.first()) != null)) {
1433     exhausted = true;
1434     do {
1435     E e = p.item;
1436     if (p == (p = p.next))
1437     p = q.first();
1438     if (e != null)
1439     action.accept(e);
1440     } while (p != null);
1441     }
1442     }
1443    
1444     public boolean tryAdvance(Consumer<? super E> action) {
1445     Node<E> p;
1446     if (action == null) throw new NullPointerException();
1447     final ConcurrentLinkedDeque<E> q = this.queue;
1448     if (!exhausted &&
1449     ((p = current) != null || (p = q.first()) != null)) {
1450     E e;
1451     do {
1452     e = p.item;
1453     if (p == (p = p.next))
1454     p = q.first();
1455     } while (e == null && p != null);
1456     if ((current = p) == null)
1457     exhausted = true;
1458     if (e != null) {
1459     action.accept(e);
1460     return true;
1461     }
1462     }
1463     return false;
1464     }
1465    
1466 dl 1.36 public long estimateSize() { return Long.MAX_VALUE; }
1467    
1468 dl 1.35 public int characteristics() {
1469     return Spliterator.ORDERED | Spliterator.NONNULL |
1470     Spliterator.CONCURRENT;
1471     }
1472     }
1473    
1474 jsr166 1.49 /**
1475     * Returns a {@link Spliterator} over the elements in this deque.
1476     *
1477 jsr166 1.50 * <p>The returned spliterator is
1478     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1479     *
1480 jsr166 1.49 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1481     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1482     *
1483     * @implNote
1484     * The {@code Spliterator} implements {@code trySplit} to permit limited
1485     * parallelism.
1486     *
1487     * @return a {@code Spliterator} over the elements in this deque
1488     * @since 1.8
1489     */
1490 dl 1.38 public Spliterator<E> spliterator() {
1491 dl 1.35 return new CLDSpliterator<E>(this);
1492 dl 1.34 }
1493    
1494 jsr166 1.1 /**
1495 jsr166 1.31 * Saves this deque to a stream (that is, serializes it).
1496 jsr166 1.1 *
1497 jsr166 1.47 * @param s the stream
1498 jsr166 1.48 * @throws java.io.IOException if an I/O error occurs
1499 jsr166 1.1 * @serialData All of the elements (each an {@code E}) in
1500     * the proper order, followed by a null
1501     */
1502     private void writeObject(java.io.ObjectOutputStream s)
1503     throws java.io.IOException {
1504    
1505     // Write out any hidden stuff
1506     s.defaultWriteObject();
1507    
1508     // Write out all elements in the proper order.
1509     for (Node<E> p = first(); p != null; p = succ(p)) {
1510 jsr166 1.14 E item = p.item;
1511 jsr166 1.1 if (item != null)
1512     s.writeObject(item);
1513     }
1514    
1515     // Use trailing null as sentinel
1516     s.writeObject(null);
1517     }
1518    
1519     /**
1520 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1521 jsr166 1.47 * @param s the stream
1522 jsr166 1.48 * @throws ClassNotFoundException if the class of a serialized object
1523     * could not be found
1524     * @throws java.io.IOException if an I/O error occurs
1525 jsr166 1.1 */
1526     private void readObject(java.io.ObjectInputStream s)
1527     throws java.io.IOException, ClassNotFoundException {
1528     s.defaultReadObject();
1529 jsr166 1.3
1530     // Read in elements until trailing null sentinel found
1531     Node<E> h = null, t = null;
1532 jsr166 1.53 for (Object item; (item = s.readObject()) != null; ) {
1533 jsr166 1.1 @SuppressWarnings("unchecked")
1534 jsr166 1.3 Node<E> newNode = new Node<E>((E) item);
1535     if (h == null)
1536     h = t = newNode;
1537     else {
1538 jsr166 1.8 t.lazySetNext(newNode);
1539     newNode.lazySetPrev(t);
1540 jsr166 1.3 t = newNode;
1541     }
1542 jsr166 1.1 }
1543 jsr166 1.9 initHeadTail(h, t);
1544 jsr166 1.1 }
1545    
1546     private boolean casHead(Node<E> cmp, Node<E> val) {
1547     return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
1548     }
1549    
1550     private boolean casTail(Node<E> cmp, Node<E> val) {
1551     return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
1552     }
1553    
1554 dl 1.23 // Unsafe mechanics
1555    
1556     private static final sun.misc.Unsafe UNSAFE;
1557     private static final long headOffset;
1558     private static final long tailOffset;
1559     static {
1560     PREV_TERMINATOR = new Node<Object>();
1561     PREV_TERMINATOR.next = PREV_TERMINATOR;
1562     NEXT_TERMINATOR = new Node<Object>();
1563     NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1564 jsr166 1.1 try {
1565 dl 1.23 UNSAFE = sun.misc.Unsafe.getUnsafe();
1566 jsr166 1.28 Class<?> k = ConcurrentLinkedDeque.class;
1567 dl 1.23 headOffset = UNSAFE.objectFieldOffset
1568     (k.getDeclaredField("head"));
1569     tailOffset = UNSAFE.objectFieldOffset
1570     (k.getDeclaredField("tail"));
1571 jsr166 1.59 } catch (ReflectiveOperationException e) {
1572 dl 1.23 throw new Error(e);
1573 jsr166 1.1 }
1574     }
1575     }