ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.14
Committed: Fri Sep 17 20:54:51 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.13: +27 -20 lines
Log Message:
recheck head/tail after two hops

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