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