ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ConcurrentLinkedDeque.java
Revision: 1.3
Committed: Fri Jun 10 18:10:53 2011 UTC (12 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.2: +1 -2 lines
Log Message:
sync with main

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