ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.36
Committed: Mon Feb 25 17:59:40 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.35: +6 -2 lines
Log Message:
lambda syncs and improvements

File Contents

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