ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.4
Committed: Wed Sep 1 22:49:09 2010 UTC (13 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +5 -6 lines
Log Message:
Use relaxed Unsafe.putObject in Node constructors

File Contents

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