ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.13
Committed: Mon Sep 13 16:50:36 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.12: +5 -3 lines
Log Message:
remove accessor methods for Node.item; make size methods consistent

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 p = q;
339 }
340 }
341 }
342
343 /**
344 * Links e as last element.
345 */
346 private void linkLast(E e) {
347 checkNotNull(e);
348 final Node<E> newNode = new Node<E>(e);
349
350 restartFromTail:
351 for (;;) {
352 for (Node<E> t = tail, p = t;;) {
353 Node<E> q = p.next;
354 if (q == null) {
355 if (p.prev == p) // NEXT_TERMINATOR
356 continue restartFromTail;
357 // p is last node
358 newNode.lazySetPrev(p); // CAS piggyback
359 if (p.casNext(null, newNode)) {
360 // Successful CAS is the linearization point
361 // for e to become an element of this deque,
362 // and for newNode to become "live".
363 if (p != t) // hop two nodes at a time
364 casTail(t, newNode); // Failure is OK.
365 return;
366 }
367 // Lost CAS race to another thread; re-read next
368 }
369 else if (p == q)
370 continue restartFromTail;
371 else
372 p = q;
373 }
374 }
375 }
376
377 private final static int HOPS = 2;
378
379 /**
380 * Unlinks non-null node x.
381 */
382 void unlink(Node<E> x) {
383 // assert x != null;
384 // assert x.item == null;
385 // assert x != PREV_TERMINATOR;
386 // assert x != NEXT_TERMINATOR;
387
388 final Node<E> prev = x.prev;
389 final Node<E> next = x.next;
390 if (prev == null) {
391 unlinkFirst(x, next);
392 } else if (next == null) {
393 unlinkLast(x, prev);
394 } else {
395 // Unlink interior node.
396 //
397 // This is the common case, since a series of polls at the
398 // same end will be "interior" removes, except perhaps for
399 // the first one, since end nodes cannot be unlinked.
400 //
401 // At any time, all active nodes are mutually reachable by
402 // following a sequence of either next or prev pointers.
403 //
404 // Our strategy is to find the unique active predecessor
405 // and successor of x. Try to fix up their links so that
406 // they point to each other, leaving x unreachable from
407 // active nodes. If successful, and if x has no live
408 // predecessor/successor, we additionally try to gc-unlink,
409 // leaving active nodes unreachable from x, by rechecking
410 // that the status of predecessor and successor are
411 // unchanged and ensuring that x is not reachable from
412 // tail/head, before setting x's prev/next links to their
413 // logical approximate replacements, self/TERMINATOR.
414 Node<E> activePred, activeSucc;
415 boolean isFirst, isLast;
416 int hops = 1;
417
418 // Find active predecessor
419 for (Node<E> p = prev; ; ++hops) {
420 if (p.item != null) {
421 activePred = p;
422 isFirst = false;
423 break;
424 }
425 Node<E> q = p.prev;
426 if (q == null) {
427 if (p.next == p)
428 return;
429 activePred = p;
430 isFirst = true;
431 break;
432 }
433 else if (p == q)
434 return;
435 else
436 p = q;
437 }
438
439 // Find active successor
440 for (Node<E> p = next; ; ++hops) {
441 if (p.item != null) {
442 activeSucc = p;
443 isLast = false;
444 break;
445 }
446 Node<E> q = p.next;
447 if (q == null) {
448 if (p.prev == p)
449 return;
450 activeSucc = p;
451 isLast = true;
452 break;
453 }
454 else if (p == q)
455 return;
456 else
457 p = q;
458 }
459
460 // TODO: better HOP heuristics
461 if (hops < HOPS
462 // always squeeze out interior deleted nodes
463 && (isFirst | isLast))
464 return;
465
466 // Squeeze out deleted nodes between activePred and
467 // activeSucc, including x.
468 skipDeletedSuccessors(activePred);
469 skipDeletedPredecessors(activeSucc);
470
471 // Try to gc-unlink, if possible
472 if ((isFirst | isLast) &&
473
474 // Recheck expected state of predecessor and successor
475 (activePred.next == activeSucc) &&
476 (activeSucc.prev == activePred) &&
477 (isFirst ? activePred.prev == null : activePred.item != null) &&
478 (isLast ? activeSucc.next == null : activeSucc.item != null)) {
479
480 updateHead(); // Ensure x is not reachable from head
481 updateTail(); // Ensure x is not reachable from tail
482
483 // Finally, actually gc-unlink
484 x.lazySetPrev(isFirst ? prevTerminator() : x);
485 x.lazySetNext(isLast ? nextTerminator() : x);
486 }
487 }
488 }
489
490 /**
491 * Unlinks non-null first node.
492 */
493 private void unlinkFirst(Node<E> first, Node<E> next) {
494 // assert first != null;
495 // assert next != null;
496 // assert first.item == null;
497 Node<E> o = null, p = next;
498 for (int hops = 0; ; ++hops) {
499 Node<E> q;
500 if (p.item != null || (q = p.next) == null) {
501 if (hops >= HOPS && p.prev != p && first.casNext(next, p)) {
502 skipDeletedPredecessors(p);
503 if (first.prev == null &&
504 (p.next == null || p.item != null) &&
505 p.prev == first) {
506
507 updateHead(); // Ensure o is not reachable from head
508 updateTail(); // Ensure o is not reachable from tail
509
510 // Finally, actually gc-unlink
511 o.lazySetNext(o);
512 o.lazySetPrev(prevTerminator());
513 }
514 }
515 return;
516 }
517 else if (p == q)
518 return;
519 else {
520 o = p;
521 p = q;
522 }
523 }
524 }
525
526 /**
527 * Unlinks non-null last node.
528 */
529 private void unlinkLast(Node<E> last, Node<E> prev) {
530 // assert last != null;
531 // assert prev != null;
532 // assert last.item == null;
533 Node<E> o = null, p = prev;
534 for (int hops = 0; ; ++hops) {
535 Node<E> q;
536 if (p.item != null || (q = p.prev) == null) {
537 if (hops >= HOPS && p.next != p && last.casPrev(prev, p)) {
538 skipDeletedSuccessors(p);
539 if (last.next == null &&
540 (p.prev == null || p.item != null) &&
541 p.next == last) {
542
543 updateHead(); // Ensure o is not reachable from head
544 updateTail(); // Ensure o is not reachable from tail
545
546 // Finally, actually gc-unlink
547 o.lazySetPrev(o);
548 o.lazySetNext(nextTerminator());
549 }
550 }
551 return;
552 }
553 else if (p == q)
554 return;
555 else {
556 o = p;
557 p = q;
558 }
559 }
560 }
561
562 /**
563 * Sets head to first node. Guarantees that any node which was
564 * unlinked before a call to this method will be unreachable from
565 * head after it returns.
566 */
567 private final void updateHead() {
568 first();
569 }
570
571 /**
572 * Sets tail to last node. Guarantees that any node which was
573 * unlinked before a call to this method will be unreachable from
574 * tail after it returns.
575 */
576 private final void updateTail() {
577 last();
578 }
579
580 private void skipDeletedPredecessors(Node<E> x) {
581 whileActive:
582 do {
583 Node<E> prev = x.prev;
584 // assert prev != null;
585 // assert x != NEXT_TERMINATOR;
586 // assert x != PREV_TERMINATOR;
587 Node<E> p = prev;
588 findActive:
589 for (;;) {
590 if (p.item != null)
591 break findActive;
592 Node<E> q = p.prev;
593 if (q == null) {
594 if (p.next == p)
595 continue whileActive;
596 break findActive;
597 }
598 else if (p == q)
599 continue whileActive;
600 else
601 p = q;
602 }
603
604 // found active CAS target
605 if (prev == p || x.casPrev(prev, p))
606 return;
607
608 } while (x.item != null || x.next == null);
609 }
610
611 private void skipDeletedSuccessors(Node<E> x) {
612 whileActive:
613 do {
614 Node<E> next = x.next;
615 // assert next != null;
616 // assert x != NEXT_TERMINATOR;
617 // assert x != PREV_TERMINATOR;
618 Node<E> p = next;
619 findActive:
620 for (;;) {
621 if (p.item != null)
622 break findActive;
623 Node<E> q = p.next;
624 if (q == null) {
625 if (p.prev == p)
626 continue whileActive;
627 break findActive;
628 }
629 else if (p == q)
630 continue whileActive;
631 else
632 p = q;
633 }
634
635 // found active CAS target
636 if (next == p || x.casNext(next, p))
637 return;
638
639 } while (x.item != null || x.prev == null);
640 }
641
642 /**
643 * Returns the successor of p, or the first node if p.next has been
644 * linked to self, which will only be true if traversing with a
645 * stale pointer that is now off the list.
646 */
647 final Node<E> succ(Node<E> p) {
648 // TODO: should we skip deleted nodes here?
649 Node<E> q = p.next;
650 return (p == q) ? first() : q;
651 }
652
653 /**
654 * Returns the predecessor of p, or the last node if p.prev has been
655 * linked to self, which will only be true if traversing with a
656 * stale pointer that is now off the list.
657 */
658 final Node<E> pred(Node<E> p) {
659 Node<E> q = p.prev;
660 return (p == q) ? last() : q;
661 }
662
663 /**
664 * Returns the first node, the unique node p for which:
665 * p.prev == null && p.next != p
666 * The returned node may or may not be logically deleted.
667 * Guarantees that head is set to the returned node.
668 */
669 Node<E> first() {
670 restartFromHead:
671 for (;;) {
672 for (Node<E> h = head, p = h;;) {
673 Node<E> q = p.prev;
674 if (q == null) {
675 if (p == h
676 // It is possible that p is PREV_TERMINATOR,
677 // but if so, the CAS is guaranteed to fail.
678 || casHead(h, p))
679 return p;
680 else
681 continue restartFromHead;
682 } else if (p == q) {
683 continue restartFromHead;
684 } else {
685 p = q;
686 }
687 }
688 }
689 }
690
691 /**
692 * Returns the last node, the unique node p for which:
693 * p.next == null && p.prev != p
694 * The returned node may or may not be logically deleted.
695 * Guarantees that tail is set to the returned node.
696 */
697 Node<E> last() {
698 restartFromTail:
699 for (;;) {
700 for (Node<E> t = tail, p = t;;) {
701 Node<E> q = p.next;
702 if (q == null) {
703 if (p == t
704 // It is possible that p is NEXT_TERMINATOR,
705 // but if so, the CAS is guaranteed to fail.
706 || casTail(t, p))
707 return p;
708 else
709 continue restartFromTail;
710 } else if (p == q) {
711 continue restartFromTail;
712 } else {
713 p = q;
714 }
715 }
716 }
717 }
718
719 // Minor convenience utilities
720
721 /**
722 * Throws NullPointerException if argument is null.
723 *
724 * @param v the element
725 */
726 private static void checkNotNull(Object v) {
727 if (v == null)
728 throw new NullPointerException();
729 }
730
731 /**
732 * Returns element unless it is null, in which case throws
733 * NoSuchElementException.
734 *
735 * @param v the element
736 * @return the element
737 */
738 private E screenNullResult(E v) {
739 if (v == null)
740 throw new NoSuchElementException();
741 return v;
742 }
743
744 /**
745 * Creates an array list and fills it with elements of this list.
746 * Used by toArray.
747 *
748 * @return the arrayList
749 */
750 private ArrayList<E> toArrayList() {
751 ArrayList<E> list = new ArrayList<E>();
752 for (Node<E> p = first(); p != null; p = succ(p)) {
753 E item = p.item;
754 if (item != null)
755 list.add(item);
756 }
757 return list;
758 }
759
760 /**
761 * Constructs an empty deque.
762 */
763 public ConcurrentLinkedDeque() {
764 head = tail = new Node<E>(null);
765 }
766
767 /**
768 * Constructs a deque initially containing the elements of
769 * the given collection, added in traversal order of the
770 * collection's iterator.
771 *
772 * @param c the collection of elements to initially contain
773 * @throws NullPointerException if the specified collection or any
774 * of its elements are null
775 */
776 public ConcurrentLinkedDeque(Collection<? extends E> c) {
777 // Copy c into a private chain of Nodes
778 Node<E> h = null, t = null;
779 for (E e : c) {
780 checkNotNull(e);
781 Node<E> newNode = new Node<E>(e);
782 if (h == null)
783 h = t = newNode;
784 else {
785 t.lazySetNext(newNode);
786 newNode.lazySetPrev(t);
787 t = newNode;
788 }
789 }
790 initHeadTail(h, t);
791 }
792
793 /**
794 * Initializes head and tail, ensuring invariants hold.
795 */
796 private void initHeadTail(Node<E> h, Node<E> t) {
797 if (h == t) {
798 if (h == null)
799 h = t = new Node<E>(null);
800 else {
801 // Avoid edge case of a single Node with non-null item.
802 Node<E> newNode = new Node<E>(null);
803 t.lazySetNext(newNode);
804 newNode.lazySetPrev(t);
805 t = newNode;
806 }
807 }
808 head = h;
809 tail = t;
810 }
811
812 /**
813 * Inserts the specified element at the front of this deque.
814 *
815 * @throws NullPointerException {@inheritDoc}
816 */
817 public void addFirst(E e) {
818 linkFirst(e);
819 }
820
821 /**
822 * Inserts the specified element at the end of this deque.
823 *
824 * <p>This method is equivalent to {@link #add}.
825 *
826 * @throws NullPointerException {@inheritDoc}
827 */
828 public void addLast(E e) {
829 linkLast(e);
830 }
831
832 /**
833 * Inserts the specified element at the front of this deque.
834 *
835 * @return {@code true} always
836 * @throws NullPointerException {@inheritDoc}
837 */
838 public boolean offerFirst(E e) {
839 linkFirst(e);
840 return true;
841 }
842
843 /**
844 * Inserts the specified element at the end of this deque.
845 *
846 * <p>This method is equivalent to {@link #add}.
847 *
848 * @return {@code true} always
849 * @throws NullPointerException {@inheritDoc}
850 */
851 public boolean offerLast(E e) {
852 linkLast(e);
853 return true;
854 }
855
856 public E peekFirst() {
857 for (Node<E> p = first(); p != null; p = succ(p)) {
858 E item = p.item;
859 if (item != null)
860 return item;
861 }
862 return null;
863 }
864
865 public E peekLast() {
866 for (Node<E> p = last(); p != null; p = pred(p)) {
867 E item = p.item;
868 if (item != null)
869 return item;
870 }
871 return null;
872 }
873
874 /**
875 * @throws NoSuchElementException {@inheritDoc}
876 */
877 public E getFirst() {
878 return screenNullResult(peekFirst());
879 }
880
881 /**
882 * @throws NoSuchElementException {@inheritDoc}
883 */
884 public E getLast() {
885 return screenNullResult(peekLast());
886 }
887
888 public E pollFirst() {
889 for (Node<E> p = first(); p != null; p = succ(p)) {
890 E item = p.item;
891 if (item != null && p.casItem(item, null)) {
892 unlink(p);
893 return item;
894 }
895 }
896 return null;
897 }
898
899 public E pollLast() {
900 for (Node<E> p = last(); p != null; p = pred(p)) {
901 E item = p.item;
902 if (item != null && p.casItem(item, null)) {
903 unlink(p);
904 return item;
905 }
906 }
907 return null;
908 }
909
910 /**
911 * @throws NoSuchElementException {@inheritDoc}
912 */
913 public E removeFirst() {
914 return screenNullResult(pollFirst());
915 }
916
917 /**
918 * @throws NoSuchElementException {@inheritDoc}
919 */
920 public E removeLast() {
921 return screenNullResult(pollLast());
922 }
923
924 // *** Queue and stack methods ***
925
926 /**
927 * Inserts the specified element at the tail of this deque.
928 *
929 * @return {@code true} (as specified by {@link Queue#offer})
930 * @throws NullPointerException if the specified element is null
931 */
932 public boolean offer(E e) {
933 return offerLast(e);
934 }
935
936 /**
937 * Inserts the specified element at the tail of this deque.
938 *
939 * @return {@code true} (as specified by {@link Collection#add})
940 * @throws NullPointerException if the specified element is null
941 */
942 public boolean add(E e) {
943 return offerLast(e);
944 }
945
946 public E poll() { return pollFirst(); }
947 public E remove() { return removeFirst(); }
948 public E peek() { return peekFirst(); }
949 public E element() { return getFirst(); }
950 public void push(E e) { addFirst(e); }
951 public E pop() { return removeFirst(); }
952
953 /**
954 * Removes the first element {@code e} such that
955 * {@code o.equals(e)}, if such an element exists in this deque.
956 * If the deque does not contain the element, it is unchanged.
957 *
958 * @param o element to be removed from this deque, if present
959 * @return {@code true} if the deque contained the specified element
960 * @throws NullPointerException if the specified element is {@code null}
961 */
962 public boolean removeFirstOccurrence(Object o) {
963 checkNotNull(o);
964 for (Node<E> p = first(); p != null; p = succ(p)) {
965 E item = p.item;
966 if (item != null && o.equals(item) && p.casItem(item, null)) {
967 unlink(p);
968 return true;
969 }
970 }
971 return false;
972 }
973
974 /**
975 * Removes the last element {@code e} such that
976 * {@code o.equals(e)}, if such an element exists in this deque.
977 * If the deque does not contain the element, it is unchanged.
978 *
979 * @param o element to be removed from this deque, if present
980 * @return {@code true} if the deque contained the specified element
981 * @throws NullPointerException if the specified element is {@code null}
982 */
983 public boolean removeLastOccurrence(Object o) {
984 checkNotNull(o);
985 for (Node<E> p = last(); p != null; p = pred(p)) {
986 E item = p.item;
987 if (item != null && o.equals(item) && p.casItem(item, null)) {
988 unlink(p);
989 return true;
990 }
991 }
992 return false;
993 }
994
995 /**
996 * Returns {@code true} if this deque contains at least one
997 * element {@code e} such that {@code o.equals(e)}.
998 *
999 * @param o element whose presence in this deque is to be tested
1000 * @return {@code true} if this deque contains the specified element
1001 */
1002 public boolean contains(Object o) {
1003 if (o == null) return false;
1004 for (Node<E> p = first(); p != null; p = succ(p)) {
1005 E item = p.item;
1006 if (item != null && o.equals(item))
1007 return true;
1008 }
1009 return false;
1010 }
1011
1012 /**
1013 * Returns {@code true} if this collection contains no elements.
1014 *
1015 * @return {@code true} if this collection contains no elements
1016 */
1017 public boolean isEmpty() {
1018 return peekFirst() == null;
1019 }
1020
1021 /**
1022 * Returns the number of elements in this deque. If this deque
1023 * contains more than {@code Integer.MAX_VALUE} elements, it
1024 * returns {@code Integer.MAX_VALUE}.
1025 *
1026 * <p>Beware that, unlike in most collections, this method is
1027 * <em>NOT</em> a constant-time operation. Because of the
1028 * asynchronous nature of these deques, determining the current
1029 * number of elements requires traversing them all to count them.
1030 * Additionally, it is possible for the size to change during
1031 * execution of this method, in which case the returned result
1032 * will be inaccurate. Thus, this method is typically not very
1033 * useful in concurrent applications.
1034 *
1035 * @return the number of elements in this deque
1036 */
1037 public int size() {
1038 int count = 0;
1039 for (Node<E> p = first(); p != null; p = succ(p))
1040 if (p.item != null)
1041 // Collection.size() spec says to max out
1042 if (++count == Integer.MAX_VALUE)
1043 break;
1044 return count;
1045 }
1046
1047 /**
1048 * Removes the first element {@code e} such that
1049 * {@code o.equals(e)}, if such an element exists in this deque.
1050 * If the deque does not contain the element, it is unchanged.
1051 *
1052 * @param o element to be removed from this deque, if present
1053 * @return {@code true} if the deque contained the specified element
1054 * @throws NullPointerException if the specified element is {@code null}
1055 */
1056 public boolean remove(Object o) {
1057 return removeFirstOccurrence(o);
1058 }
1059
1060 /**
1061 * Appends all of the elements in the specified collection to the end of
1062 * this deque, in the order that they are returned by the specified
1063 * collection's iterator. Attempts to {@code addAll} of a deque to
1064 * itself result in {@code IllegalArgumentException}.
1065 *
1066 * @param c the elements to be inserted into this deque
1067 * @return {@code true} if this deque changed as a result of the call
1068 * @throws NullPointerException if the specified collection or any
1069 * of its elements are null
1070 * @throws IllegalArgumentException if the collection is this deque
1071 */
1072 public boolean addAll(Collection<? extends E> c) {
1073 if (c == this)
1074 // As historically specified in AbstractQueue#addAll
1075 throw new IllegalArgumentException();
1076
1077 // Copy c into a private chain of Nodes
1078 Node<E> splice = null, last = null;
1079 for (E e : c) {
1080 checkNotNull(e);
1081 Node<E> newNode = new Node<E>(e);
1082 if (splice == null)
1083 splice = last = newNode;
1084 else {
1085 last.lazySetNext(newNode);
1086 newNode.lazySetPrev(last);
1087 last = newNode;
1088 }
1089 }
1090 if (splice == null)
1091 return false;
1092
1093 // Atomically splice the chain as the tail of this collection
1094 restartFromTail:
1095 for (;;) {
1096 for (Node<E> t = tail, p = t;;) {
1097 Node<E> q = p.next;
1098 if (q == null) {
1099 if (p.prev == p) // NEXT_TERMINATOR
1100 continue restartFromTail;
1101 // p is last node
1102 splice.lazySetPrev(p); // CAS piggyback
1103 if (p.casNext(null, splice)) {
1104 if (! casTail(t, last)) {
1105 // Try a little harder to update tail,
1106 // since we may be adding many elements.
1107 t = tail;
1108 if (last.next == null)
1109 casTail(t, last);
1110 }
1111 return true;
1112 }
1113 // Lost CAS race to another thread; re-read next
1114 }
1115 else if (p == q)
1116 continue restartFromTail;
1117 else
1118 p = q;
1119 }
1120 }
1121 }
1122
1123 /**
1124 * Removes all of the elements from this deque.
1125 */
1126 public void clear() {
1127 while (pollFirst() != null)
1128 ;
1129 }
1130
1131 /**
1132 * Returns an array containing all of the elements in this deque, in
1133 * proper sequence (from first to last element).
1134 *
1135 * <p>The returned array will be "safe" in that no references to it are
1136 * maintained by this deque. (In other words, this method must allocate
1137 * a new array). The caller is thus free to modify the returned array.
1138 *
1139 * <p>This method acts as bridge between array-based and collection-based
1140 * APIs.
1141 *
1142 * @return an array containing all of the elements in this deque
1143 */
1144 public Object[] toArray() {
1145 return toArrayList().toArray();
1146 }
1147
1148 /**
1149 * Returns an array containing all of the elements in this deque,
1150 * in proper sequence (from first to last element); the runtime
1151 * type of the returned array is that of the specified array. If
1152 * the deque fits in the specified array, it is returned therein.
1153 * Otherwise, a new array is allocated with the runtime type of
1154 * the specified array and the size of this deque.
1155 *
1156 * <p>If this deque fits in the specified array with room to spare
1157 * (i.e., the array has more elements than this deque), the element in
1158 * the array immediately following the end of the deque is set to
1159 * {@code null}.
1160 *
1161 * <p>Like the {@link #toArray()} method, this method acts as
1162 * bridge between array-based and collection-based APIs. Further,
1163 * this method allows precise control over the runtime type of the
1164 * output array, and may, under certain circumstances, be used to
1165 * save allocation costs.
1166 *
1167 * <p>Suppose {@code x} is a deque known to contain only strings.
1168 * The following code can be used to dump the deque into a newly
1169 * allocated array of {@code String}:
1170 *
1171 * <pre>
1172 * String[] y = x.toArray(new String[0]);</pre>
1173 *
1174 * Note that {@code toArray(new Object[0])} is identical in function to
1175 * {@code toArray()}.
1176 *
1177 * @param a the array into which the elements of the deque are to
1178 * be stored, if it is big enough; otherwise, a new array of the
1179 * same runtime type is allocated for this purpose
1180 * @return an array containing all of the elements in this deque
1181 * @throws ArrayStoreException if the runtime type of the specified array
1182 * is not a supertype of the runtime type of every element in
1183 * this deque
1184 * @throws NullPointerException if the specified array is null
1185 */
1186 public <T> T[] toArray(T[] a) {
1187 return toArrayList().toArray(a);
1188 }
1189
1190 /**
1191 * Returns an iterator over the elements in this deque in proper sequence.
1192 * The elements will be returned in order from first (head) to last (tail).
1193 *
1194 * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
1195 * will never throw {@link java.util.ConcurrentModificationException
1196 * ConcurrentModificationException},
1197 * and guarantees to traverse elements as they existed upon
1198 * construction of the iterator, and may (but is not guaranteed to)
1199 * reflect any modifications subsequent to construction.
1200 *
1201 * @return an iterator over the elements in this deque in proper sequence
1202 */
1203 public Iterator<E> iterator() {
1204 return new Itr();
1205 }
1206
1207 /**
1208 * Returns an iterator over the elements in this deque in reverse
1209 * sequential order. The elements will be returned in order from
1210 * last (tail) to first (head).
1211 *
1212 * <p>The returned {@code Iterator} is a "weakly consistent" iterator that
1213 * will never throw {@link java.util.ConcurrentModificationException
1214 * ConcurrentModificationException},
1215 * and guarantees to traverse elements as they existed upon
1216 * construction of the iterator, and may (but is not guaranteed to)
1217 * reflect any modifications subsequent to construction.
1218 *
1219 * @return an iterator over the elements in this deque in reverse order
1220 */
1221 public Iterator<E> descendingIterator() {
1222 return new DescendingItr();
1223 }
1224
1225 private abstract class AbstractItr implements Iterator<E> {
1226 /**
1227 * Next node to return item for.
1228 */
1229 private Node<E> nextNode;
1230
1231 /**
1232 * nextItem holds on to item fields because once we claim
1233 * that an element exists in hasNext(), we must return it in
1234 * the following next() call even if it was in the process of
1235 * being removed when hasNext() was called.
1236 */
1237 private E nextItem;
1238
1239 /**
1240 * Node returned by most recent call to next. Needed by remove.
1241 * Reset to null if this element is deleted by a call to remove.
1242 */
1243 private Node<E> lastRet;
1244
1245 abstract Node<E> startNode();
1246 abstract Node<E> nextNode(Node<E> p);
1247
1248 AbstractItr() {
1249 advance();
1250 }
1251
1252 /**
1253 * Sets nextNode and nextItem to next valid node, or to null
1254 * if no such.
1255 */
1256 private void advance() {
1257 lastRet = nextNode;
1258
1259 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1260 for (;; p = nextNode(p)) {
1261 if (p == null) {
1262 // p might be active end or TERMINATOR node; both are OK
1263 nextNode = null;
1264 nextItem = null;
1265 break;
1266 }
1267 E item = p.item;
1268 if (item != null) {
1269 nextNode = p;
1270 nextItem = item;
1271 break;
1272 }
1273 }
1274 }
1275
1276 public boolean hasNext() {
1277 return nextItem != null;
1278 }
1279
1280 public E next() {
1281 E item = nextItem;
1282 if (item == null) throw new NoSuchElementException();
1283 advance();
1284 return item;
1285 }
1286
1287 public void remove() {
1288 Node<E> l = lastRet;
1289 if (l == null) throw new IllegalStateException();
1290 l.item = null;
1291 unlink(l);
1292 lastRet = null;
1293 }
1294 }
1295
1296 /** Forward iterator */
1297 private class Itr extends AbstractItr {
1298 Node<E> startNode() { return first(); }
1299 Node<E> nextNode(Node<E> p) { return succ(p); }
1300 }
1301
1302 /** Descending iterator */
1303 private class DescendingItr extends AbstractItr {
1304 Node<E> startNode() { return last(); }
1305 Node<E> nextNode(Node<E> p) { return pred(p); }
1306 }
1307
1308 /**
1309 * Saves the state to a stream (that is, serializes it).
1310 *
1311 * @serialData All of the elements (each an {@code E}) in
1312 * the proper order, followed by a null
1313 * @param s the stream
1314 */
1315 private void writeObject(java.io.ObjectOutputStream s)
1316 throws java.io.IOException {
1317
1318 // Write out any hidden stuff
1319 s.defaultWriteObject();
1320
1321 // Write out all elements in the proper order.
1322 for (Node<E> p = first(); p != null; p = succ(p)) {
1323 Object item = p.item;
1324 if (item != null)
1325 s.writeObject(item);
1326 }
1327
1328 // Use trailing null as sentinel
1329 s.writeObject(null);
1330 }
1331
1332 /**
1333 * Reconstitutes the instance from a stream (that is, deserializes it).
1334 * @param s the stream
1335 */
1336 private void readObject(java.io.ObjectInputStream s)
1337 throws java.io.IOException, ClassNotFoundException {
1338 s.defaultReadObject();
1339
1340 // Read in elements until trailing null sentinel found
1341 Node<E> h = null, t = null;
1342 Object item;
1343 while ((item = s.readObject()) != null) {
1344 @SuppressWarnings("unchecked")
1345 Node<E> newNode = new Node<E>((E) item);
1346 if (h == null)
1347 h = t = newNode;
1348 else {
1349 t.lazySetNext(newNode);
1350 newNode.lazySetPrev(t);
1351 t = newNode;
1352 }
1353 }
1354 initHeadTail(h, t);
1355 }
1356
1357 // Unsafe mechanics
1358
1359 private static final sun.misc.Unsafe UNSAFE =
1360 sun.misc.Unsafe.getUnsafe();
1361 private static final long headOffset =
1362 objectFieldOffset(UNSAFE, "head", ConcurrentLinkedDeque.class);
1363 private static final long tailOffset =
1364 objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedDeque.class);
1365
1366 private boolean casHead(Node<E> cmp, Node<E> val) {
1367 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
1368 }
1369
1370 private boolean casTail(Node<E> cmp, Node<E> val) {
1371 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
1372 }
1373
1374 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
1375 String field, Class<?> klazz) {
1376 try {
1377 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1378 } catch (NoSuchFieldException e) {
1379 // Convert Exception to corresponding Error
1380 NoSuchFieldError error = new NoSuchFieldError(field);
1381 error.initCause(e);
1382 throw error;
1383 }
1384 }
1385 }