ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.45
Committed: Thu May 2 06:38:33 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.44: +18 -2 lines
Log Message:
fix up exception spec javadoc for deque methods

File Contents

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