ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.84
Committed: Mon Dec 26 17:29:34 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.83: +4 -2 lines
Log Message:
write to exhausted field only when necessary

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