ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.90
Committed: Tue Oct 10 05:54:41 2017 UTC (6 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.89: +62 -37 lines
Log Message:
8188900: ConcurrentLinkedDeque linearizability

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