2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea and Martin Buchholz with assistance from members of
32 * JCP JSR-166 Expert Group and released to the public domain, as explained
33 * at http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
38 import java.util.AbstractCollection;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.Deque;
42 import java.util.Iterator;
43 import java.util.NoSuchElementException;
44 import java.util.Queue;
47 * An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
48 * Concurrent insertion, removal, and access operations execute safely
49 * across multiple threads.
50 * A {@code ConcurrentLinkedDeque} is an appropriate choice when
51 * many threads will share access to a common collection.
52 * Like most other concurrent collection implementations, this class
53 * does not permit the use of {@code null} elements.
55 * <p>Iterators are <i>weakly consistent</i>, returning elements
56 * reflecting the state of the deque at some point at or since the
57 * creation of the iterator. They do <em>not</em> throw {@link
58 * java.util.ConcurrentModificationException
59 * ConcurrentModificationException}, and may proceed concurrently with
62 * <p>Beware that, unlike in most collections, the {@code size} method
63 * is <em>NOT</em> a constant-time operation. Because of the
64 * asynchronous nature of these deques, determining the current number
65 * of elements requires a traversal of the elements, and so may report
66 * inaccurate results if this collection is modified during traversal.
67 * Additionally, the bulk operations {@code addAll},
68 * {@code removeAll}, {@code retainAll}, {@code containsAll},
69 * {@code equals}, and {@code toArray} are <em>not</em> guaranteed
70 * to be performed atomically. For example, an iterator operating
71 * concurrently with an {@code addAll} operation might view only some
72 * of the added elements.
74 * <p>This class and its iterator implement all of the <em>optional</em>
75 * methods of the {@link Deque} and {@link Iterator} interfaces.
77 * <p>Memory consistency effects: As with other concurrent collections,
78 * actions in a thread prior to placing an object into a
79 * {@code ConcurrentLinkedDeque}
80 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
81 * actions subsequent to the access or removal of that element from
82 * the {@code ConcurrentLinkedDeque} in another thread.
84 * <p>This class is a member of the
85 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
86 * Java Collections Framework</a>.
90 * @author Martin Buchholz
91 * @param <E> the type of elements held in this collection
94 public class ConcurrentLinkedDeque<E>
95 extends AbstractCollection<E>
96 implements Deque<E>, java.io.Serializable {
99 * This is an implementation of a concurrent lock-free deque
100 * supporting interior removes but not interior insertions, as
101 * required to support the entire Deque interface.
103 * We extend the techniques developed for ConcurrentLinkedQueue and
104 * LinkedTransferQueue (see the internal docs for those classes).
105 * Understanding the ConcurrentLinkedQueue implementation is a
106 * prerequisite for understanding the implementation of this class.
108 * The data structure is a symmetrical doubly-linked "GC-robust"
109 * linked list of nodes. We minimize the number of volatile writes
110 * using two techniques: advancing multiple hops with a single CAS
111 * and mixing volatile and non-volatile writes of the same memory
114 * A node contains the expected E ("item") and links to predecessor
115 * ("prev") and successor ("next") nodes:
117 * class Node<E> { volatile Node<E> prev, next; volatile E item; }
119 * A node p is considered "live" if it contains a non-null item
120 * (p.item != null). When an item is CASed to null, the item is
121 * atomically logically deleted from the collection.
123 * At any time, there is precisely one "first" node with a null
124 * prev reference that terminates any chain of prev references
125 * starting at a live node. Similarly there is precisely one
126 * "last" node terminating any chain of next references starting at
127 * a live node. The "first" and "last" nodes may or may not be live.
128 * The "first" and "last" nodes are always mutually reachable.
130 * A new element is added atomically by CASing the null prev or
131 * next reference in the first or last node to a fresh node
132 * containing the element. The element's node atomically becomes
133 * "live" at that point.
135 * A node is considered "active" if it is a live node, or the
136 * first or last node. Active nodes cannot be unlinked.
138 * A "self-link" is a next or prev reference that is the same node:
139 * p.prev == p or p.next == p
140 * Self-links are used in the node unlinking process. Active nodes
141 * never have self-links.
143 * A node p is active if and only if:
146 * (p.prev == null && p.next != p) ||
147 * (p.next == null && p.prev != p)
149 * The deque object has two node references, "head" and "tail".
150 * The head and tail are only approximations to the first and last
151 * nodes of the deque. The first node can always be found by
152 * following prev pointers from head; likewise for tail. However,
153 * it is permissible for head and tail to be referring to deleted
154 * nodes that have been unlinked and so may not be reachable from
157 * There are 3 stages of node deletion;
158 * "logical deletion", "unlinking", and "gc-unlinking".
160 * 1. "logical deletion" by CASing item to null atomically removes
161 * the element from the collection, and makes the containing node
162 * eligible for unlinking.
164 * 2. "unlinking" makes a deleted node unreachable from active
165 * nodes, and thus eventually reclaimable by GC. Unlinked nodes
166 * may remain reachable indefinitely from an iterator.
168 * Physical node unlinking is merely an optimization (albeit a
169 * critical one), and so can be performed at our convenience. At
170 * any time, the set of live nodes maintained by prev and next
171 * links are identical, that is, the live nodes found via next
172 * links from the first node is equal to the elements found via
173 * prev links from the last node. However, this is not true for
174 * nodes that have already been logically deleted - such nodes may
175 * be reachable in one direction only.
177 * 3. "gc-unlinking" takes unlinking further by making active
178 * nodes unreachable from deleted nodes, making it easier for the
179 * GC to reclaim future deleted nodes. This step makes the data
180 * structure "gc-robust", as first described in detail by Boehm
181 * (http://portal.acm.org/citation.cfm?doid=503272.503282).
183 * GC-unlinked nodes may remain reachable indefinitely from an
184 * iterator, but unlike unlinked nodes, are never reachable from
187 * Making the data structure GC-robust will eliminate the risk of
188 * unbounded memory retention with conservative GCs and is likely
189 * to improve performance with generational GCs.
191 * When a node is dequeued at either end, e.g. via poll(), we would
192 * like to break any references from the node to active nodes. We
193 * develop further the use of self-links that was very effective in
194 * other concurrent collection classes. The idea is to replace
195 * prev and next pointers with special values that are interpreted
196 * to mean off-the-list-at-one-end. These are approximations, but
197 * good enough to preserve the properties we want in our
198 * traversals, e.g. we guarantee that a traversal will never visit
199 * the same element twice, but we don't guarantee whether a
200 * traversal that runs out of elements will be able to see more
201 * elements later after enqueues at that end. Doing gc-unlinking
202 * safely is particularly tricky, since any node can be in use
203 * indefinitely (for example by an iterator). We must ensure that
204 * the nodes pointed at by head/tail never get gc-unlinked, since
205 * head/tail are needed to get "back on track" by other nodes that
206 * are gc-unlinked. gc-unlinking accounts for much of the
207 * implementation complexity.
209 * Since neither unlinking nor gc-unlinking are necessary for
210 * correctness, there are many implementation choices regarding
211 * frequency (eagerness) of these operations. Since volatile
212 * reads are likely to be much cheaper than CASes, saving CASes by
213 * unlinking multiple adjacent nodes at a time may be a win.
214 * gc-unlinking can be performed rarely and still be effective,
215 * since it is most important that long chains of deleted nodes
216 * are occasionally broken.
218 * The actual representation we use is that p.next == p means to
219 * goto the first node (which in turn is reached by following prev
220 * pointers from head), and p.next == null && p.prev == p means
221 * that the iteration is at an end and that p is a (static final)
222 * dummy node, NEXT_TERMINATOR, and not the last active node.
223 * Finishing the iteration when encountering such a TERMINATOR is
224 * good enough for read-only traversals, so such traversals can use
225 * p.next == null as the termination condition. When we need to
226 * find the last (active) node, for enqueueing a new node, we need
227 * to check whether we have reached a TERMINATOR node; if so,
228 * restart traversal from tail.
230 * The implementation is completely directionally symmetrical,
231 * except that most public methods that iterate through the list
232 * follow next pointers ("forward" direction).
234 * We believe (without full proof) that all single-element deque
235 * operations (e.g., addFirst, peekLast, pollLast) are linearizable
236 * (see Herlihy and Shavit's book). However, some combinations of
237 * operations are known not to be linearizable. In particular,
238 * when an addFirst(A) is racing with pollFirst() removing B, it is
239 * possible for an observer iterating over the elements to observe
240 * A B C and subsequently observe A C, even though no interior
241 * removes are ever performed. Nevertheless, iterators behave
242 * reasonably, providing the "weakly consistent" guarantees.
244 * Empirically, microbenchmarks suggest that this class adds about
245 * 40% overhead relative to ConcurrentLinkedQueue, which feels as
246 * good as we can hope for.
249 private static final long serialVersionUID = 876323262645176354L;
252 * A node from which the first node on list (that is, the unique node p
253 * with p.prev == null && p.next != p) can be reached in O(1) time.
255 * - the first node is always O(1) reachable from head via prev links
256 * - all live nodes are reachable from the first node via succ()
258 * - (tmp = head).next != tmp || tmp != head
259 * - head is never gc-unlinked (but may be unlinked)
261 * - head.item may or may not be null
262 * - head may not be reachable from the first or last node, or from tail
264 private transient volatile Node<E> head;
267 * A node from which the last node on list (that is, the unique node p
268 * with p.next == null && p.prev != p) can be reached in O(1) time.
270 * - the last node is always O(1) reachable from tail via next links
271 * - all live nodes are reachable from the last node via pred()
273 * - tail is never gc-unlinked (but may be unlinked)
275 * - tail.item may or may not be null
276 * - tail may not be reachable from the first or last node, or from head
278 private transient volatile Node<E> tail;
280 private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR;
282 @SuppressWarnings("unchecked")
283 Node<E> prevTerminator() {
284 return (Node<E>) PREV_TERMINATOR;
287 @SuppressWarnings("unchecked")
288 Node<E> nextTerminator() {
289 return (Node<E>) NEXT_TERMINATOR;
292 static final class Node<E> {
293 volatile Node<E> prev;
295 volatile Node<E> next;
297 Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR
301 * Constructs a new node. Uses relaxed write because item can
302 * only be seen after publication via casNext or casPrev.
305 UNSAFE.putObject(this, itemOffset, item);
308 boolean casItem(E cmp, E val) {
309 return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
312 void lazySetNext(Node<E> val) {
313 UNSAFE.putOrderedObject(this, nextOffset, val);
316 boolean casNext(Node<E> cmp, Node<E> val) {
317 return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
320 void lazySetPrev(Node<E> val) {
321 UNSAFE.putOrderedObject(this, prevOffset, val);
324 boolean casPrev(Node<E> cmp, Node<E> val) {
325 return UNSAFE.compareAndSwapObject(this, prevOffset, cmp, val);
330 private static final sun.misc.Unsafe UNSAFE;
331 private static final long prevOffset;
332 private static final long itemOffset;
333 private static final long nextOffset;
337 UNSAFE = sun.misc.Unsafe.getUnsafe();
338 Class k = Node.class;
339 prevOffset = UNSAFE.objectFieldOffset
340 (k.getDeclaredField("prev"));
341 itemOffset = UNSAFE.objectFieldOffset
342 (k.getDeclaredField("item"));
343 nextOffset = UNSAFE.objectFieldOffset
344 (k.getDeclaredField("next"));
345 } catch (Exception e) {
352 * Links e as first element.
354 private void linkFirst(E e) {
356 final Node<E> newNode = new Node<E>(e);
360 for (Node<E> h = head, p = h, q;;) {
361 if ((q = p.prev) != null &&
362 (q = (p = q).prev) != null)
363 // Check for head updates every other hop.
364 // If p == q, we are sure to follow head instead.
365 p = (h != (h = head)) ? h : q;
366 else if (p.next == p) // PREV_TERMINATOR
367 continue restartFromHead;
370 newNode.lazySetNext(p); // CAS piggyback
371 if (p.casPrev(null, newNode)) {
372 // Successful CAS is the linearization point
373 // for e to become an element of this deque,
374 // and for newNode to become "live".
375 if (p != h) // hop two nodes at a time
376 casHead(h, newNode); // Failure is OK.
379 // Lost CAS race to another thread; re-read prev
385 * Links e as last element.
387 private void linkLast(E e) {
389 final Node<E> newNode = new Node<E>(e);
393 for (Node<E> t = tail, p = t, q;;) {
394 if ((q = p.next) != null &&
395 (q = (p = q).next) != null)
396 // Check for tail updates every other hop.
397 // If p == q, we are sure to follow tail instead.
398 p = (t != (t = tail)) ? t : q;
399 else if (p.prev == p) // NEXT_TERMINATOR
400 continue restartFromTail;
403 newNode.lazySetPrev(p); // CAS piggyback
404 if (p.casNext(null, newNode)) {
405 // Successful CAS is the linearization point
406 // for e to become an element of this deque,
407 // and for newNode to become "live".
408 if (p != t) // hop two nodes at a time
409 casTail(t, newNode); // Failure is OK.
412 // Lost CAS race to another thread; re-read next
417 private static final int HOPS = 2;
420 * Unlinks non-null node x.
422 void unlink(Node<E> x) {
424 // assert x.item == null;
425 // assert x != PREV_TERMINATOR;
426 // assert x != NEXT_TERMINATOR;
428 final Node<E> prev = x.prev;
429 final Node<E> next = x.next;
431 unlinkFirst(x, next);
432 } else if (next == null) {
435 // Unlink interior node.
437 // This is the common case, since a series of polls at the
438 // same end will be "interior" removes, except perhaps for
439 // the first one, since end nodes cannot be unlinked.
441 // At any time, all active nodes are mutually reachable by
442 // following a sequence of either next or prev pointers.
444 // Our strategy is to find the unique active predecessor
445 // and successor of x. Try to fix up their links so that
446 // they point to each other, leaving x unreachable from
447 // active nodes. If successful, and if x has no live
448 // predecessor/successor, we additionally try to gc-unlink,
449 // leaving active nodes unreachable from x, by rechecking
450 // that the status of predecessor and successor are
451 // unchanged and ensuring that x is not reachable from
452 // tail/head, before setting x's prev/next links to their
453 // logical approximate replacements, self/TERMINATOR.
454 Node<E> activePred, activeSucc;
455 boolean isFirst, isLast;
458 // Find active predecessor
459 for (Node<E> p = prev; ; ++hops) {
460 if (p.item != null) {
479 // Find active successor
480 for (Node<E> p = next; ; ++hops) {
481 if (p.item != null) {
500 // TODO: better HOP heuristics
502 // always squeeze out interior deleted nodes
503 && (isFirst | isLast))
506 // Squeeze out deleted nodes between activePred and
507 // activeSucc, including x.
508 skipDeletedSuccessors(activePred);
509 skipDeletedPredecessors(activeSucc);
511 // Try to gc-unlink, if possible
512 if ((isFirst | isLast) &&
514 // Recheck expected state of predecessor and successor
515 (activePred.next == activeSucc) &&
516 (activeSucc.prev == activePred) &&
517 (isFirst ? activePred.prev == null : activePred.item != null) &&
518 (isLast ? activeSucc.next == null : activeSucc.item != null)) {
520 updateHead(); // Ensure x is not reachable from head
521 updateTail(); // Ensure x is not reachable from tail
523 // Finally, actually gc-unlink
524 x.lazySetPrev(isFirst ? prevTerminator() : x);
525 x.lazySetNext(isLast ? nextTerminator() : x);
531 * Unlinks non-null first node.
533 private void unlinkFirst(Node<E> first, Node<E> next) {
534 // assert first != null;
535 // assert next != null;
536 // assert first.item == null;
537 for (Node<E> o = null, p = next, q;;) {
538 if (p.item != null || (q = p.next) == null) {
539 if (o != null && p.prev != p && first.casNext(next, p)) {
540 skipDeletedPredecessors(p);
541 if (first.prev == null &&
542 (p.next == null || p.item != null) &&
545 updateHead(); // Ensure o is not reachable from head
546 updateTail(); // Ensure o is not reachable from tail
548 // Finally, actually gc-unlink
550 o.lazySetPrev(prevTerminator());
565 * Unlinks non-null last node.
567 private void unlinkLast(Node<E> last, Node<E> prev) {
568 // assert last != null;
569 // assert prev != null;
570 // assert last.item == null;
571 for (Node<E> o = null, p = prev, q;;) {
572 if (p.item != null || (q = p.prev) == null) {
573 if (o != null && p.next != p && last.casPrev(prev, p)) {
574 skipDeletedSuccessors(p);
575 if (last.next == null &&
576 (p.prev == null || p.item != null) &&
579 updateHead(); // Ensure o is not reachable from head
580 updateTail(); // Ensure o is not reachable from tail
582 // Finally, actually gc-unlink
584 o.lazySetNext(nextTerminator());
599 * Guarantees that any node which was unlinked before a call to
600 * this method will be unreachable from head after it returns.
601 * Does not guarantee to eliminate slack, only that head will
602 * point to a node that was active while this method was running.
604 private final void updateHead() {
605 // Either head already points to an active node, or we keep
606 // trying to cas it to the first node until it does.
609 while ((h = head).item == null && (p = h.prev) != null) {
611 if ((q = p.prev) == null ||
612 (q = (p = q).prev) == null) {
613 // It is possible that p is PREV_TERMINATOR,
614 // but if so, the CAS is guaranteed to fail.
618 continue restartFromHead;
621 continue restartFromHead;
629 * Guarantees that any node which was unlinked before a call to
630 * this method will be unreachable from tail after it returns.
631 * Does not guarantee to eliminate slack, only that tail will
632 * point to a node that was active while this method was running.
634 private final void updateTail() {
635 // Either tail already points to an active node, or we keep
636 // trying to cas it to the last node until it does.
639 while ((t = tail).item == null && (p = t.next) != null) {
641 if ((q = p.next) == null ||
642 (q = (p = q).next) == null) {
643 // It is possible that p is NEXT_TERMINATOR,
644 // but if so, the CAS is guaranteed to fail.
648 continue restartFromTail;
651 continue restartFromTail;
658 private void skipDeletedPredecessors(Node<E> x) {
661 Node<E> prev = x.prev;
662 // assert prev != null;
663 // assert x != NEXT_TERMINATOR;
664 // assert x != PREV_TERMINATOR;
673 continue whileActive;
677 continue whileActive;
682 // found active CAS target
683 if (prev == p || x.casPrev(prev, p))
686 } while (x.item != null || x.next == null);
689 private void skipDeletedSuccessors(Node<E> x) {
692 Node<E> next = x.next;
693 // assert next != null;
694 // assert x != NEXT_TERMINATOR;
695 // assert x != PREV_TERMINATOR;
704 continue whileActive;
708 continue whileActive;
713 // found active CAS target
714 if (next == p || x.casNext(next, p))
717 } while (x.item != null || x.prev == null);
721 * Returns the successor of p, or the first node if p.next has been
722 * linked to self, which will only be true if traversing with a
723 * stale pointer that is now off the list.
725 final Node<E> succ(Node<E> p) {
726 // TODO: should we skip deleted nodes here?
728 return (p == q) ? first() : q;
732 * Returns the predecessor of p, or the last node if p.prev has been
733 * linked to self, which will only be true if traversing with a
734 * stale pointer that is now off the list.
736 final Node<E> pred(Node<E> p) {
738 return (p == q) ? last() : q;
742 * Returns the first node, the unique node p for which:
743 * p.prev == null && p.next != p
744 * The returned node may or may not be logically deleted.
745 * Guarantees that head is set to the returned node.
750 for (Node<E> h = head, p = h, q;;) {
751 if ((q = p.prev) != null &&
752 (q = (p = q).prev) != null)
753 // Check for head updates every other hop.
754 // If p == q, we are sure to follow head instead.
755 p = (h != (h = head)) ? h : q;
757 // It is possible that p is PREV_TERMINATOR,
758 // but if so, the CAS is guaranteed to fail.
762 continue restartFromHead;
767 * Returns the last node, the unique node p for which:
768 * p.next == null && p.prev != p
769 * The returned node may or may not be logically deleted.
770 * Guarantees that tail is set to the returned node.
775 for (Node<E> t = tail, p = t, q;;) {
776 if ((q = p.next) != null &&
777 (q = (p = q).next) != null)
778 // Check for tail updates every other hop.
779 // If p == q, we are sure to follow tail instead.
780 p = (t != (t = tail)) ? t : q;
782 // It is possible that p is NEXT_TERMINATOR,
783 // but if so, the CAS is guaranteed to fail.
787 continue restartFromTail;
791 // Minor convenience utilities
794 * Throws NullPointerException if argument is null.
796 * @param v the element
798 private static void checkNotNull(Object v) {
800 throw new NullPointerException();
804 * Returns element unless it is null, in which case throws
805 * NoSuchElementException.
807 * @param v the element
808 * @return the element
810 private E screenNullResult(E v) {
812 throw new NoSuchElementException();
817 * Creates an array list and fills it with elements of this list.
820 * @return the arrayList
822 private ArrayList<E> toArrayList() {
823 ArrayList<E> list = new ArrayList<E>();
824 for (Node<E> p = first(); p != null; p = succ(p)) {
833 * Constructs an empty deque.
835 public ConcurrentLinkedDeque() {
836 head = tail = new Node<E>(null);
840 * Constructs a deque initially containing the elements of
841 * the given collection, added in traversal order of the
842 * collection's iterator.
844 * @param c the collection of elements to initially contain
845 * @throws NullPointerException if the specified collection or any
846 * of its elements are null
848 public ConcurrentLinkedDeque(Collection<? extends E> c) {
849 // Copy c into a private chain of Nodes
850 Node<E> h = null, t = null;
853 Node<E> newNode = new Node<E>(e);
857 t.lazySetNext(newNode);
858 newNode.lazySetPrev(t);
866 * Initializes head and tail, ensuring invariants hold.
868 private void initHeadTail(Node<E> h, Node<E> t) {
871 h = t = new Node<E>(null);
873 // Avoid edge case of a single Node with non-null item.
874 Node<E> newNode = new Node<E>(null);
875 t.lazySetNext(newNode);
876 newNode.lazySetPrev(t);
885 * Inserts the specified element at the front of this deque.
886 * As the deque is unbounded, this method will never throw
887 * {@link IllegalStateException}.
889 * @throws NullPointerException if the specified element is null
891 public void addFirst(E e) {
896 * Inserts the specified element at the end of this deque.
897 * As the deque is unbounded, this method will never throw
898 * {@link IllegalStateException}.
900 * <p>This method is equivalent to {@link #add}.
902 * @throws NullPointerException if the specified element is null
904 public void addLast(E e) {
909 * Inserts the specified element at the front of this deque.
910 * As the deque is unbounded, this method will never return {@code false}.
912 * @return {@code true} (as specified by {@link Deque#offerFirst})
913 * @throws NullPointerException if the specified element is null
915 public boolean offerFirst(E e) {
921 * Inserts the specified element at the end of this deque.
922 * As the deque is unbounded, this method will never return {@code false}.
924 * <p>This method is equivalent to {@link #add}.
926 * @return {@code true} (as specified by {@link Deque#offerLast})
927 * @throws NullPointerException if the specified element is null
929 public boolean offerLast(E e) {
934 public E peekFirst() {
935 for (Node<E> p = first(); p != null; p = succ(p)) {
943 public E peekLast() {
944 for (Node<E> p = last(); p != null; p = pred(p)) {
953 * @throws NoSuchElementException {@inheritDoc}
955 public E getFirst() {
956 return screenNullResult(peekFirst());
960 * @throws NoSuchElementException {@inheritDoc}
963 return screenNullResult(peekLast());
966 public E pollFirst() {
967 for (Node<E> p = first(); p != null; p = succ(p)) {
969 if (item != null && p.casItem(item, null)) {
977 public E pollLast() {
978 for (Node<E> p = last(); p != null; p = pred(p)) {
980 if (item != null && p.casItem(item, null)) {
989 * @throws NoSuchElementException {@inheritDoc}
991 public E removeFirst() {
992 return screenNullResult(pollFirst());
996 * @throws NoSuchElementException {@inheritDoc}
998 public E removeLast() {
999 return screenNullResult(pollLast());
1002 // *** Queue and stack methods ***
1005 * Inserts the specified element at the tail of this deque.
1006 * As the deque is unbounded, this method will never return {@code false}.
1008 * @return {@code true} (as specified by {@link Queue#offer})
1009 * @throws NullPointerException if the specified element is null
1011 public boolean offer(E e) {
1012 return offerLast(e);
1016 * Inserts the specified element at the tail of this deque.
1017 * As the deque is unbounded, this method will never throw
1018 * {@link IllegalStateException} or return {@code false}.
1020 * @return {@code true} (as specified by {@link Collection#add})
1021 * @throws NullPointerException if the specified element is null
1023 public boolean add(E e) {
1024 return offerLast(e);
1027 public E poll() { return pollFirst(); }
1028 public E remove() { return removeFirst(); }
1029 public E peek() { return peekFirst(); }
1030 public E element() { return getFirst(); }
1031 public void push(E e) { addFirst(e); }
1032 public E pop() { return removeFirst(); }
1035 * Removes the first element {@code e} such that
1036 * {@code o.equals(e)}, if such an element exists in this deque.
1037 * If the deque does not contain the element, it is unchanged.
1039 * @param o element to be removed from this deque, if present
1040 * @return {@code true} if the deque contained the specified element
1041 * @throws NullPointerException if the specified element is null
1043 public boolean removeFirstOccurrence(Object o) {
1045 for (Node<E> p = first(); p != null; p = succ(p)) {
1047 if (item != null && o.equals(item) && p.casItem(item, null)) {
1056 * Removes the last element {@code e} such that
1057 * {@code o.equals(e)}, if such an element exists in this deque.
1058 * If the deque does not contain the element, it is unchanged.
1060 * @param o element to be removed from this deque, if present
1061 * @return {@code true} if the deque contained the specified element
1062 * @throws NullPointerException if the specified element is null
1064 public boolean removeLastOccurrence(Object o) {
1066 for (Node<E> p = last(); p != null; p = pred(p)) {
1068 if (item != null && o.equals(item) && p.casItem(item, null)) {
1077 * Returns {@code true} if this deque contains at least one
1078 * element {@code e} such that {@code o.equals(e)}.
1080 * @param o element whose presence in this deque is to be tested
1081 * @return {@code true} if this deque contains the specified element
1083 public boolean contains(Object o) {
1084 if (o == null) return false;
1085 for (Node<E> p = first(); p != null; p = succ(p)) {
1087 if (item != null && o.equals(item))
1094 * Returns {@code true} if this collection contains no elements.
1096 * @return {@code true} if this collection contains no elements
1098 public boolean isEmpty() {
1099 return peekFirst() == null;
1103 * Returns the number of elements in this deque. If this deque
1104 * contains more than {@code Integer.MAX_VALUE} elements, it
1105 * returns {@code Integer.MAX_VALUE}.
1107 * <p>Beware that, unlike in most collections, this method is
1108 * <em>NOT</em> a constant-time operation. Because of the
1109 * asynchronous nature of these deques, determining the current
1110 * number of elements requires traversing them all to count them.
1111 * Additionally, it is possible for the size to change during
1112 * execution of this method, in which case the returned result
1113 * will be inaccurate. Thus, this method is typically not very
1114 * useful in concurrent applications.
1116 * @return the number of elements in this deque
1120 for (Node<E> p = first(); p != null; p = succ(p))
1122 // Collection.size() spec says to max out
1123 if (++count == Integer.MAX_VALUE)
1129 * Removes the first element {@code e} such that
1130 * {@code o.equals(e)}, if such an element exists in this deque.
1131 * If the deque does not contain the element, it is unchanged.
1133 * @param o element to be removed from this deque, if present
1134 * @return {@code true} if the deque contained the specified element
1135 * @throws NullPointerException if the specified element is null
1137 public boolean remove(Object o) {
1138 return removeFirstOccurrence(o);
1142 * Appends all of the elements in the specified collection to the end of
1143 * this deque, in the order that they are returned by the specified
1144 * collection's iterator. Attempts to {@code addAll} of a deque to
1145 * itself result in {@code IllegalArgumentException}.
1147 * @param c the elements to be inserted into this deque
1148 * @return {@code true} if this deque changed as a result of the call
1149 * @throws NullPointerException if the specified collection or any
1150 * of its elements are null
1151 * @throws IllegalArgumentException if the collection is this deque
1153 public boolean addAll(Collection<? extends E> c) {
1155 // As historically specified in AbstractQueue#addAll
1156 throw new IllegalArgumentException();
1158 // Copy c into a private chain of Nodes
1159 Node<E> beginningOfTheEnd = null, last = null;
1162 Node<E> newNode = new Node<E>(e);
1163 if (beginningOfTheEnd == null)
1164 beginningOfTheEnd = last = newNode;
1166 last.lazySetNext(newNode);
1167 newNode.lazySetPrev(last);
1171 if (beginningOfTheEnd == null)
1174 // Atomically append the chain at the tail of this collection
1177 for (Node<E> t = tail, p = t, q;;) {
1178 if ((q = p.next) != null &&
1179 (q = (p = q).next) != null)
1180 // Check for tail updates every other hop.
1181 // If p == q, we are sure to follow tail instead.
1182 p = (t != (t = tail)) ? t : q;
1183 else if (p.prev == p) // NEXT_TERMINATOR
1184 continue restartFromTail;
1187 beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
1188 if (p.casNext(null, beginningOfTheEnd)) {
1189 // Successful CAS is the linearization point
1190 // for all elements to be added to this deque.
1191 if (!casTail(t, last)) {
1192 // Try a little harder to update tail,
1193 // since we may be adding many elements.
1195 if (last.next == null)
1200 // Lost CAS race to another thread; re-read next
1206 * Removes all of the elements from this deque.
1208 public void clear() {
1209 while (pollFirst() != null)
1214 * Returns an array containing all of the elements in this deque, in
1215 * proper sequence (from first to last element).
1217 * <p>The returned array will be "safe" in that no references to it are
1218 * maintained by this deque. (In other words, this method must allocate
1219 * a new array). The caller is thus free to modify the returned array.
1221 * <p>This method acts as bridge between array-based and collection-based
1224 * @return an array containing all of the elements in this deque
1226 public Object[] toArray() {
1227 return toArrayList().toArray();
1231 * Returns an array containing all of the elements in this deque,
1232 * in proper sequence (from first to last element); the runtime
1233 * type of the returned array is that of the specified array. If
1234 * the deque fits in the specified array, it is returned therein.
1235 * Otherwise, a new array is allocated with the runtime type of
1236 * the specified array and the size of this deque.
1238 * <p>If this deque fits in the specified array with room to spare
1239 * (i.e., the array has more elements than this deque), the element in
1240 * the array immediately following the end of the deque is set to
1243 * <p>Like the {@link #toArray()} method, this method acts as
1244 * bridge between array-based and collection-based APIs. Further,
1245 * this method allows precise control over the runtime type of the
1246 * output array, and may, under certain circumstances, be used to
1247 * save allocation costs.
1249 * <p>Suppose {@code x} is a deque known to contain only strings.
1250 * The following code can be used to dump the deque into a newly
1251 * allocated array of {@code String}:
1254 * String[] y = x.toArray(new String[0]);</pre>
1256 * Note that {@code toArray(new Object[0])} is identical in function to
1257 * {@code toArray()}.
1259 * @param a the array into which the elements of the deque are to
1260 * be stored, if it is big enough; otherwise, a new array of the
1261 * same runtime type is allocated for this purpose
1262 * @return an array containing all of the elements in this deque
1263 * @throws ArrayStoreException if the runtime type of the specified array
1264 * is not a supertype of the runtime type of every element in
1266 * @throws NullPointerException if the specified array is null
1268 public <T> T[] toArray(T[] a) {
1269 return toArrayList().toArray(a);
1273 * Returns an iterator over the elements in this deque in proper sequence.
1274 * The elements will be returned in order from first (head) to last (tail).
1276 * <p>The returned iterator is a "weakly consistent" iterator that
1277 * will never throw {@link java.util.ConcurrentModificationException
1278 * ConcurrentModificationException}, and guarantees to traverse
1279 * elements as they existed upon construction of the iterator, and
1280 * may (but is not guaranteed to) reflect any modifications
1281 * subsequent to construction.
1283 * @return an iterator over the elements in this deque in proper sequence
1285 public Iterator<E> iterator() {
1290 * Returns an iterator over the elements in this deque in reverse
1291 * sequential order. The elements will be returned in order from
1292 * last (tail) to first (head).
1294 * <p>The returned iterator is a "weakly consistent" iterator that
1295 * will never throw {@link java.util.ConcurrentModificationException
1296 * ConcurrentModificationException}, and guarantees to traverse
1297 * elements as they existed upon construction of the iterator, and
1298 * may (but is not guaranteed to) reflect any modifications
1299 * subsequent to construction.
1301 * @return an iterator over the elements in this deque in reverse order
1303 public Iterator<E> descendingIterator() {
1304 return new DescendingItr();
1307 private abstract class AbstractItr implements Iterator<E> {
1309 * Next node to return item for.
1311 private Node<E> nextNode;
1314 * nextItem holds on to item fields because once we claim
1315 * that an element exists in hasNext(), we must return it in
1316 * the following next() call even if it was in the process of
1317 * being removed when hasNext() was called.
1322 * Node returned by most recent call to next. Needed by remove.
1323 * Reset to null if this element is deleted by a call to remove.
1325 private Node<E> lastRet;
1327 abstract Node<E> startNode();
1328 abstract Node<E> nextNode(Node<E> p);
1335 * Sets nextNode and nextItem to next valid node, or to null
1338 private void advance() {
1341 Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
1342 for (;; p = nextNode(p)) {
1344 // p might be active end or TERMINATOR node; both are OK
1358 public boolean hasNext() {
1359 return nextItem != null;
1364 if (item == null) throw new NoSuchElementException();
1369 public void remove() {
1370 Node<E> l = lastRet;
1371 if (l == null) throw new IllegalStateException();
1378 /** Forward iterator */
1379 private class Itr extends AbstractItr {
1380 Node<E> startNode() { return first(); }
1381 Node<E> nextNode(Node<E> p) { return succ(p); }
1384 /** Descending iterator */
1385 private class DescendingItr extends AbstractItr {
1386 Node<E> startNode() { return last(); }
1387 Node<E> nextNode(Node<E> p) { return pred(p); }
1391 * Saves the state to a stream (that is, serializes it).
1393 * @serialData All of the elements (each an {@code E}) in
1394 * the proper order, followed by a null
1395 * @param s the stream
1397 private void writeObject(java.io.ObjectOutputStream s)
1398 throws java.io.IOException {
1400 // Write out any hidden stuff
1401 s.defaultWriteObject();
1403 // Write out all elements in the proper order.
1404 for (Node<E> p = first(); p != null; p = succ(p)) {
1407 s.writeObject(item);
1410 // Use trailing null as sentinel
1411 s.writeObject(null);
1415 * Reconstitutes the instance from a stream (that is, deserializes it).
1416 * @param s the stream
1418 private void readObject(java.io.ObjectInputStream s)
1419 throws java.io.IOException, ClassNotFoundException {
1420 s.defaultReadObject();
1422 // Read in elements until trailing null sentinel found
1423 Node<E> h = null, t = null;
1425 while ((item = s.readObject()) != null) {
1426 @SuppressWarnings("unchecked")
1427 Node<E> newNode = new Node<E>((E) item);
1431 t.lazySetNext(newNode);
1432 newNode.lazySetPrev(t);
1440 private boolean casHead(Node<E> cmp, Node<E> val) {
1441 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
1444 private boolean casTail(Node<E> cmp, Node<E> val) {
1445 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
1450 private static final sun.misc.Unsafe UNSAFE;
1451 private static final long headOffset;
1452 private static final long tailOffset;
1454 PREV_TERMINATOR = new Node<Object>();
1455 PREV_TERMINATOR.next = PREV_TERMINATOR;
1456 NEXT_TERMINATOR = new Node<Object>();
1457 NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
1459 UNSAFE = sun.misc.Unsafe.getUnsafe();
1460 Class k = ConcurrentLinkedDeque.class;
1461 headOffset = UNSAFE.objectFieldOffset
1462 (k.getDeclaredField("head"));
1463 tailOffset = UNSAFE.objectFieldOffset
1464 (k.getDeclaredField("tail"));
1465 } catch (Exception e) {