ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.63
Committed: Fri Feb 20 03:09:08 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.62: +76 -19 lines
Log Message:
improve toArray and toString implementations

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 jsr166 1.63 import java.util.Arrays;
11 jsr166 1.1 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     * Constructs an empty deque.
785     */
786 jsr166 1.3 public ConcurrentLinkedDeque() {
787     head = tail = new Node<E>(null);
788     }
789 jsr166 1.1
790     /**
791     * Constructs a deque initially containing the elements of
792     * the given collection, added in traversal order of the
793     * collection's iterator.
794     *
795     * @param c the collection of elements to initially contain
796     * @throws NullPointerException if the specified collection or any
797     * of its elements are null
798     */
799 jsr166 1.3 public ConcurrentLinkedDeque(Collection<? extends E> c) {
800     // Copy c into a private chain of Nodes
801     Node<E> h = null, t = null;
802     for (E e : c) {
803     checkNotNull(e);
804     Node<E> newNode = new Node<E>(e);
805     if (h == null)
806     h = t = newNode;
807     else {
808 jsr166 1.8 t.lazySetNext(newNode);
809     newNode.lazySetPrev(t);
810 jsr166 1.3 t = newNode;
811     }
812     }
813 jsr166 1.9 initHeadTail(h, t);
814     }
815    
816     /**
817     * Initializes head and tail, ensuring invariants hold.
818     */
819     private void initHeadTail(Node<E> h, Node<E> t) {
820     if (h == t) {
821     if (h == null)
822     h = t = new Node<E>(null);
823     else {
824     // Avoid edge case of a single Node with non-null item.
825     Node<E> newNode = new Node<E>(null);
826     t.lazySetNext(newNode);
827     newNode.lazySetPrev(t);
828     t = newNode;
829     }
830     }
831 jsr166 1.3 head = h;
832     tail = t;
833     }
834 jsr166 1.1
835     /**
836     * Inserts the specified element at the front of this deque.
837 jsr166 1.19 * As the deque is unbounded, this method will never throw
838     * {@link IllegalStateException}.
839 jsr166 1.1 *
840 jsr166 1.19 * @throws NullPointerException if the specified element is null
841 jsr166 1.1 */
842     public void addFirst(E e) {
843     linkFirst(e);
844     }
845    
846     /**
847     * Inserts the specified element at the end of this deque.
848 jsr166 1.19 * As the deque is unbounded, this method will never throw
849     * {@link IllegalStateException}.
850 jsr166 1.3 *
851     * <p>This method is equivalent to {@link #add}.
852 jsr166 1.1 *
853 jsr166 1.19 * @throws NullPointerException if the specified element is null
854 jsr166 1.1 */
855     public void addLast(E e) {
856     linkLast(e);
857     }
858    
859     /**
860     * Inserts the specified element at the front of this deque.
861 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
862 jsr166 1.1 *
863 jsr166 1.19 * @return {@code true} (as specified by {@link Deque#offerFirst})
864     * @throws NullPointerException if the specified element is null
865 jsr166 1.1 */
866     public boolean offerFirst(E e) {
867     linkFirst(e);
868     return true;
869     }
870    
871     /**
872     * Inserts the specified element at the end of this deque.
873 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
874 jsr166 1.1 *
875     * <p>This method is equivalent to {@link #add}.
876     *
877 jsr166 1.19 * @return {@code true} (as specified by {@link Deque#offerLast})
878     * @throws NullPointerException if the specified element is null
879 jsr166 1.1 */
880     public boolean offerLast(E e) {
881     linkLast(e);
882     return true;
883     }
884    
885     public E peekFirst() {
886     for (Node<E> p = first(); p != null; p = succ(p)) {
887     E item = p.item;
888     if (item != null)
889     return item;
890     }
891     return null;
892     }
893    
894     public E peekLast() {
895     for (Node<E> p = last(); p != null; p = pred(p)) {
896     E item = p.item;
897     if (item != null)
898     return item;
899     }
900     return null;
901     }
902    
903     /**
904     * @throws NoSuchElementException {@inheritDoc}
905     */
906     public E getFirst() {
907     return screenNullResult(peekFirst());
908     }
909    
910     /**
911     * @throws NoSuchElementException {@inheritDoc}
912     */
913 jsr166 1.21 public E getLast() {
914 jsr166 1.1 return screenNullResult(peekLast());
915     }
916    
917     public E pollFirst() {
918     for (Node<E> p = first(); p != null; p = succ(p)) {
919     E item = p.item;
920     if (item != null && p.casItem(item, null)) {
921     unlink(p);
922     return item;
923     }
924     }
925     return null;
926     }
927    
928     public E pollLast() {
929     for (Node<E> p = last(); p != null; p = pred(p)) {
930     E item = p.item;
931     if (item != null && p.casItem(item, null)) {
932     unlink(p);
933     return item;
934     }
935     }
936     return null;
937     }
938    
939     /**
940     * @throws NoSuchElementException {@inheritDoc}
941     */
942     public E removeFirst() {
943     return screenNullResult(pollFirst());
944     }
945    
946     /**
947     * @throws NoSuchElementException {@inheritDoc}
948     */
949     public E removeLast() {
950     return screenNullResult(pollLast());
951     }
952    
953     // *** Queue and stack methods ***
954    
955     /**
956     * Inserts the specified element at the tail of this deque.
957 jsr166 1.19 * As the deque is unbounded, this method will never return {@code false}.
958 jsr166 1.1 *
959     * @return {@code true} (as specified by {@link Queue#offer})
960     * @throws NullPointerException if the specified element is null
961     */
962     public boolean offer(E e) {
963     return offerLast(e);
964     }
965    
966     /**
967     * Inserts the specified element at the tail of this deque.
968 jsr166 1.19 * As the deque is unbounded, this method will never throw
969     * {@link IllegalStateException} or return {@code false}.
970 jsr166 1.1 *
971     * @return {@code true} (as specified by {@link Collection#add})
972     * @throws NullPointerException if the specified element is null
973     */
974     public boolean add(E e) {
975     return offerLast(e);
976     }
977    
978     public E poll() { return pollFirst(); }
979 jsr166 1.45 public E peek() { return peekFirst(); }
980    
981     /**
982     * @throws NoSuchElementException {@inheritDoc}
983     */
984 jsr166 1.1 public E remove() { return removeFirst(); }
985 jsr166 1.45
986     /**
987     * @throws NoSuchElementException {@inheritDoc}
988     */
989     public E pop() { return removeFirst(); }
990    
991     /**
992     * @throws NoSuchElementException {@inheritDoc}
993     */
994 jsr166 1.1 public E element() { return getFirst(); }
995 jsr166 1.45
996     /**
997     * @throws NullPointerException {@inheritDoc}
998     */
999 jsr166 1.1 public void push(E e) { addFirst(e); }
1000    
1001     /**
1002 jsr166 1.54 * Removes the first occurrence of the specified element from this deque.
1003 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1004 jsr166 1.54 * More formally, removes the first element {@code e} such that
1005     * {@code o.equals(e)} (if such an element exists).
1006     * Returns {@code true} if this deque contained the specified element
1007     * (or equivalently, if this deque changed as a result of the call).
1008 jsr166 1.1 *
1009     * @param o element to be removed from this deque, if present
1010     * @return {@code true} if the deque contained the specified element
1011 jsr166 1.19 * @throws NullPointerException if the specified element is null
1012 jsr166 1.1 */
1013     public boolean removeFirstOccurrence(Object o) {
1014     checkNotNull(o);
1015     for (Node<E> p = first(); p != null; p = succ(p)) {
1016     E item = p.item;
1017     if (item != null && o.equals(item) && p.casItem(item, null)) {
1018     unlink(p);
1019     return true;
1020     }
1021     }
1022     return false;
1023     }
1024    
1025     /**
1026 jsr166 1.54 * Removes the last occurrence of the specified element from this deque.
1027 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1028 jsr166 1.54 * More formally, removes the last element {@code e} such that
1029     * {@code o.equals(e)} (if such an element exists).
1030     * Returns {@code true} if this deque contained the specified element
1031     * (or equivalently, if this deque changed as a result of the call).
1032 jsr166 1.1 *
1033     * @param o element to be removed from this deque, if present
1034     * @return {@code true} if the deque contained the specified element
1035 jsr166 1.19 * @throws NullPointerException if the specified element is null
1036 jsr166 1.1 */
1037     public boolean removeLastOccurrence(Object o) {
1038     checkNotNull(o);
1039     for (Node<E> p = last(); p != null; p = pred(p)) {
1040     E item = p.item;
1041     if (item != null && o.equals(item) && p.casItem(item, null)) {
1042     unlink(p);
1043     return true;
1044     }
1045     }
1046     return false;
1047     }
1048    
1049     /**
1050 jsr166 1.54 * Returns {@code true} if this deque contains the specified element.
1051     * More formally, returns {@code true} if and only if this deque contains
1052     * at least one element {@code e} such that {@code o.equals(e)}.
1053 jsr166 1.1 *
1054     * @param o element whose presence in this deque is to be tested
1055     * @return {@code true} if this deque contains the specified element
1056     */
1057     public boolean contains(Object o) {
1058 jsr166 1.52 if (o != null) {
1059     for (Node<E> p = first(); p != null; p = succ(p)) {
1060     E item = p.item;
1061     if (item != null && o.equals(item))
1062     return true;
1063     }
1064 jsr166 1.1 }
1065     return false;
1066     }
1067    
1068     /**
1069     * Returns {@code true} if this collection contains no elements.
1070     *
1071     * @return {@code true} if this collection contains no elements
1072     */
1073     public boolean isEmpty() {
1074     return peekFirst() == null;
1075     }
1076    
1077     /**
1078     * Returns the number of elements in this deque. If this deque
1079     * contains more than {@code Integer.MAX_VALUE} elements, it
1080     * returns {@code Integer.MAX_VALUE}.
1081     *
1082     * <p>Beware that, unlike in most collections, this method is
1083     * <em>NOT</em> a constant-time operation. Because of the
1084     * asynchronous nature of these deques, determining the current
1085     * number of elements requires traversing them all to count them.
1086     * Additionally, it is possible for the size to change during
1087     * execution of this method, in which case the returned result
1088     * will be inaccurate. Thus, this method is typically not very
1089     * useful in concurrent applications.
1090     *
1091     * @return the number of elements in this deque
1092     */
1093     public int size() {
1094 jsr166 1.51 restartFromHead: for (;;) {
1095     int count = 0;
1096     for (Node<E> p = first(); p != null;) {
1097     if (p.item != null)
1098     if (++count == Integer.MAX_VALUE)
1099     break; // @see Collection.size()
1100 jsr166 1.62 if (p == (p = p.next))
1101 jsr166 1.51 continue restartFromHead;
1102     }
1103     return count;
1104     }
1105 jsr166 1.1 }
1106    
1107     /**
1108 jsr166 1.54 * Removes the first occurrence of the specified element from this deque.
1109 jsr166 1.1 * If the deque does not contain the element, it is unchanged.
1110 jsr166 1.54 * More formally, removes the first element {@code e} such that
1111     * {@code o.equals(e)} (if such an element exists).
1112     * Returns {@code true} if this deque contained the specified element
1113     * (or equivalently, if this deque changed as a result of the call).
1114     *
1115     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1116 jsr166 1.1 *
1117     * @param o element to be removed from this deque, if present
1118     * @return {@code true} if the deque contained the specified element
1119 jsr166 1.19 * @throws NullPointerException if the specified element is null
1120 jsr166 1.1 */
1121     public boolean remove(Object o) {
1122     return removeFirstOccurrence(o);
1123     }
1124    
1125     /**
1126     * Appends all of the elements in the specified collection to the end of
1127     * this deque, in the order that they are returned by the specified
1128 jsr166 1.3 * collection's iterator. Attempts to {@code addAll} of a deque to
1129     * itself result in {@code IllegalArgumentException}.
1130 jsr166 1.1 *
1131     * @param c the elements to be inserted into this deque
1132     * @return {@code true} if this deque changed as a result of the call
1133 jsr166 1.3 * @throws NullPointerException if the specified collection or any
1134     * of its elements are null
1135     * @throws IllegalArgumentException if the collection is this deque
1136 jsr166 1.1 */
1137     public boolean addAll(Collection<? extends E> c) {
1138 jsr166 1.3 if (c == this)
1139     // As historically specified in AbstractQueue#addAll
1140     throw new IllegalArgumentException();
1141    
1142     // Copy c into a private chain of Nodes
1143 jsr166 1.14 Node<E> beginningOfTheEnd = null, last = null;
1144 jsr166 1.3 for (E e : c) {
1145     checkNotNull(e);
1146     Node<E> newNode = new Node<E>(e);
1147 jsr166 1.14 if (beginningOfTheEnd == null)
1148     beginningOfTheEnd = last = newNode;
1149 jsr166 1.3 else {
1150 jsr166 1.8 last.lazySetNext(newNode);
1151     newNode.lazySetPrev(last);
1152 jsr166 1.3 last = newNode;
1153     }
1154     }
1155 jsr166 1.14 if (beginningOfTheEnd == null)
1156 jsr166 1.1 return false;
1157 jsr166 1.3
1158 jsr166 1.14 // Atomically append the chain at the tail of this collection
1159 jsr166 1.7 restartFromTail:
1160 jsr166 1.15 for (;;)
1161     for (Node<E> t = tail, p = t, q;;) {
1162     if ((q = p.next) != null &&
1163     (q = (p = q).next) != null)
1164     // Check for tail updates every other hop.
1165     // If p == q, we are sure to follow tail instead.
1166     p = (t != (t = tail)) ? t : q;
1167     else if (p.prev == p) // NEXT_TERMINATOR
1168     continue restartFromTail;
1169     else {
1170 jsr166 1.3 // p is last node
1171 jsr166 1.14 beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
1172     if (p.casNext(null, beginningOfTheEnd)) {
1173     // Successful CAS is the linearization point
1174 jsr166 1.20 // for all elements to be added to this deque.
1175 jsr166 1.14 if (!casTail(t, last)) {
1176 jsr166 1.3 // Try a little harder to update tail,
1177     // since we may be adding many elements.
1178     t = tail;
1179     if (last.next == null)
1180     casTail(t, last);
1181     }
1182     return true;
1183     }
1184 jsr166 1.11 // Lost CAS race to another thread; re-read next
1185 jsr166 1.3 }
1186     }
1187 jsr166 1.1 }
1188    
1189     /**
1190     * Removes all of the elements from this deque.
1191     */
1192     public void clear() {
1193     while (pollFirst() != null)
1194     ;
1195     }
1196    
1197 jsr166 1.63 public String toString() {
1198     String[] a = null;
1199     restartFromHead: for (;;) {
1200     int charLength = 0;
1201     int size = 0;
1202     for (Node<E> p = first(); p != null;) {
1203     E item = p.item;
1204     if (item != null) {
1205     if (a == null)
1206     a = new String[4];
1207     else if (size == a.length)
1208     a = Arrays.copyOf(a, 2 * size);
1209     String s = item.toString();
1210     a[size++] = s;
1211     charLength += s.length();
1212     }
1213     if (p == (p = p.next))
1214     continue restartFromHead;
1215     }
1216    
1217     if (size == 0)
1218     return "[]";
1219    
1220     // Copy each string into a perfectly sized char[]
1221     final char[] chars = new char[charLength + 2 * size];
1222     chars[0] = '[';
1223     int j = 1;
1224     for (int i = 0; i < size; i++) {
1225     if (i > 0) {
1226     chars[j++] = ',';
1227     chars[j++] = ' ';
1228     }
1229     String s = a[i];
1230     int len = s.length();
1231     s.getChars(0, len, chars, j);
1232     j += len;
1233     }
1234     chars[j] = ']';
1235     return new String(chars);
1236     }
1237     }
1238    
1239     private Object[] toArrayInternal(Object[] a) {
1240     Object[] x = a;
1241     restartFromHead: for (;;) {
1242     int size = 0;
1243     for (Node<E> p = first(); p != null;) {
1244     E item = p.item;
1245     if (item != null) {
1246     if (x == null)
1247     x = new Object[4];
1248     else if (size == x.length)
1249     x = Arrays.copyOf(x, 2 * (size + 4));
1250     x[size++] = item;
1251     }
1252     if (p == (p = p.next))
1253     continue restartFromHead;
1254     }
1255     if (x == null)
1256     return new Object[0];
1257     else if (a != null && size <= a.length) {
1258     if (a != x)
1259     System.arraycopy(x, 0, a, 0, size);
1260     if (size < a.length)
1261     a[size] = null;
1262     return a;
1263     }
1264     return (size == x.length) ? x : Arrays.copyOf(x, size);
1265     }
1266     }
1267    
1268 jsr166 1.1 /**
1269     * Returns an array containing all of the elements in this deque, in
1270     * proper sequence (from first to last element).
1271     *
1272     * <p>The returned array will be "safe" in that no references to it are
1273     * maintained by this deque. (In other words, this method must allocate
1274     * a new array). The caller is thus free to modify the returned array.
1275     *
1276     * <p>This method acts as bridge between array-based and collection-based
1277     * APIs.
1278     *
1279     * @return an array containing all of the elements in this deque
1280     */
1281     public Object[] toArray() {
1282 jsr166 1.63 return toArrayInternal(null);
1283 jsr166 1.1 }
1284    
1285     /**
1286     * Returns an array containing all of the elements in this deque,
1287     * in proper sequence (from first to last element); the runtime
1288     * type of the returned array is that of the specified array. If
1289     * the deque fits in the specified array, it is returned therein.
1290     * Otherwise, a new array is allocated with the runtime type of
1291     * the specified array and the size of this deque.
1292     *
1293     * <p>If this deque fits in the specified array with room to spare
1294     * (i.e., the array has more elements than this deque), the element in
1295     * the array immediately following the end of the deque is set to
1296     * {@code null}.
1297     *
1298 jsr166 1.3 * <p>Like the {@link #toArray()} method, this method acts as
1299     * bridge between array-based and collection-based APIs. Further,
1300     * this method allows precise control over the runtime type of the
1301     * output array, and may, under certain circumstances, be used to
1302     * save allocation costs.
1303 jsr166 1.1 *
1304     * <p>Suppose {@code x} is a deque known to contain only strings.
1305     * The following code can be used to dump the deque into a newly
1306     * allocated array of {@code String}:
1307     *
1308 jsr166 1.61 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1309 jsr166 1.1 *
1310     * Note that {@code toArray(new Object[0])} is identical in function to
1311     * {@code toArray()}.
1312     *
1313     * @param a the array into which the elements of the deque are to
1314     * be stored, if it is big enough; otherwise, a new array of the
1315     * same runtime type is allocated for this purpose
1316     * @return an array containing all of the elements in this deque
1317     * @throws ArrayStoreException if the runtime type of the specified array
1318     * is not a supertype of the runtime type of every element in
1319     * this deque
1320     * @throws NullPointerException if the specified array is null
1321     */
1322 jsr166 1.63 @SuppressWarnings("unchecked")
1323 jsr166 1.1 public <T> T[] toArray(T[] a) {
1324 jsr166 1.63 if (a == null) throw new NullPointerException();
1325     return (T[]) toArrayInternal(a);
1326 jsr166 1.1 }
1327    
1328     /**
1329     * Returns an iterator over the elements in this deque in proper sequence.
1330     * The elements will be returned in order from first (head) to last (tail).
1331     *
1332 jsr166 1.50 * <p>The returned iterator is
1333     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1334 jsr166 1.1 *
1335     * @return an iterator over the elements in this deque in proper sequence
1336     */
1337     public Iterator<E> iterator() {
1338     return new Itr();
1339     }
1340    
1341     /**
1342     * Returns an iterator over the elements in this deque in reverse
1343     * sequential order. The elements will be returned in order from
1344     * last (tail) to first (head).
1345     *
1346 jsr166 1.50 * <p>The returned iterator is
1347     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1348 jsr166 1.3 *
1349     * @return an iterator over the elements in this deque in reverse order
1350 jsr166 1.1 */
1351     public Iterator<E> descendingIterator() {
1352     return new DescendingItr();
1353     }
1354    
1355     private abstract class AbstractItr implements Iterator<E> {
1356     /**
1357     * Next node to return item for.
1358     */
1359     private Node<E> nextNode;
1360    
1361     /**
1362     * nextItem holds on to item fields because once we claim
1363     * that an element exists in hasNext(), we must return it in
1364     * the following next() call even if it was in the process of
1365     * being removed when hasNext() was called.
1366     */
1367     private E nextItem;
1368    
1369     /**
1370     * Node returned by most recent call to next. Needed by remove.
1371     * Reset to null if this element is deleted by a call to remove.
1372     */
1373     private Node<E> lastRet;
1374    
1375     abstract Node<E> startNode();
1376     abstract Node<E> nextNode(Node<E> p);
1377    
1378     AbstractItr() {
1379     advance();
1380     }
1381    
1382     /**
1383     * Sets nextNode and nextItem to next valid node, or to null
1384     * if no such.
1385     */
1386     private void advance() {
1387     lastRet = nextNode;
1388    
1389     Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1390     for (;; p = nextNode(p)) {
1391     if (p == null) {
1392 jsr166 1.56 // might be at active end or TERMINATOR node; both are OK
1393 jsr166 1.1 nextNode = null;
1394     nextItem = null;
1395     break;
1396     }
1397     E item = p.item;
1398     if (item != null) {
1399     nextNode = p;
1400     nextItem = item;
1401     break;
1402     }
1403     }
1404     }
1405    
1406     public boolean hasNext() {
1407     return nextItem != null;
1408     }
1409    
1410     public E next() {
1411     E item = nextItem;
1412     if (item == null) throw new NoSuchElementException();
1413     advance();
1414     return item;
1415     }
1416    
1417     public void remove() {
1418     Node<E> l = lastRet;
1419     if (l == null) throw new IllegalStateException();
1420     l.item = null;
1421     unlink(l);
1422     lastRet = null;
1423     }
1424     }
1425    
1426     /** Forward iterator */
1427     private class Itr extends AbstractItr {
1428     Node<E> startNode() { return first(); }
1429     Node<E> nextNode(Node<E> p) { return succ(p); }
1430     }
1431    
1432     /** Descending iterator */
1433     private class DescendingItr extends AbstractItr {
1434     Node<E> startNode() { return last(); }
1435     Node<E> nextNode(Node<E> p) { return pred(p); }
1436     }
1437    
1438 dl 1.39 /** A customized variant of Spliterators.IteratorSpliterator */
1439 dl 1.35 static final class CLDSpliterator<E> implements Spliterator<E> {
1440 dl 1.42 static final int MAX_BATCH = 1 << 25; // max batch array size;
1441 dl 1.35 final ConcurrentLinkedDeque<E> queue;
1442     Node<E> current; // current node; null until initialized
1443     int batch; // batch size for splits
1444     boolean exhausted; // true when no more nodes
1445     CLDSpliterator(ConcurrentLinkedDeque<E> queue) {
1446     this.queue = queue;
1447     }
1448    
1449     public Spliterator<E> trySplit() {
1450 dl 1.42 Node<E> p;
1451 dl 1.35 final ConcurrentLinkedDeque<E> q = this.queue;
1452 dl 1.42 int b = batch;
1453     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1454 jsr166 1.40 if (!exhausted &&
1455 dl 1.37 ((p = current) != null || (p = q.first()) != null)) {
1456     if (p.item == null && p == (p = p.next))
1457     current = p = q.first();
1458 dl 1.42 if (p != null && p.next != null) {
1459 dl 1.46 Object[] a = new Object[n];
1460 dl 1.37 int i = 0;
1461     do {
1462     if ((a[i] = p.item) != null)
1463     ++i;
1464     if (p == (p = p.next))
1465     p = q.first();
1466     } while (p != null && i < n);
1467     if ((current = p) == null)
1468     exhausted = true;
1469 dl 1.42 if (i > 0) {
1470     batch = i;
1471     return Spliterators.spliterator
1472     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
1473     Spliterator.CONCURRENT);
1474     }
1475 dl 1.37 }
1476 dl 1.35 }
1477     return null;
1478     }
1479    
1480 dl 1.43 public void forEachRemaining(Consumer<? super E> action) {
1481 dl 1.35 Node<E> p;
1482     if (action == null) throw new NullPointerException();
1483     final ConcurrentLinkedDeque<E> q = this.queue;
1484     if (!exhausted &&
1485     ((p = current) != null || (p = q.first()) != null)) {
1486     exhausted = true;
1487     do {
1488     E e = p.item;
1489     if (p == (p = p.next))
1490     p = q.first();
1491     if (e != null)
1492     action.accept(e);
1493     } while (p != null);
1494     }
1495     }
1496    
1497     public boolean tryAdvance(Consumer<? super E> action) {
1498     Node<E> p;
1499     if (action == null) throw new NullPointerException();
1500     final ConcurrentLinkedDeque<E> q = this.queue;
1501     if (!exhausted &&
1502     ((p = current) != null || (p = q.first()) != null)) {
1503     E e;
1504     do {
1505     e = p.item;
1506     if (p == (p = p.next))
1507     p = q.first();
1508     } while (e == null && p != null);
1509     if ((current = p) == null)
1510     exhausted = true;
1511     if (e != null) {
1512     action.accept(e);
1513     return true;
1514     }
1515     }
1516     return false;
1517     }
1518    
1519 dl 1.36 public long estimateSize() { return Long.MAX_VALUE; }
1520    
1521 dl 1.35 public int characteristics() {
1522     return Spliterator.ORDERED | Spliterator.NONNULL |
1523     Spliterator.CONCURRENT;
1524     }
1525     }
1526    
1527 jsr166 1.49 /**
1528     * Returns a {@link Spliterator} over the elements in this deque.
1529     *
1530 jsr166 1.50 * <p>The returned spliterator is
1531     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1532     *
1533 jsr166 1.49 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1534     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1535     *
1536     * @implNote
1537     * The {@code Spliterator} implements {@code trySplit} to permit limited
1538     * parallelism.
1539     *
1540     * @return a {@code Spliterator} over the elements in this deque
1541     * @since 1.8
1542     */
1543 dl 1.38 public Spliterator<E> spliterator() {
1544 dl 1.35 return new CLDSpliterator<E>(this);
1545 dl 1.34 }
1546    
1547 jsr166 1.1 /**
1548 jsr166 1.31 * Saves this deque to a stream (that is, serializes it).
1549 jsr166 1.1 *
1550 jsr166 1.47 * @param s the stream
1551 jsr166 1.48 * @throws java.io.IOException if an I/O error occurs
1552 jsr166 1.1 * @serialData All of the elements (each an {@code E}) in
1553     * the proper order, followed by a null
1554     */
1555     private void writeObject(java.io.ObjectOutputStream s)
1556     throws java.io.IOException {
1557    
1558     // Write out any hidden stuff
1559     s.defaultWriteObject();
1560    
1561     // Write out all elements in the proper order.
1562     for (Node<E> p = first(); p != null; p = succ(p)) {
1563 jsr166 1.14 E item = p.item;
1564 jsr166 1.1 if (item != null)
1565     s.writeObject(item);
1566     }
1567    
1568     // Use trailing null as sentinel
1569     s.writeObject(null);
1570     }
1571    
1572     /**
1573 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1574 jsr166 1.47 * @param s the stream
1575 jsr166 1.48 * @throws ClassNotFoundException if the class of a serialized object
1576     * could not be found
1577     * @throws java.io.IOException if an I/O error occurs
1578 jsr166 1.1 */
1579     private void readObject(java.io.ObjectInputStream s)
1580     throws java.io.IOException, ClassNotFoundException {
1581     s.defaultReadObject();
1582 jsr166 1.3
1583     // Read in elements until trailing null sentinel found
1584     Node<E> h = null, t = null;
1585 jsr166 1.53 for (Object item; (item = s.readObject()) != null; ) {
1586 jsr166 1.1 @SuppressWarnings("unchecked")
1587 jsr166 1.3 Node<E> newNode = new Node<E>((E) item);
1588     if (h == null)
1589     h = t = newNode;
1590     else {
1591 jsr166 1.8 t.lazySetNext(newNode);
1592     newNode.lazySetPrev(t);
1593 jsr166 1.3 t = newNode;
1594     }
1595 jsr166 1.1 }
1596 jsr166 1.9 initHeadTail(h, t);
1597 jsr166 1.1 }
1598    
1599     private boolean casHead(Node<E> cmp, Node<E> val) {
1600 jsr166 1.60 return U.compareAndSwapObject(this, HEAD, cmp, val);
1601 jsr166 1.1 }
1602    
1603     private boolean casTail(Node<E> cmp, Node<E> val) {
1604 jsr166 1.60 return U.compareAndSwapObject(this, TAIL, cmp, val);
1605 jsr166 1.1 }
1606    
1607 dl 1.23 // Unsafe mechanics
1608    
1609 jsr166 1.60 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1610     private static final long HEAD;
1611     private static final long TAIL;
1612 dl 1.23 static {
1613     PREV_TERMINATOR = new Node<Object>();
1614     PREV_TERMINATOR.next = PREV_TERMINATOR;
1615     NEXT_TERMINATOR = new Node<Object>();
1616     NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1617 jsr166 1.1 try {
1618 jsr166 1.60 HEAD = U.objectFieldOffset
1619     (ConcurrentLinkedDeque.class.getDeclaredField("head"));
1620     TAIL = U.objectFieldOffset
1621     (ConcurrentLinkedDeque.class.getDeclaredField("tail"));
1622 jsr166 1.59 } catch (ReflectiveOperationException e) {
1623 dl 1.23 throw new Error(e);
1624 jsr166 1.1 }
1625     }
1626     }