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