rt/emul/compact/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 12:51:03 +0100
changeset 1895 bfaf3300b7ba
parent 1890 212417b74b72
permissions -rw-r--r--
Making java.util.concurrent package compilable except ForkJoinPool
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3  *
     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.
     9  *
    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).
    15  *
    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.
    19  *
    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
    22  * questions.
    23  */
    24 
    25 /*
    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
    29  * file:
    30  *
    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/
    34  */
    35 
    36 package java.util.concurrent;
    37 
    38 import java.util.AbstractQueue;
    39 import java.util.ArrayList;
    40 import java.util.Collection;
    41 import java.util.Iterator;
    42 import java.util.NoSuchElementException;
    43 import java.util.Queue;
    44 
    45 /**
    46  * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
    47  * This queue orders elements FIFO (first-in-first-out).
    48  * The <em>head</em> of the queue is that element that has been on the
    49  * queue the longest time.
    50  * The <em>tail</em> of the queue is that element that has been on the
    51  * queue the shortest time. New elements
    52  * are inserted at the tail of the queue, and the queue retrieval
    53  * operations obtain elements at the head of the queue.
    54  * A {@code ConcurrentLinkedQueue} is an appropriate choice when
    55  * many threads will share access to a common collection.
    56  * Like most other concurrent collection implementations, this class
    57  * does not permit the use of {@code null} elements.
    58  *
    59  * <p>This implementation employs an efficient &quot;wait-free&quot;
    60  * algorithm based on one described in <a
    61  * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
    62  * Fast, and Practical Non-Blocking and Blocking Concurrent Queue
    63  * Algorithms</a> by Maged M. Michael and Michael L. Scott.
    64  *
    65  * <p>Iterators are <i>weakly consistent</i>, returning elements
    66  * reflecting the state of the queue at some point at or since the
    67  * creation of the iterator.  They do <em>not</em> throw {@link
    68  * java.util.ConcurrentModificationException}, and may proceed concurrently
    69  * with other operations.  Elements contained in the queue since the creation
    70  * of the iterator will be returned exactly once.
    71  *
    72  * <p>Beware that, unlike in most collections, the {@code size} method
    73  * is <em>NOT</em> a constant-time operation. Because of the
    74  * asynchronous nature of these queues, determining the current number
    75  * of elements requires a traversal of the elements, and so may report
    76  * inaccurate results if this collection is modified during traversal.
    77  * Additionally, the bulk operations {@code addAll},
    78  * {@code removeAll}, {@code retainAll}, {@code containsAll},
    79  * {@code equals}, and {@code toArray} are <em>not</em> guaranteed
    80  * to be performed atomically. For example, an iterator operating
    81  * concurrently with an {@code addAll} operation might view only some
    82  * of the added elements.
    83  *
    84  * <p>This class and its iterator implement all of the <em>optional</em>
    85  * methods of the {@link Queue} and {@link Iterator} interfaces.
    86  *
    87  * <p>Memory consistency effects: As with other concurrent
    88  * collections, actions in a thread prior to placing an object into a
    89  * {@code ConcurrentLinkedQueue}
    90  * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
    91  * actions subsequent to the access or removal of that element from
    92  * the {@code ConcurrentLinkedQueue} in another thread.
    93  *
    94  * <p>This class is a member of the
    95  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
    96  * Java Collections Framework</a>.
    97  *
    98  * @since 1.5
    99  * @author Doug Lea
   100  * @param <E> the type of elements held in this collection
   101  *
   102  */
   103 public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
   104         implements Queue<E>, java.io.Serializable {
   105     private static final long serialVersionUID = 196745693267521676L;
   106 
   107     /*
   108      * This is a modification of the Michael & Scott algorithm,
   109      * adapted for a garbage-collected environment, with support for
   110      * interior node deletion (to support remove(Object)).  For
   111      * explanation, read the paper.
   112      *
   113      * Note that like most non-blocking algorithms in this package,
   114      * this implementation relies on the fact that in garbage
   115      * collected systems, there is no possibility of ABA problems due
   116      * to recycled nodes, so there is no need to use "counted
   117      * pointers" or related techniques seen in versions used in
   118      * non-GC'ed settings.
   119      *
   120      * The fundamental invariants are:
   121      * - There is exactly one (last) Node with a null next reference,
   122      *   which is CASed when enqueueing.  This last Node can be
   123      *   reached in O(1) time from tail, but tail is merely an
   124      *   optimization - it can always be reached in O(N) time from
   125      *   head as well.
   126      * - The elements contained in the queue are the non-null items in
   127      *   Nodes that are reachable from head.  CASing the item
   128      *   reference of a Node to null atomically removes it from the
   129      *   queue.  Reachability of all elements from head must remain
   130      *   true even in the case of concurrent modifications that cause
   131      *   head to advance.  A dequeued Node may remain in use
   132      *   indefinitely due to creation of an Iterator or simply a
   133      *   poll() that has lost its time slice.
   134      *
   135      * The above might appear to imply that all Nodes are GC-reachable
   136      * from a predecessor dequeued Node.  That would cause two problems:
   137      * - allow a rogue Iterator to cause unbounded memory retention
   138      * - cause cross-generational linking of old Nodes to new Nodes if
   139      *   a Node was tenured while live, which generational GCs have a
   140      *   hard time dealing with, causing repeated major collections.
   141      * However, only non-deleted Nodes need to be reachable from
   142      * dequeued Nodes, and reachability does not necessarily have to
   143      * be of the kind understood by the GC.  We use the trick of
   144      * linking a Node that has just been dequeued to itself.  Such a
   145      * self-link implicitly means to advance to head.
   146      *
   147      * Both head and tail are permitted to lag.  In fact, failing to
   148      * update them every time one could is a significant optimization
   149      * (fewer CASes). As with LinkedTransferQueue (see the internal
   150      * documentation for that class), we use a slack threshold of two;
   151      * that is, we update head/tail when the current pointer appears
   152      * to be two or more steps away from the first/last node.
   153      *
   154      * Since head and tail are updated concurrently and independently,
   155      * it is possible for tail to lag behind head (why not)?
   156      *
   157      * CASing a Node's item reference to null atomically removes the
   158      * element from the queue.  Iterators skip over Nodes with null
   159      * items.  Prior implementations of this class had a race between
   160      * poll() and remove(Object) where the same element would appear
   161      * to be successfully removed by two concurrent operations.  The
   162      * method remove(Object) also lazily unlinks deleted Nodes, but
   163      * this is merely an optimization.
   164      *
   165      * When constructing a Node (before enqueuing it) we avoid paying
   166      * for a volatile write to item by using Unsafe.putObject instead
   167      * of a normal write.  This allows the cost of enqueue to be
   168      * "one-and-a-half" CASes.
   169      *
   170      * Both head and tail may or may not point to a Node with a
   171      * non-null item.  If the queue is empty, all items must of course
   172      * be null.  Upon creation, both head and tail refer to a dummy
   173      * Node with null item.  Both head and tail are only updated using
   174      * CAS, so they never regress, although again this is merely an
   175      * optimization.
   176      */
   177 
   178     private static class Node<E> {
   179         volatile E item;
   180         volatile Node<E> next;
   181 
   182         /**
   183          * Constructs a new node.  Uses relaxed write because item can
   184          * only be seen after publication via casNext.
   185          */
   186         Node(E item) {
   187             this.item = item;
   188         }
   189 
   190         boolean casItem(E cmp, E val) {
   191             if (item == cmp) {
   192                 item = val;
   193                 return true;
   194             }
   195             return false;
   196         }
   197 
   198         void lazySetNext(Node<E> val) {
   199             this.next = val;
   200         }
   201 
   202         boolean casNext(Node<E> cmp, Node<E> val) {
   203             if (next == cmp) {
   204                 next = val;
   205                 return true;
   206             }
   207             return false;
   208         }
   209     }
   210 
   211     /**
   212      * A node from which the first live (non-deleted) node (if any)
   213      * can be reached in O(1) time.
   214      * Invariants:
   215      * - all live nodes are reachable from head via succ()
   216      * - head != null
   217      * - (tmp = head).next != tmp || tmp != head
   218      * Non-invariants:
   219      * - head.item may or may not be null.
   220      * - it is permitted for tail to lag behind head, that is, for tail
   221      *   to not be reachable from head!
   222      */
   223     private transient volatile Node<E> head;
   224 
   225     /**
   226      * A node from which the last node on list (that is, the unique
   227      * node with node.next == null) can be reached in O(1) time.
   228      * Invariants:
   229      * - the last node is always reachable from tail via succ()
   230      * - tail != null
   231      * Non-invariants:
   232      * - tail.item may or may not be null.
   233      * - it is permitted for tail to lag behind head, that is, for tail
   234      *   to not be reachable from head!
   235      * - tail.next may or may not be self-pointing to tail.
   236      */
   237     private transient volatile Node<E> tail;
   238 
   239 
   240     /**
   241      * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
   242      */
   243     public ConcurrentLinkedQueue() {
   244         head = tail = new Node<E>(null);
   245     }
   246 
   247     /**
   248      * Creates a {@code ConcurrentLinkedQueue}
   249      * initially containing the elements of the given collection,
   250      * added in traversal order of the collection's iterator.
   251      *
   252      * @param c the collection of elements to initially contain
   253      * @throws NullPointerException if the specified collection or any
   254      *         of its elements are null
   255      */
   256     public ConcurrentLinkedQueue(Collection<? extends E> c) {
   257         Node<E> h = null, t = null;
   258         for (E e : c) {
   259             checkNotNull(e);
   260             Node<E> newNode = new Node<E>(e);
   261             if (h == null)
   262                 h = t = newNode;
   263             else {
   264                 t.lazySetNext(newNode);
   265                 t = newNode;
   266             }
   267         }
   268         if (h == null)
   269             h = t = new Node<E>(null);
   270         head = h;
   271         tail = t;
   272     }
   273 
   274     // Have to override just to update the javadoc
   275 
   276     /**
   277      * Inserts the specified element at the tail of this queue.
   278      * As the queue is unbounded, this method will never throw
   279      * {@link IllegalStateException} or return {@code false}.
   280      *
   281      * @return {@code true} (as specified by {@link Collection#add})
   282      * @throws NullPointerException if the specified element is null
   283      */
   284     public boolean add(E e) {
   285         return offer(e);
   286     }
   287 
   288     /**
   289      * Try to CAS head to p. If successful, repoint old head to itself
   290      * as sentinel for succ(), below.
   291      */
   292     final void updateHead(Node<E> h, Node<E> p) {
   293         if (h != p && casHead(h, p))
   294             h.lazySetNext(h);
   295     }
   296 
   297     /**
   298      * Returns the successor of p, or the head node if p.next has been
   299      * linked to self, which will only be true if traversing with a
   300      * stale pointer that is now off the list.
   301      */
   302     final Node<E> succ(Node<E> p) {
   303         Node<E> next = p.next;
   304         return (p == next) ? head : next;
   305     }
   306 
   307     /**
   308      * Inserts the specified element at the tail of this queue.
   309      * As the queue is unbounded, this method will never return {@code false}.
   310      *
   311      * @return {@code true} (as specified by {@link Queue#offer})
   312      * @throws NullPointerException if the specified element is null
   313      */
   314     public boolean offer(E e) {
   315         checkNotNull(e);
   316         final Node<E> newNode = new Node<E>(e);
   317 
   318         for (Node<E> t = tail, p = t;;) {
   319             Node<E> q = p.next;
   320             if (q == null) {
   321                 // p is last node
   322                 if (p.casNext(null, newNode)) {
   323                     // Successful CAS is the linearization point
   324                     // for e to become an element of this queue,
   325                     // and for newNode to become "live".
   326                     if (p != t) // hop two nodes at a time
   327                         casTail(t, newNode);  // Failure is OK.
   328                     return true;
   329                 }
   330                 // Lost CAS race to another thread; re-read next
   331             }
   332             else if (p == q)
   333                 // We have fallen off list.  If tail is unchanged, it
   334                 // will also be off-list, in which case we need to
   335                 // jump to head, from which all live nodes are always
   336                 // reachable.  Else the new tail is a better bet.
   337                 p = (t != (t = tail)) ? t : head;
   338             else
   339                 // Check for tail updates after two hops.
   340                 p = (p != t && t != (t = tail)) ? t : q;
   341         }
   342     }
   343 
   344     public E poll() {
   345         restartFromHead:
   346         for (;;) {
   347             for (Node<E> h = head, p = h, q;;) {
   348                 E item = p.item;
   349 
   350                 if (item != null && p.casItem(item, null)) {
   351                     // Successful CAS is the linearization point
   352                     // for item to be removed from this queue.
   353                     if (p != h) // hop two nodes at a time
   354                         updateHead(h, ((q = p.next) != null) ? q : p);
   355                     return item;
   356                 }
   357                 else if ((q = p.next) == null) {
   358                     updateHead(h, p);
   359                     return null;
   360                 }
   361                 else if (p == q)
   362                     continue restartFromHead;
   363                 else
   364                     p = q;
   365             }
   366         }
   367     }
   368 
   369     public E peek() {
   370         restartFromHead:
   371         for (;;) {
   372             for (Node<E> h = head, p = h, q;;) {
   373                 E item = p.item;
   374                 if (item != null || (q = p.next) == null) {
   375                     updateHead(h, p);
   376                     return item;
   377                 }
   378                 else if (p == q)
   379                     continue restartFromHead;
   380                 else
   381                     p = q;
   382             }
   383         }
   384     }
   385 
   386     /**
   387      * Returns the first live (non-deleted) node on list, or null if none.
   388      * This is yet another variant of poll/peek; here returning the
   389      * first node, not element.  We could make peek() a wrapper around
   390      * first(), but that would cost an extra volatile read of item,
   391      * and the need to add a retry loop to deal with the possibility
   392      * of losing a race to a concurrent poll().
   393      */
   394     Node<E> first() {
   395         restartFromHead:
   396         for (;;) {
   397             for (Node<E> h = head, p = h, q;;) {
   398                 boolean hasItem = (p.item != null);
   399                 if (hasItem || (q = p.next) == null) {
   400                     updateHead(h, p);
   401                     return hasItem ? p : null;
   402                 }
   403                 else if (p == q)
   404                     continue restartFromHead;
   405                 else
   406                     p = q;
   407             }
   408         }
   409     }
   410 
   411     /**
   412      * Returns {@code true} if this queue contains no elements.
   413      *
   414      * @return {@code true} if this queue contains no elements
   415      */
   416     public boolean isEmpty() {
   417         return first() == null;
   418     }
   419 
   420     /**
   421      * Returns the number of elements in this queue.  If this queue
   422      * contains more than {@code Integer.MAX_VALUE} elements, returns
   423      * {@code Integer.MAX_VALUE}.
   424      *
   425      * <p>Beware that, unlike in most collections, this method is
   426      * <em>NOT</em> a constant-time operation. Because of the
   427      * asynchronous nature of these queues, determining the current
   428      * number of elements requires an O(n) traversal.
   429      * Additionally, if elements are added or removed during execution
   430      * of this method, the returned result may be inaccurate.  Thus,
   431      * this method is typically not very useful in concurrent
   432      * applications.
   433      *
   434      * @return the number of elements in this queue
   435      */
   436     public int size() {
   437         int count = 0;
   438         for (Node<E> p = first(); p != null; p = succ(p))
   439             if (p.item != null)
   440                 // Collection.size() spec says to max out
   441                 if (++count == Integer.MAX_VALUE)
   442                     break;
   443         return count;
   444     }
   445 
   446     /**
   447      * Returns {@code true} if this queue contains the specified element.
   448      * More formally, returns {@code true} if and only if this queue contains
   449      * at least one element {@code e} such that {@code o.equals(e)}.
   450      *
   451      * @param o object to be checked for containment in this queue
   452      * @return {@code true} if this queue contains the specified element
   453      */
   454     public boolean contains(Object o) {
   455         if (o == null) return false;
   456         for (Node<E> p = first(); p != null; p = succ(p)) {
   457             E item = p.item;
   458             if (item != null && o.equals(item))
   459                 return true;
   460         }
   461         return false;
   462     }
   463 
   464     /**
   465      * Removes a single instance of the specified element from this queue,
   466      * if it is present.  More formally, removes an element {@code e} such
   467      * that {@code o.equals(e)}, if this queue contains one or more such
   468      * elements.
   469      * Returns {@code true} if this queue contained the specified element
   470      * (or equivalently, if this queue changed as a result of the call).
   471      *
   472      * @param o element to be removed from this queue, if present
   473      * @return {@code true} if this queue changed as a result of the call
   474      */
   475     public boolean remove(Object o) {
   476         if (o == null) return false;
   477         Node<E> pred = null;
   478         for (Node<E> p = first(); p != null; p = succ(p)) {
   479             E item = p.item;
   480             if (item != null &&
   481                 o.equals(item) &&
   482                 p.casItem(item, null)) {
   483                 Node<E> next = succ(p);
   484                 if (pred != null && next != null)
   485                     pred.casNext(p, next);
   486                 return true;
   487             }
   488             pred = p;
   489         }
   490         return false;
   491     }
   492 
   493     /**
   494      * Appends all of the elements in the specified collection to the end of
   495      * this queue, in the order that they are returned by the specified
   496      * collection's iterator.  Attempts to {@code addAll} of a queue to
   497      * itself result in {@code IllegalArgumentException}.
   498      *
   499      * @param c the elements to be inserted into this queue
   500      * @return {@code true} if this queue changed as a result of the call
   501      * @throws NullPointerException if the specified collection or any
   502      *         of its elements are null
   503      * @throws IllegalArgumentException if the collection is this queue
   504      */
   505     public boolean addAll(Collection<? extends E> c) {
   506         if (c == this)
   507             // As historically specified in AbstractQueue#addAll
   508             throw new IllegalArgumentException();
   509 
   510         // Copy c into a private chain of Nodes
   511         Node<E> beginningOfTheEnd = null, last = null;
   512         for (E e : c) {
   513             checkNotNull(e);
   514             Node<E> newNode = new Node<E>(e);
   515             if (beginningOfTheEnd == null)
   516                 beginningOfTheEnd = last = newNode;
   517             else {
   518                 last.lazySetNext(newNode);
   519                 last = newNode;
   520             }
   521         }
   522         if (beginningOfTheEnd == null)
   523             return false;
   524 
   525         // Atomically append the chain at the tail of this collection
   526         for (Node<E> t = tail, p = t;;) {
   527             Node<E> q = p.next;
   528             if (q == null) {
   529                 // p is last node
   530                 if (p.casNext(null, beginningOfTheEnd)) {
   531                     // Successful CAS is the linearization point
   532                     // for all elements to be added to this queue.
   533                     if (!casTail(t, last)) {
   534                         // Try a little harder to update tail,
   535                         // since we may be adding many elements.
   536                         t = tail;
   537                         if (last.next == null)
   538                             casTail(t, last);
   539                     }
   540                     return true;
   541                 }
   542                 // Lost CAS race to another thread; re-read next
   543             }
   544             else if (p == q)
   545                 // We have fallen off list.  If tail is unchanged, it
   546                 // will also be off-list, in which case we need to
   547                 // jump to head, from which all live nodes are always
   548                 // reachable.  Else the new tail is a better bet.
   549                 p = (t != (t = tail)) ? t : head;
   550             else
   551                 // Check for tail updates after two hops.
   552                 p = (p != t && t != (t = tail)) ? t : q;
   553         }
   554     }
   555 
   556     /**
   557      * Returns an array containing all of the elements in this queue, in
   558      * proper sequence.
   559      *
   560      * <p>The returned array will be "safe" in that no references to it are
   561      * maintained by this queue.  (In other words, this method must allocate
   562      * a new array).  The caller is thus free to modify the returned array.
   563      *
   564      * <p>This method acts as bridge between array-based and collection-based
   565      * APIs.
   566      *
   567      * @return an array containing all of the elements in this queue
   568      */
   569     public Object[] toArray() {
   570         // Use ArrayList to deal with resizing.
   571         ArrayList<E> al = new ArrayList<E>();
   572         for (Node<E> p = first(); p != null; p = succ(p)) {
   573             E item = p.item;
   574             if (item != null)
   575                 al.add(item);
   576         }
   577         return al.toArray();
   578     }
   579 
   580     /**
   581      * Returns an array containing all of the elements in this queue, in
   582      * proper sequence; the runtime type of the returned array is that of
   583      * the specified array.  If the queue fits in the specified array, it
   584      * is returned therein.  Otherwise, a new array is allocated with the
   585      * runtime type of the specified array and the size of this queue.
   586      *
   587      * <p>If this queue fits in the specified array with room to spare
   588      * (i.e., the array has more elements than this queue), the element in
   589      * the array immediately following the end of the queue is set to
   590      * {@code null}.
   591      *
   592      * <p>Like the {@link #toArray()} method, this method acts as bridge between
   593      * array-based and collection-based APIs.  Further, this method allows
   594      * precise control over the runtime type of the output array, and may,
   595      * under certain circumstances, be used to save allocation costs.
   596      *
   597      * <p>Suppose {@code x} is a queue known to contain only strings.
   598      * The following code can be used to dump the queue into a newly
   599      * allocated array of {@code String}:
   600      *
   601      * <pre>
   602      *     String[] y = x.toArray(new String[0]);</pre>
   603      *
   604      * Note that {@code toArray(new Object[0])} is identical in function to
   605      * {@code toArray()}.
   606      *
   607      * @param a the array into which the elements of the queue are to
   608      *          be stored, if it is big enough; otherwise, a new array of the
   609      *          same runtime type is allocated for this purpose
   610      * @return an array containing all of the elements in this queue
   611      * @throws ArrayStoreException if the runtime type of the specified array
   612      *         is not a supertype of the runtime type of every element in
   613      *         this queue
   614      * @throws NullPointerException if the specified array is null
   615      */
   616     @SuppressWarnings("unchecked")
   617     public <T> T[] toArray(T[] a) {
   618         // try to use sent-in array
   619         int k = 0;
   620         Node<E> p;
   621         for (p = first(); p != null && k < a.length; p = succ(p)) {
   622             E item = p.item;
   623             if (item != null)
   624                 a[k++] = (T)item;
   625         }
   626         if (p == null) {
   627             if (k < a.length)
   628                 a[k] = null;
   629             return a;
   630         }
   631 
   632         // If won't fit, use ArrayList version
   633         ArrayList<E> al = new ArrayList<E>();
   634         for (Node<E> q = first(); q != null; q = succ(q)) {
   635             E item = q.item;
   636             if (item != null)
   637                 al.add(item);
   638         }
   639         return al.toArray(a);
   640     }
   641 
   642     /**
   643      * Returns an iterator over the elements in this queue in proper sequence.
   644      * The elements will be returned in order from first (head) to last (tail).
   645      *
   646      * <p>The returned iterator is a "weakly consistent" iterator that
   647      * will never throw {@link java.util.ConcurrentModificationException
   648      * ConcurrentModificationException}, and guarantees to traverse
   649      * elements as they existed upon construction of the iterator, and
   650      * may (but is not guaranteed to) reflect any modifications
   651      * subsequent to construction.
   652      *
   653      * @return an iterator over the elements in this queue in proper sequence
   654      */
   655     public Iterator<E> iterator() {
   656         return new Itr();
   657     }
   658 
   659     private class Itr implements Iterator<E> {
   660         /**
   661          * Next node to return item for.
   662          */
   663         private Node<E> nextNode;
   664 
   665         /**
   666          * nextItem holds on to item fields because once we claim
   667          * that an element exists in hasNext(), we must return it in
   668          * the following next() call even if it was in the process of
   669          * being removed when hasNext() was called.
   670          */
   671         private E nextItem;
   672 
   673         /**
   674          * Node of the last returned item, to support remove.
   675          */
   676         private Node<E> lastRet;
   677 
   678         Itr() {
   679             advance();
   680         }
   681 
   682         /**
   683          * Moves to next valid node and returns item to return for
   684          * next(), or null if no such.
   685          */
   686         private E advance() {
   687             lastRet = nextNode;
   688             E x = nextItem;
   689 
   690             Node<E> pred, p;
   691             if (nextNode == null) {
   692                 p = first();
   693                 pred = null;
   694             } else {
   695                 pred = nextNode;
   696                 p = succ(nextNode);
   697             }
   698 
   699             for (;;) {
   700                 if (p == null) {
   701                     nextNode = null;
   702                     nextItem = null;
   703                     return x;
   704                 }
   705                 E item = p.item;
   706                 if (item != null) {
   707                     nextNode = p;
   708                     nextItem = item;
   709                     return x;
   710                 } else {
   711                     // skip over nulls
   712                     Node<E> next = succ(p);
   713                     if (pred != null && next != null)
   714                         pred.casNext(p, next);
   715                     p = next;
   716                 }
   717             }
   718         }
   719 
   720         public boolean hasNext() {
   721             return nextNode != null;
   722         }
   723 
   724         public E next() {
   725             if (nextNode == null) throw new NoSuchElementException();
   726             return advance();
   727         }
   728 
   729         public void remove() {
   730             Node<E> l = lastRet;
   731             if (l == null) throw new IllegalStateException();
   732             // rely on a future traversal to relink.
   733             l.item = null;
   734             lastRet = null;
   735         }
   736     }
   737 
   738     /**
   739      * Saves the state to a stream (that is, serializes it).
   740      *
   741      * @serialData All of the elements (each an {@code E}) in
   742      * the proper order, followed by a null
   743      * @param s the stream
   744      */
   745     private void writeObject(java.io.ObjectOutputStream s)
   746         throws java.io.IOException {
   747 
   748         // Write out any hidden stuff
   749         s.defaultWriteObject();
   750 
   751         // Write out all elements in the proper order.
   752         for (Node<E> p = first(); p != null; p = succ(p)) {
   753             Object item = p.item;
   754             if (item != null)
   755                 s.writeObject(item);
   756         }
   757 
   758         // Use trailing null as sentinel
   759         s.writeObject(null);
   760     }
   761 
   762     /**
   763      * Reconstitutes the instance from a stream (that is, deserializes it).
   764      * @param s the stream
   765      */
   766     private void readObject(java.io.ObjectInputStream s)
   767         throws java.io.IOException, ClassNotFoundException {
   768         s.defaultReadObject();
   769 
   770         // Read in elements until trailing null sentinel found
   771         Node<E> h = null, t = null;
   772         Object item;
   773         while ((item = s.readObject()) != null) {
   774             @SuppressWarnings("unchecked")
   775             Node<E> newNode = new Node<E>((E) item);
   776             if (h == null)
   777                 h = t = newNode;
   778             else {
   779                 t.lazySetNext(newNode);
   780                 t = newNode;
   781             }
   782         }
   783         if (h == null)
   784             h = t = new Node<E>(null);
   785         head = h;
   786         tail = t;
   787     }
   788 
   789     /**
   790      * Throws NullPointerException if argument is null.
   791      *
   792      * @param v the element
   793      */
   794     private static void checkNotNull(Object v) {
   795         if (v == null)
   796             throw new NullPointerException();
   797     }
   798 
   799     private boolean casTail(Node<E> cmp, Node<E> val) {
   800         if (tail == cmp) {
   801             tail = val;
   802             return true;
   803         }
   804         return false;
   805     }
   806 
   807     private boolean casHead(Node<E> cmp, Node<E> val) {
   808         if (head == cmp) {
   809             head = val;
   810             return true;
   811         }
   812         return false;
   813     }
   814 
   815 }