ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java
Revision: 1.15
Committed: Mon Sep 20 20:18:25 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.14: +112 -86 lines
Log Message:
micro-optimizations

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