rt/emul/compact/src/main/java/java/util/concurrent/LinkedTransferQueue.java
branchjdk7-b147
changeset 1890 212417b74b72
child 1895 bfaf3300b7ba
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/util/concurrent/LinkedTransferQueue.java	Sat Mar 19 10:46:31 2016 +0100
     1.3 @@ -0,0 +1,1351 @@
     1.4 +/*
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.6 + *
     1.7 + * This code is free software; you can redistribute it and/or modify it
     1.8 + * under the terms of the GNU General Public License version 2 only, as
     1.9 + * published by the Free Software Foundation.  Oracle designates this
    1.10 + * particular file as subject to the "Classpath" exception as provided
    1.11 + * by Oracle in the LICENSE file that accompanied this code.
    1.12 + *
    1.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.15 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.16 + * version 2 for more details (a copy is included in the LICENSE file that
    1.17 + * accompanied this code).
    1.18 + *
    1.19 + * You should have received a copy of the GNU General Public License version
    1.20 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.22 + *
    1.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.24 + * or visit www.oracle.com if you need additional information or have any
    1.25 + * questions.
    1.26 + */
    1.27 +
    1.28 +/*
    1.29 + * This file is available under and governed by the GNU General Public
    1.30 + * License version 2 only, as published by the Free Software Foundation.
    1.31 + * However, the following notice accompanied the original version of this
    1.32 + * file:
    1.33 + *
    1.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
    1.35 + * Expert Group and released to the public domain, as explained at
    1.36 + * http://creativecommons.org/publicdomain/zero/1.0/
    1.37 + */
    1.38 +
    1.39 +package java.util.concurrent;
    1.40 +
    1.41 +import java.util.AbstractQueue;
    1.42 +import java.util.Collection;
    1.43 +import java.util.Iterator;
    1.44 +import java.util.NoSuchElementException;
    1.45 +import java.util.Queue;
    1.46 +import java.util.concurrent.TimeUnit;
    1.47 +import java.util.concurrent.locks.LockSupport;
    1.48 +
    1.49 +/**
    1.50 + * An unbounded {@link TransferQueue} based on linked nodes.
    1.51 + * This queue orders elements FIFO (first-in-first-out) with respect
    1.52 + * to any given producer.  The <em>head</em> of the queue is that
    1.53 + * element that has been on the queue the longest time for some
    1.54 + * producer.  The <em>tail</em> of the queue is that element that has
    1.55 + * been on the queue the shortest time for some producer.
    1.56 + *
    1.57 + * <p>Beware that, unlike in most collections, the {@code size} method
    1.58 + * is <em>NOT</em> a constant-time operation. Because of the
    1.59 + * asynchronous nature of these queues, determining the current number
    1.60 + * of elements requires a traversal of the elements, and so may report
    1.61 + * inaccurate results if this collection is modified during traversal.
    1.62 + * Additionally, the bulk operations {@code addAll},
    1.63 + * {@code removeAll}, {@code retainAll}, {@code containsAll},
    1.64 + * {@code equals}, and {@code toArray} are <em>not</em> guaranteed
    1.65 + * to be performed atomically. For example, an iterator operating
    1.66 + * concurrently with an {@code addAll} operation might view only some
    1.67 + * of the added elements.
    1.68 + *
    1.69 + * <p>This class and its iterator implement all of the
    1.70 + * <em>optional</em> methods of the {@link Collection} and {@link
    1.71 + * Iterator} interfaces.
    1.72 + *
    1.73 + * <p>Memory consistency effects: As with other concurrent
    1.74 + * collections, actions in a thread prior to placing an object into a
    1.75 + * {@code LinkedTransferQueue}
    1.76 + * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
    1.77 + * actions subsequent to the access or removal of that element from
    1.78 + * the {@code LinkedTransferQueue} in another thread.
    1.79 + *
    1.80 + * <p>This class is a member of the
    1.81 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
    1.82 + * Java Collections Framework</a>.
    1.83 + *
    1.84 + * @since 1.7
    1.85 + * @author Doug Lea
    1.86 + * @param <E> the type of elements held in this collection
    1.87 + */
    1.88 +public class LinkedTransferQueue<E> extends AbstractQueue<E>
    1.89 +    implements TransferQueue<E>, java.io.Serializable {
    1.90 +    private static final long serialVersionUID = -3223113410248163686L;
    1.91 +
    1.92 +    /*
    1.93 +     * *** Overview of Dual Queues with Slack ***
    1.94 +     *
    1.95 +     * Dual Queues, introduced by Scherer and Scott
    1.96 +     * (http://www.cs.rice.edu/~wns1/papers/2004-DISC-DDS.pdf) are
    1.97 +     * (linked) queues in which nodes may represent either data or
    1.98 +     * requests.  When a thread tries to enqueue a data node, but
    1.99 +     * encounters a request node, it instead "matches" and removes it;
   1.100 +     * and vice versa for enqueuing requests. Blocking Dual Queues
   1.101 +     * arrange that threads enqueuing unmatched requests block until
   1.102 +     * other threads provide the match. Dual Synchronous Queues (see
   1.103 +     * Scherer, Lea, & Scott
   1.104 +     * http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf)
   1.105 +     * additionally arrange that threads enqueuing unmatched data also
   1.106 +     * block.  Dual Transfer Queues support all of these modes, as
   1.107 +     * dictated by callers.
   1.108 +     *
   1.109 +     * A FIFO dual queue may be implemented using a variation of the
   1.110 +     * Michael & Scott (M&S) lock-free queue algorithm
   1.111 +     * (http://www.cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf).
   1.112 +     * It maintains two pointer fields, "head", pointing to a
   1.113 +     * (matched) node that in turn points to the first actual
   1.114 +     * (unmatched) queue node (or null if empty); and "tail" that
   1.115 +     * points to the last node on the queue (or again null if
   1.116 +     * empty). For example, here is a possible queue with four data
   1.117 +     * elements:
   1.118 +     *
   1.119 +     *  head                tail
   1.120 +     *    |                   |
   1.121 +     *    v                   v
   1.122 +     *    M -> U -> U -> U -> U
   1.123 +     *
   1.124 +     * The M&S queue algorithm is known to be prone to scalability and
   1.125 +     * overhead limitations when maintaining (via CAS) these head and
   1.126 +     * tail pointers. This has led to the development of
   1.127 +     * contention-reducing variants such as elimination arrays (see
   1.128 +     * Moir et al http://portal.acm.org/citation.cfm?id=1074013) and
   1.129 +     * optimistic back pointers (see Ladan-Mozes & Shavit
   1.130 +     * http://people.csail.mit.edu/edya/publications/OptimisticFIFOQueue-journal.pdf).
   1.131 +     * However, the nature of dual queues enables a simpler tactic for
   1.132 +     * improving M&S-style implementations when dual-ness is needed.
   1.133 +     *
   1.134 +     * In a dual queue, each node must atomically maintain its match
   1.135 +     * status. While there are other possible variants, we implement
   1.136 +     * this here as: for a data-mode node, matching entails CASing an
   1.137 +     * "item" field from a non-null data value to null upon match, and
   1.138 +     * vice-versa for request nodes, CASing from null to a data
   1.139 +     * value. (Note that the linearization properties of this style of
   1.140 +     * queue are easy to verify -- elements are made available by
   1.141 +     * linking, and unavailable by matching.) Compared to plain M&S
   1.142 +     * queues, this property of dual queues requires one additional
   1.143 +     * successful atomic operation per enq/deq pair. But it also
   1.144 +     * enables lower cost variants of queue maintenance mechanics. (A
   1.145 +     * variation of this idea applies even for non-dual queues that
   1.146 +     * support deletion of interior elements, such as
   1.147 +     * j.u.c.ConcurrentLinkedQueue.)
   1.148 +     *
   1.149 +     * Once a node is matched, its match status can never again
   1.150 +     * change.  We may thus arrange that the linked list of them
   1.151 +     * contain a prefix of zero or more matched nodes, followed by a
   1.152 +     * suffix of zero or more unmatched nodes. (Note that we allow
   1.153 +     * both the prefix and suffix to be zero length, which in turn
   1.154 +     * means that we do not use a dummy header.)  If we were not
   1.155 +     * concerned with either time or space efficiency, we could
   1.156 +     * correctly perform enqueue and dequeue operations by traversing
   1.157 +     * from a pointer to the initial node; CASing the item of the
   1.158 +     * first unmatched node on match and CASing the next field of the
   1.159 +     * trailing node on appends. (Plus some special-casing when
   1.160 +     * initially empty).  While this would be a terrible idea in
   1.161 +     * itself, it does have the benefit of not requiring ANY atomic
   1.162 +     * updates on head/tail fields.
   1.163 +     *
   1.164 +     * We introduce here an approach that lies between the extremes of
   1.165 +     * never versus always updating queue (head and tail) pointers.
   1.166 +     * This offers a tradeoff between sometimes requiring extra
   1.167 +     * traversal steps to locate the first and/or last unmatched
   1.168 +     * nodes, versus the reduced overhead and contention of fewer
   1.169 +     * updates to queue pointers. For example, a possible snapshot of
   1.170 +     * a queue is:
   1.171 +     *
   1.172 +     *  head           tail
   1.173 +     *    |              |
   1.174 +     *    v              v
   1.175 +     *    M -> M -> U -> U -> U -> U
   1.176 +     *
   1.177 +     * The best value for this "slack" (the targeted maximum distance
   1.178 +     * between the value of "head" and the first unmatched node, and
   1.179 +     * similarly for "tail") is an empirical matter. We have found
   1.180 +     * that using very small constants in the range of 1-3 work best
   1.181 +     * over a range of platforms. Larger values introduce increasing
   1.182 +     * costs of cache misses and risks of long traversal chains, while
   1.183 +     * smaller values increase CAS contention and overhead.
   1.184 +     *
   1.185 +     * Dual queues with slack differ from plain M&S dual queues by
   1.186 +     * virtue of only sometimes updating head or tail pointers when
   1.187 +     * matching, appending, or even traversing nodes; in order to
   1.188 +     * maintain a targeted slack.  The idea of "sometimes" may be
   1.189 +     * operationalized in several ways. The simplest is to use a
   1.190 +     * per-operation counter incremented on each traversal step, and
   1.191 +     * to try (via CAS) to update the associated queue pointer
   1.192 +     * whenever the count exceeds a threshold. Another, that requires
   1.193 +     * more overhead, is to use random number generators to update
   1.194 +     * with a given probability per traversal step.
   1.195 +     *
   1.196 +     * In any strategy along these lines, because CASes updating
   1.197 +     * fields may fail, the actual slack may exceed targeted
   1.198 +     * slack. However, they may be retried at any time to maintain
   1.199 +     * targets.  Even when using very small slack values, this
   1.200 +     * approach works well for dual queues because it allows all
   1.201 +     * operations up to the point of matching or appending an item
   1.202 +     * (hence potentially allowing progress by another thread) to be
   1.203 +     * read-only, thus not introducing any further contention. As
   1.204 +     * described below, we implement this by performing slack
   1.205 +     * maintenance retries only after these points.
   1.206 +     *
   1.207 +     * As an accompaniment to such techniques, traversal overhead can
   1.208 +     * be further reduced without increasing contention of head
   1.209 +     * pointer updates: Threads may sometimes shortcut the "next" link
   1.210 +     * path from the current "head" node to be closer to the currently
   1.211 +     * known first unmatched node, and similarly for tail. Again, this
   1.212 +     * may be triggered with using thresholds or randomization.
   1.213 +     *
   1.214 +     * These ideas must be further extended to avoid unbounded amounts
   1.215 +     * of costly-to-reclaim garbage caused by the sequential "next"
   1.216 +     * links of nodes starting at old forgotten head nodes: As first
   1.217 +     * described in detail by Boehm
   1.218 +     * (http://portal.acm.org/citation.cfm?doid=503272.503282) if a GC
   1.219 +     * delays noticing that any arbitrarily old node has become
   1.220 +     * garbage, all newer dead nodes will also be unreclaimed.
   1.221 +     * (Similar issues arise in non-GC environments.)  To cope with
   1.222 +     * this in our implementation, upon CASing to advance the head
   1.223 +     * pointer, we set the "next" link of the previous head to point
   1.224 +     * only to itself; thus limiting the length of connected dead lists.
   1.225 +     * (We also take similar care to wipe out possibly garbage
   1.226 +     * retaining values held in other Node fields.)  However, doing so
   1.227 +     * adds some further complexity to traversal: If any "next"
   1.228 +     * pointer links to itself, it indicates that the current thread
   1.229 +     * has lagged behind a head-update, and so the traversal must
   1.230 +     * continue from the "head".  Traversals trying to find the
   1.231 +     * current tail starting from "tail" may also encounter
   1.232 +     * self-links, in which case they also continue at "head".
   1.233 +     *
   1.234 +     * It is tempting in slack-based scheme to not even use CAS for
   1.235 +     * updates (similarly to Ladan-Mozes & Shavit). However, this
   1.236 +     * cannot be done for head updates under the above link-forgetting
   1.237 +     * mechanics because an update may leave head at a detached node.
   1.238 +     * And while direct writes are possible for tail updates, they
   1.239 +     * increase the risk of long retraversals, and hence long garbage
   1.240 +     * chains, which can be much more costly than is worthwhile
   1.241 +     * considering that the cost difference of performing a CAS vs
   1.242 +     * write is smaller when they are not triggered on each operation
   1.243 +     * (especially considering that writes and CASes equally require
   1.244 +     * additional GC bookkeeping ("write barriers") that are sometimes
   1.245 +     * more costly than the writes themselves because of contention).
   1.246 +     *
   1.247 +     * *** Overview of implementation ***
   1.248 +     *
   1.249 +     * We use a threshold-based approach to updates, with a slack
   1.250 +     * threshold of two -- that is, we update head/tail when the
   1.251 +     * current pointer appears to be two or more steps away from the
   1.252 +     * first/last node. The slack value is hard-wired: a path greater
   1.253 +     * than one is naturally implemented by checking equality of
   1.254 +     * traversal pointers except when the list has only one element,
   1.255 +     * in which case we keep slack threshold at one. Avoiding tracking
   1.256 +     * explicit counts across method calls slightly simplifies an
   1.257 +     * already-messy implementation. Using randomization would
   1.258 +     * probably work better if there were a low-quality dirt-cheap
   1.259 +     * per-thread one available, but even ThreadLocalRandom is too
   1.260 +     * heavy for these purposes.
   1.261 +     *
   1.262 +     * With such a small slack threshold value, it is not worthwhile
   1.263 +     * to augment this with path short-circuiting (i.e., unsplicing
   1.264 +     * interior nodes) except in the case of cancellation/removal (see
   1.265 +     * below).
   1.266 +     *
   1.267 +     * We allow both the head and tail fields to be null before any
   1.268 +     * nodes are enqueued; initializing upon first append.  This
   1.269 +     * simplifies some other logic, as well as providing more
   1.270 +     * efficient explicit control paths instead of letting JVMs insert
   1.271 +     * implicit NullPointerExceptions when they are null.  While not
   1.272 +     * currently fully implemented, we also leave open the possibility
   1.273 +     * of re-nulling these fields when empty (which is complicated to
   1.274 +     * arrange, for little benefit.)
   1.275 +     *
   1.276 +     * All enqueue/dequeue operations are handled by the single method
   1.277 +     * "xfer" with parameters indicating whether to act as some form
   1.278 +     * of offer, put, poll, take, or transfer (each possibly with
   1.279 +     * timeout). The relative complexity of using one monolithic
   1.280 +     * method outweighs the code bulk and maintenance problems of
   1.281 +     * using separate methods for each case.
   1.282 +     *
   1.283 +     * Operation consists of up to three phases. The first is
   1.284 +     * implemented within method xfer, the second in tryAppend, and
   1.285 +     * the third in method awaitMatch.
   1.286 +     *
   1.287 +     * 1. Try to match an existing node
   1.288 +     *
   1.289 +     *    Starting at head, skip already-matched nodes until finding
   1.290 +     *    an unmatched node of opposite mode, if one exists, in which
   1.291 +     *    case matching it and returning, also if necessary updating
   1.292 +     *    head to one past the matched node (or the node itself if the
   1.293 +     *    list has no other unmatched nodes). If the CAS misses, then
   1.294 +     *    a loop retries advancing head by two steps until either
   1.295 +     *    success or the slack is at most two. By requiring that each
   1.296 +     *    attempt advances head by two (if applicable), we ensure that
   1.297 +     *    the slack does not grow without bound. Traversals also check
   1.298 +     *    if the initial head is now off-list, in which case they
   1.299 +     *    start at the new head.
   1.300 +     *
   1.301 +     *    If no candidates are found and the call was untimed
   1.302 +     *    poll/offer, (argument "how" is NOW) return.
   1.303 +     *
   1.304 +     * 2. Try to append a new node (method tryAppend)
   1.305 +     *
   1.306 +     *    Starting at current tail pointer, find the actual last node
   1.307 +     *    and try to append a new node (or if head was null, establish
   1.308 +     *    the first node). Nodes can be appended only if their
   1.309 +     *    predecessors are either already matched or are of the same
   1.310 +     *    mode. If we detect otherwise, then a new node with opposite
   1.311 +     *    mode must have been appended during traversal, so we must
   1.312 +     *    restart at phase 1. The traversal and update steps are
   1.313 +     *    otherwise similar to phase 1: Retrying upon CAS misses and
   1.314 +     *    checking for staleness.  In particular, if a self-link is
   1.315 +     *    encountered, then we can safely jump to a node on the list
   1.316 +     *    by continuing the traversal at current head.
   1.317 +     *
   1.318 +     *    On successful append, if the call was ASYNC, return.
   1.319 +     *
   1.320 +     * 3. Await match or cancellation (method awaitMatch)
   1.321 +     *
   1.322 +     *    Wait for another thread to match node; instead cancelling if
   1.323 +     *    the current thread was interrupted or the wait timed out. On
   1.324 +     *    multiprocessors, we use front-of-queue spinning: If a node
   1.325 +     *    appears to be the first unmatched node in the queue, it
   1.326 +     *    spins a bit before blocking. In either case, before blocking
   1.327 +     *    it tries to unsplice any nodes between the current "head"
   1.328 +     *    and the first unmatched node.
   1.329 +     *
   1.330 +     *    Front-of-queue spinning vastly improves performance of
   1.331 +     *    heavily contended queues. And so long as it is relatively
   1.332 +     *    brief and "quiet", spinning does not much impact performance
   1.333 +     *    of less-contended queues.  During spins threads check their
   1.334 +     *    interrupt status and generate a thread-local random number
   1.335 +     *    to decide to occasionally perform a Thread.yield. While
   1.336 +     *    yield has underdefined specs, we assume that might it help,
   1.337 +     *    and will not hurt in limiting impact of spinning on busy
   1.338 +     *    systems.  We also use smaller (1/2) spins for nodes that are
   1.339 +     *    not known to be front but whose predecessors have not
   1.340 +     *    blocked -- these "chained" spins avoid artifacts of
   1.341 +     *    front-of-queue rules which otherwise lead to alternating
   1.342 +     *    nodes spinning vs blocking. Further, front threads that
   1.343 +     *    represent phase changes (from data to request node or vice
   1.344 +     *    versa) compared to their predecessors receive additional
   1.345 +     *    chained spins, reflecting longer paths typically required to
   1.346 +     *    unblock threads during phase changes.
   1.347 +     *
   1.348 +     *
   1.349 +     * ** Unlinking removed interior nodes **
   1.350 +     *
   1.351 +     * In addition to minimizing garbage retention via self-linking
   1.352 +     * described above, we also unlink removed interior nodes. These
   1.353 +     * may arise due to timed out or interrupted waits, or calls to
   1.354 +     * remove(x) or Iterator.remove.  Normally, given a node that was
   1.355 +     * at one time known to be the predecessor of some node s that is
   1.356 +     * to be removed, we can unsplice s by CASing the next field of
   1.357 +     * its predecessor if it still points to s (otherwise s must
   1.358 +     * already have been removed or is now offlist). But there are two
   1.359 +     * situations in which we cannot guarantee to make node s
   1.360 +     * unreachable in this way: (1) If s is the trailing node of list
   1.361 +     * (i.e., with null next), then it is pinned as the target node
   1.362 +     * for appends, so can only be removed later after other nodes are
   1.363 +     * appended. (2) We cannot necessarily unlink s given a
   1.364 +     * predecessor node that is matched (including the case of being
   1.365 +     * cancelled): the predecessor may already be unspliced, in which
   1.366 +     * case some previous reachable node may still point to s.
   1.367 +     * (For further explanation see Herlihy & Shavit "The Art of
   1.368 +     * Multiprocessor Programming" chapter 9).  Although, in both
   1.369 +     * cases, we can rule out the need for further action if either s
   1.370 +     * or its predecessor are (or can be made to be) at, or fall off
   1.371 +     * from, the head of list.
   1.372 +     *
   1.373 +     * Without taking these into account, it would be possible for an
   1.374 +     * unbounded number of supposedly removed nodes to remain
   1.375 +     * reachable.  Situations leading to such buildup are uncommon but
   1.376 +     * can occur in practice; for example when a series of short timed
   1.377 +     * calls to poll repeatedly time out but never otherwise fall off
   1.378 +     * the list because of an untimed call to take at the front of the
   1.379 +     * queue.
   1.380 +     *
   1.381 +     * When these cases arise, rather than always retraversing the
   1.382 +     * entire list to find an actual predecessor to unlink (which
   1.383 +     * won't help for case (1) anyway), we record a conservative
   1.384 +     * estimate of possible unsplice failures (in "sweepVotes").
   1.385 +     * We trigger a full sweep when the estimate exceeds a threshold
   1.386 +     * ("SWEEP_THRESHOLD") indicating the maximum number of estimated
   1.387 +     * removal failures to tolerate before sweeping through, unlinking
   1.388 +     * cancelled nodes that were not unlinked upon initial removal.
   1.389 +     * We perform sweeps by the thread hitting threshold (rather than
   1.390 +     * background threads or by spreading work to other threads)
   1.391 +     * because in the main contexts in which removal occurs, the
   1.392 +     * caller is already timed-out, cancelled, or performing a
   1.393 +     * potentially O(n) operation (e.g. remove(x)), none of which are
   1.394 +     * time-critical enough to warrant the overhead that alternatives
   1.395 +     * would impose on other threads.
   1.396 +     *
   1.397 +     * Because the sweepVotes estimate is conservative, and because
   1.398 +     * nodes become unlinked "naturally" as they fall off the head of
   1.399 +     * the queue, and because we allow votes to accumulate even while
   1.400 +     * sweeps are in progress, there are typically significantly fewer
   1.401 +     * such nodes than estimated.  Choice of a threshold value
   1.402 +     * balances the likelihood of wasted effort and contention, versus
   1.403 +     * providing a worst-case bound on retention of interior nodes in
   1.404 +     * quiescent queues. The value defined below was chosen
   1.405 +     * empirically to balance these under various timeout scenarios.
   1.406 +     *
   1.407 +     * Note that we cannot self-link unlinked interior nodes during
   1.408 +     * sweeps. However, the associated garbage chains terminate when
   1.409 +     * some successor ultimately falls off the head of the list and is
   1.410 +     * self-linked.
   1.411 +     */
   1.412 +
   1.413 +    /** True if on multiprocessor */
   1.414 +    private static final boolean MP =
   1.415 +        Runtime.getRuntime().availableProcessors() > 1;
   1.416 +
   1.417 +    /**
   1.418 +     * The number of times to spin (with randomly interspersed calls
   1.419 +     * to Thread.yield) on multiprocessor before blocking when a node
   1.420 +     * is apparently the first waiter in the queue.  See above for
   1.421 +     * explanation. Must be a power of two. The value is empirically
   1.422 +     * derived -- it works pretty well across a variety of processors,
   1.423 +     * numbers of CPUs, and OSes.
   1.424 +     */
   1.425 +    private static final int FRONT_SPINS   = 1 << 7;
   1.426 +
   1.427 +    /**
   1.428 +     * The number of times to spin before blocking when a node is
   1.429 +     * preceded by another node that is apparently spinning.  Also
   1.430 +     * serves as an increment to FRONT_SPINS on phase changes, and as
   1.431 +     * base average frequency for yielding during spins. Must be a
   1.432 +     * power of two.
   1.433 +     */
   1.434 +    private static final int CHAINED_SPINS = FRONT_SPINS >>> 1;
   1.435 +
   1.436 +    /**
   1.437 +     * The maximum number of estimated removal failures (sweepVotes)
   1.438 +     * to tolerate before sweeping through the queue unlinking
   1.439 +     * cancelled nodes that were not unlinked upon initial
   1.440 +     * removal. See above for explanation. The value must be at least
   1.441 +     * two to avoid useless sweeps when removing trailing nodes.
   1.442 +     */
   1.443 +    static final int SWEEP_THRESHOLD = 32;
   1.444 +
   1.445 +    /**
   1.446 +     * Queue nodes. Uses Object, not E, for items to allow forgetting
   1.447 +     * them after use.  Relies heavily on Unsafe mechanics to minimize
   1.448 +     * unnecessary ordering constraints: Writes that are intrinsically
   1.449 +     * ordered wrt other accesses or CASes use simple relaxed forms.
   1.450 +     */
   1.451 +    static final class Node {
   1.452 +        final boolean isData;   // false if this is a request node
   1.453 +        volatile Object item;   // initially non-null if isData; CASed to match
   1.454 +        volatile Node next;
   1.455 +        volatile Thread waiter; // null until waiting
   1.456 +
   1.457 +        // CAS methods for fields
   1.458 +        final boolean casNext(Node cmp, Node val) {
   1.459 +            return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
   1.460 +        }
   1.461 +
   1.462 +        final boolean casItem(Object cmp, Object val) {
   1.463 +            // assert cmp == null || cmp.getClass() != Node.class;
   1.464 +            return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
   1.465 +        }
   1.466 +
   1.467 +        /**
   1.468 +         * Constructs a new node.  Uses relaxed write because item can
   1.469 +         * only be seen after publication via casNext.
   1.470 +         */
   1.471 +        Node(Object item, boolean isData) {
   1.472 +            UNSAFE.putObject(this, itemOffset, item); // relaxed write
   1.473 +            this.isData = isData;
   1.474 +        }
   1.475 +
   1.476 +        /**
   1.477 +         * Links node to itself to avoid garbage retention.  Called
   1.478 +         * only after CASing head field, so uses relaxed write.
   1.479 +         */
   1.480 +        final void forgetNext() {
   1.481 +            UNSAFE.putObject(this, nextOffset, this);
   1.482 +        }
   1.483 +
   1.484 +        /**
   1.485 +         * Sets item to self and waiter to null, to avoid garbage
   1.486 +         * retention after matching or cancelling. Uses relaxed writes
   1.487 +         * because order is already constrained in the only calling
   1.488 +         * contexts: item is forgotten only after volatile/atomic
   1.489 +         * mechanics that extract items.  Similarly, clearing waiter
   1.490 +         * follows either CAS or return from park (if ever parked;
   1.491 +         * else we don't care).
   1.492 +         */
   1.493 +        final void forgetContents() {
   1.494 +            UNSAFE.putObject(this, itemOffset, this);
   1.495 +            UNSAFE.putObject(this, waiterOffset, null);
   1.496 +        }
   1.497 +
   1.498 +        /**
   1.499 +         * Returns true if this node has been matched, including the
   1.500 +         * case of artificial matches due to cancellation.
   1.501 +         */
   1.502 +        final boolean isMatched() {
   1.503 +            Object x = item;
   1.504 +            return (x == this) || ((x == null) == isData);
   1.505 +        }
   1.506 +
   1.507 +        /**
   1.508 +         * Returns true if this is an unmatched request node.
   1.509 +         */
   1.510 +        final boolean isUnmatchedRequest() {
   1.511 +            return !isData && item == null;
   1.512 +        }
   1.513 +
   1.514 +        /**
   1.515 +         * Returns true if a node with the given mode cannot be
   1.516 +         * appended to this node because this node is unmatched and
   1.517 +         * has opposite data mode.
   1.518 +         */
   1.519 +        final boolean cannotPrecede(boolean haveData) {
   1.520 +            boolean d = isData;
   1.521 +            Object x;
   1.522 +            return d != haveData && (x = item) != this && (x != null) == d;
   1.523 +        }
   1.524 +
   1.525 +        /**
   1.526 +         * Tries to artificially match a data node -- used by remove.
   1.527 +         */
   1.528 +        final boolean tryMatchData() {
   1.529 +            // assert isData;
   1.530 +            Object x = item;
   1.531 +            if (x != null && x != this && casItem(x, null)) {
   1.532 +                LockSupport.unpark(waiter);
   1.533 +                return true;
   1.534 +            }
   1.535 +            return false;
   1.536 +        }
   1.537 +
   1.538 +        private static final long serialVersionUID = -3375979862319811754L;
   1.539 +
   1.540 +        // Unsafe mechanics
   1.541 +        private static final sun.misc.Unsafe UNSAFE;
   1.542 +        private static final long itemOffset;
   1.543 +        private static final long nextOffset;
   1.544 +        private static final long waiterOffset;
   1.545 +        static {
   1.546 +            try {
   1.547 +                UNSAFE = sun.misc.Unsafe.getUnsafe();
   1.548 +                Class k = Node.class;
   1.549 +                itemOffset = UNSAFE.objectFieldOffset
   1.550 +                    (k.getDeclaredField("item"));
   1.551 +                nextOffset = UNSAFE.objectFieldOffset
   1.552 +                    (k.getDeclaredField("next"));
   1.553 +                waiterOffset = UNSAFE.objectFieldOffset
   1.554 +                    (k.getDeclaredField("waiter"));
   1.555 +            } catch (Exception e) {
   1.556 +                throw new Error(e);
   1.557 +            }
   1.558 +        }
   1.559 +    }
   1.560 +
   1.561 +    /** head of the queue; null until first enqueue */
   1.562 +    transient volatile Node head;
   1.563 +
   1.564 +    /** tail of the queue; null until first append */
   1.565 +    private transient volatile Node tail;
   1.566 +
   1.567 +    /** The number of apparent failures to unsplice removed nodes */
   1.568 +    private transient volatile int sweepVotes;
   1.569 +
   1.570 +    // CAS methods for fields
   1.571 +    private boolean casTail(Node cmp, Node val) {
   1.572 +        return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
   1.573 +    }
   1.574 +
   1.575 +    private boolean casHead(Node cmp, Node val) {
   1.576 +        return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
   1.577 +    }
   1.578 +
   1.579 +    private boolean casSweepVotes(int cmp, int val) {
   1.580 +        return UNSAFE.compareAndSwapInt(this, sweepVotesOffset, cmp, val);
   1.581 +    }
   1.582 +
   1.583 +    /*
   1.584 +     * Possible values for "how" argument in xfer method.
   1.585 +     */
   1.586 +    private static final int NOW   = 0; // for untimed poll, tryTransfer
   1.587 +    private static final int ASYNC = 1; // for offer, put, add
   1.588 +    private static final int SYNC  = 2; // for transfer, take
   1.589 +    private static final int TIMED = 3; // for timed poll, tryTransfer
   1.590 +
   1.591 +    @SuppressWarnings("unchecked")
   1.592 +    static <E> E cast(Object item) {
   1.593 +        // assert item == null || item.getClass() != Node.class;
   1.594 +        return (E) item;
   1.595 +    }
   1.596 +
   1.597 +    /**
   1.598 +     * Implements all queuing methods. See above for explanation.
   1.599 +     *
   1.600 +     * @param e the item or null for take
   1.601 +     * @param haveData true if this is a put, else a take
   1.602 +     * @param how NOW, ASYNC, SYNC, or TIMED
   1.603 +     * @param nanos timeout in nanosecs, used only if mode is TIMED
   1.604 +     * @return an item if matched, else e
   1.605 +     * @throws NullPointerException if haveData mode but e is null
   1.606 +     */
   1.607 +    private E xfer(E e, boolean haveData, int how, long nanos) {
   1.608 +        if (haveData && (e == null))
   1.609 +            throw new NullPointerException();
   1.610 +        Node s = null;                        // the node to append, if needed
   1.611 +
   1.612 +        retry:
   1.613 +        for (;;) {                            // restart on append race
   1.614 +
   1.615 +            for (Node h = head, p = h; p != null;) { // find & match first node
   1.616 +                boolean isData = p.isData;
   1.617 +                Object item = p.item;
   1.618 +                if (item != p && (item != null) == isData) { // unmatched
   1.619 +                    if (isData == haveData)   // can't match
   1.620 +                        break;
   1.621 +                    if (p.casItem(item, e)) { // match
   1.622 +                        for (Node q = p; q != h;) {
   1.623 +                            Node n = q.next;  // update by 2 unless singleton
   1.624 +                            if (head == h && casHead(h, n == null ? q : n)) {
   1.625 +                                h.forgetNext();
   1.626 +                                break;
   1.627 +                            }                 // advance and retry
   1.628 +                            if ((h = head)   == null ||
   1.629 +                                (q = h.next) == null || !q.isMatched())
   1.630 +                                break;        // unless slack < 2
   1.631 +                        }
   1.632 +                        LockSupport.unpark(p.waiter);
   1.633 +                        return this.<E>cast(item);
   1.634 +                    }
   1.635 +                }
   1.636 +                Node n = p.next;
   1.637 +                p = (p != n) ? n : (h = head); // Use head if p offlist
   1.638 +            }
   1.639 +
   1.640 +            if (how != NOW) {                 // No matches available
   1.641 +                if (s == null)
   1.642 +                    s = new Node(e, haveData);
   1.643 +                Node pred = tryAppend(s, haveData);
   1.644 +                if (pred == null)
   1.645 +                    continue retry;           // lost race vs opposite mode
   1.646 +                if (how != ASYNC)
   1.647 +                    return awaitMatch(s, pred, e, (how == TIMED), nanos);
   1.648 +            }
   1.649 +            return e; // not waiting
   1.650 +        }
   1.651 +    }
   1.652 +
   1.653 +    /**
   1.654 +     * Tries to append node s as tail.
   1.655 +     *
   1.656 +     * @param s the node to append
   1.657 +     * @param haveData true if appending in data mode
   1.658 +     * @return null on failure due to losing race with append in
   1.659 +     * different mode, else s's predecessor, or s itself if no
   1.660 +     * predecessor
   1.661 +     */
   1.662 +    private Node tryAppend(Node s, boolean haveData) {
   1.663 +        for (Node t = tail, p = t;;) {        // move p to last node and append
   1.664 +            Node n, u;                        // temps for reads of next & tail
   1.665 +            if (p == null && (p = head) == null) {
   1.666 +                if (casHead(null, s))
   1.667 +                    return s;                 // initialize
   1.668 +            }
   1.669 +            else if (p.cannotPrecede(haveData))
   1.670 +                return null;                  // lost race vs opposite mode
   1.671 +            else if ((n = p.next) != null)    // not last; keep traversing
   1.672 +                p = p != t && t != (u = tail) ? (t = u) : // stale tail
   1.673 +                    (p != n) ? n : null;      // restart if off list
   1.674 +            else if (!p.casNext(null, s))
   1.675 +                p = p.next;                   // re-read on CAS failure
   1.676 +            else {
   1.677 +                if (p != t) {                 // update if slack now >= 2
   1.678 +                    while ((tail != t || !casTail(t, s)) &&
   1.679 +                           (t = tail)   != null &&
   1.680 +                           (s = t.next) != null && // advance and retry
   1.681 +                           (s = s.next) != null && s != t);
   1.682 +                }
   1.683 +                return p;
   1.684 +            }
   1.685 +        }
   1.686 +    }
   1.687 +
   1.688 +    /**
   1.689 +     * Spins/yields/blocks until node s is matched or caller gives up.
   1.690 +     *
   1.691 +     * @param s the waiting node
   1.692 +     * @param pred the predecessor of s, or s itself if it has no
   1.693 +     * predecessor, or null if unknown (the null case does not occur
   1.694 +     * in any current calls but may in possible future extensions)
   1.695 +     * @param e the comparison value for checking match
   1.696 +     * @param timed if true, wait only until timeout elapses
   1.697 +     * @param nanos timeout in nanosecs, used only if timed is true
   1.698 +     * @return matched item, or e if unmatched on interrupt or timeout
   1.699 +     */
   1.700 +    private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
   1.701 +        long lastTime = timed ? System.nanoTime() : 0L;
   1.702 +        Thread w = Thread.currentThread();
   1.703 +        int spins = -1; // initialized after first item and cancel checks
   1.704 +        ThreadLocalRandom randomYields = null; // bound if needed
   1.705 +
   1.706 +        for (;;) {
   1.707 +            Object item = s.item;
   1.708 +            if (item != e) {                  // matched
   1.709 +                // assert item != s;
   1.710 +                s.forgetContents();           // avoid garbage
   1.711 +                return this.<E>cast(item);
   1.712 +            }
   1.713 +            if ((w.isInterrupted() || (timed && nanos <= 0)) &&
   1.714 +                    s.casItem(e, s)) {        // cancel
   1.715 +                unsplice(pred, s);
   1.716 +                return e;
   1.717 +            }
   1.718 +
   1.719 +            if (spins < 0) {                  // establish spins at/near front
   1.720 +                if ((spins = spinsFor(pred, s.isData)) > 0)
   1.721 +                    randomYields = ThreadLocalRandom.current();
   1.722 +            }
   1.723 +            else if (spins > 0) {             // spin
   1.724 +                --spins;
   1.725 +                if (randomYields.nextInt(CHAINED_SPINS) == 0)
   1.726 +                    Thread.yield();           // occasionally yield
   1.727 +            }
   1.728 +            else if (s.waiter == null) {
   1.729 +                s.waiter = w;                 // request unpark then recheck
   1.730 +            }
   1.731 +            else if (timed) {
   1.732 +                long now = System.nanoTime();
   1.733 +                if ((nanos -= now - lastTime) > 0)
   1.734 +                    LockSupport.parkNanos(this, nanos);
   1.735 +                lastTime = now;
   1.736 +            }
   1.737 +            else {
   1.738 +                LockSupport.park(this);
   1.739 +            }
   1.740 +        }
   1.741 +    }
   1.742 +
   1.743 +    /**
   1.744 +     * Returns spin/yield value for a node with given predecessor and
   1.745 +     * data mode. See above for explanation.
   1.746 +     */
   1.747 +    private static int spinsFor(Node pred, boolean haveData) {
   1.748 +        if (MP && pred != null) {
   1.749 +            if (pred.isData != haveData)      // phase change
   1.750 +                return FRONT_SPINS + CHAINED_SPINS;
   1.751 +            if (pred.isMatched())             // probably at front
   1.752 +                return FRONT_SPINS;
   1.753 +            if (pred.waiter == null)          // pred apparently spinning
   1.754 +                return CHAINED_SPINS;
   1.755 +        }
   1.756 +        return 0;
   1.757 +    }
   1.758 +
   1.759 +    /* -------------- Traversal methods -------------- */
   1.760 +
   1.761 +    /**
   1.762 +     * Returns the successor of p, or the head node if p.next has been
   1.763 +     * linked to self, which will only be true if traversing with a
   1.764 +     * stale pointer that is now off the list.
   1.765 +     */
   1.766 +    final Node succ(Node p) {
   1.767 +        Node next = p.next;
   1.768 +        return (p == next) ? head : next;
   1.769 +    }
   1.770 +
   1.771 +    /**
   1.772 +     * Returns the first unmatched node of the given mode, or null if
   1.773 +     * none.  Used by methods isEmpty, hasWaitingConsumer.
   1.774 +     */
   1.775 +    private Node firstOfMode(boolean isData) {
   1.776 +        for (Node p = head; p != null; p = succ(p)) {
   1.777 +            if (!p.isMatched())
   1.778 +                return (p.isData == isData) ? p : null;
   1.779 +        }
   1.780 +        return null;
   1.781 +    }
   1.782 +
   1.783 +    /**
   1.784 +     * Returns the item in the first unmatched node with isData; or
   1.785 +     * null if none.  Used by peek.
   1.786 +     */
   1.787 +    private E firstDataItem() {
   1.788 +        for (Node p = head; p != null; p = succ(p)) {
   1.789 +            Object item = p.item;
   1.790 +            if (p.isData) {
   1.791 +                if (item != null && item != p)
   1.792 +                    return this.<E>cast(item);
   1.793 +            }
   1.794 +            else if (item == null)
   1.795 +                return null;
   1.796 +        }
   1.797 +        return null;
   1.798 +    }
   1.799 +
   1.800 +    /**
   1.801 +     * Traverses and counts unmatched nodes of the given mode.
   1.802 +     * Used by methods size and getWaitingConsumerCount.
   1.803 +     */
   1.804 +    private int countOfMode(boolean data) {
   1.805 +        int count = 0;
   1.806 +        for (Node p = head; p != null; ) {
   1.807 +            if (!p.isMatched()) {
   1.808 +                if (p.isData != data)
   1.809 +                    return 0;
   1.810 +                if (++count == Integer.MAX_VALUE) // saturated
   1.811 +                    break;
   1.812 +            }
   1.813 +            Node n = p.next;
   1.814 +            if (n != p)
   1.815 +                p = n;
   1.816 +            else {
   1.817 +                count = 0;
   1.818 +                p = head;
   1.819 +            }
   1.820 +        }
   1.821 +        return count;
   1.822 +    }
   1.823 +
   1.824 +    final class Itr implements Iterator<E> {
   1.825 +        private Node nextNode;   // next node to return item for
   1.826 +        private E nextItem;      // the corresponding item
   1.827 +        private Node lastRet;    // last returned node, to support remove
   1.828 +        private Node lastPred;   // predecessor to unlink lastRet
   1.829 +
   1.830 +        /**
   1.831 +         * Moves to next node after prev, or first node if prev null.
   1.832 +         */
   1.833 +        private void advance(Node prev) {
   1.834 +            /*
   1.835 +             * To track and avoid buildup of deleted nodes in the face
   1.836 +             * of calls to both Queue.remove and Itr.remove, we must
   1.837 +             * include variants of unsplice and sweep upon each
   1.838 +             * advance: Upon Itr.remove, we may need to catch up links
   1.839 +             * from lastPred, and upon other removes, we might need to
   1.840 +             * skip ahead from stale nodes and unsplice deleted ones
   1.841 +             * found while advancing.
   1.842 +             */
   1.843 +
   1.844 +            Node r, b; // reset lastPred upon possible deletion of lastRet
   1.845 +            if ((r = lastRet) != null && !r.isMatched())
   1.846 +                lastPred = r;    // next lastPred is old lastRet
   1.847 +            else if ((b = lastPred) == null || b.isMatched())
   1.848 +                lastPred = null; // at start of list
   1.849 +            else {
   1.850 +                Node s, n;       // help with removal of lastPred.next
   1.851 +                while ((s = b.next) != null &&
   1.852 +                       s != b && s.isMatched() &&
   1.853 +                       (n = s.next) != null && n != s)
   1.854 +                    b.casNext(s, n);
   1.855 +            }
   1.856 +
   1.857 +            this.lastRet = prev;
   1.858 +
   1.859 +            for (Node p = prev, s, n;;) {
   1.860 +                s = (p == null) ? head : p.next;
   1.861 +                if (s == null)
   1.862 +                    break;
   1.863 +                else if (s == p) {
   1.864 +                    p = null;
   1.865 +                    continue;
   1.866 +                }
   1.867 +                Object item = s.item;
   1.868 +                if (s.isData) {
   1.869 +                    if (item != null && item != s) {
   1.870 +                        nextItem = LinkedTransferQueue.<E>cast(item);
   1.871 +                        nextNode = s;
   1.872 +                        return;
   1.873 +                    }
   1.874 +                }
   1.875 +                else if (item == null)
   1.876 +                    break;
   1.877 +                // assert s.isMatched();
   1.878 +                if (p == null)
   1.879 +                    p = s;
   1.880 +                else if ((n = s.next) == null)
   1.881 +                    break;
   1.882 +                else if (s == n)
   1.883 +                    p = null;
   1.884 +                else
   1.885 +                    p.casNext(s, n);
   1.886 +            }
   1.887 +            nextNode = null;
   1.888 +            nextItem = null;
   1.889 +        }
   1.890 +
   1.891 +        Itr() {
   1.892 +            advance(null);
   1.893 +        }
   1.894 +
   1.895 +        public final boolean hasNext() {
   1.896 +            return nextNode != null;
   1.897 +        }
   1.898 +
   1.899 +        public final E next() {
   1.900 +            Node p = nextNode;
   1.901 +            if (p == null) throw new NoSuchElementException();
   1.902 +            E e = nextItem;
   1.903 +            advance(p);
   1.904 +            return e;
   1.905 +        }
   1.906 +
   1.907 +        public final void remove() {
   1.908 +            final Node lastRet = this.lastRet;
   1.909 +            if (lastRet == null)
   1.910 +                throw new IllegalStateException();
   1.911 +            this.lastRet = null;
   1.912 +            if (lastRet.tryMatchData())
   1.913 +                unsplice(lastPred, lastRet);
   1.914 +        }
   1.915 +    }
   1.916 +
   1.917 +    /* -------------- Removal methods -------------- */
   1.918 +
   1.919 +    /**
   1.920 +     * Unsplices (now or later) the given deleted/cancelled node with
   1.921 +     * the given predecessor.
   1.922 +     *
   1.923 +     * @param pred a node that was at one time known to be the
   1.924 +     * predecessor of s, or null or s itself if s is/was at head
   1.925 +     * @param s the node to be unspliced
   1.926 +     */
   1.927 +    final void unsplice(Node pred, Node s) {
   1.928 +        s.forgetContents(); // forget unneeded fields
   1.929 +        /*
   1.930 +         * See above for rationale. Briefly: if pred still points to
   1.931 +         * s, try to unlink s.  If s cannot be unlinked, because it is
   1.932 +         * trailing node or pred might be unlinked, and neither pred
   1.933 +         * nor s are head or offlist, add to sweepVotes, and if enough
   1.934 +         * votes have accumulated, sweep.
   1.935 +         */
   1.936 +        if (pred != null && pred != s && pred.next == s) {
   1.937 +            Node n = s.next;
   1.938 +            if (n == null ||
   1.939 +                (n != s && pred.casNext(s, n) && pred.isMatched())) {
   1.940 +                for (;;) {               // check if at, or could be, head
   1.941 +                    Node h = head;
   1.942 +                    if (h == pred || h == s || h == null)
   1.943 +                        return;          // at head or list empty
   1.944 +                    if (!h.isMatched())
   1.945 +                        break;
   1.946 +                    Node hn = h.next;
   1.947 +                    if (hn == null)
   1.948 +                        return;          // now empty
   1.949 +                    if (hn != h && casHead(h, hn))
   1.950 +                        h.forgetNext();  // advance head
   1.951 +                }
   1.952 +                if (pred.next != pred && s.next != s) { // recheck if offlist
   1.953 +                    for (;;) {           // sweep now if enough votes
   1.954 +                        int v = sweepVotes;
   1.955 +                        if (v < SWEEP_THRESHOLD) {
   1.956 +                            if (casSweepVotes(v, v + 1))
   1.957 +                                break;
   1.958 +                        }
   1.959 +                        else if (casSweepVotes(v, 0)) {
   1.960 +                            sweep();
   1.961 +                            break;
   1.962 +                        }
   1.963 +                    }
   1.964 +                }
   1.965 +            }
   1.966 +        }
   1.967 +    }
   1.968 +
   1.969 +    /**
   1.970 +     * Unlinks matched (typically cancelled) nodes encountered in a
   1.971 +     * traversal from head.
   1.972 +     */
   1.973 +    private void sweep() {
   1.974 +        for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
   1.975 +            if (!s.isMatched())
   1.976 +                // Unmatched nodes are never self-linked
   1.977 +                p = s;
   1.978 +            else if ((n = s.next) == null) // trailing node is pinned
   1.979 +                break;
   1.980 +            else if (s == n)    // stale
   1.981 +                // No need to also check for p == s, since that implies s == n
   1.982 +                p = head;
   1.983 +            else
   1.984 +                p.casNext(s, n);
   1.985 +        }
   1.986 +    }
   1.987 +
   1.988 +    /**
   1.989 +     * Main implementation of remove(Object)
   1.990 +     */
   1.991 +    private boolean findAndRemove(Object e) {
   1.992 +        if (e != null) {
   1.993 +            for (Node pred = null, p = head; p != null; ) {
   1.994 +                Object item = p.item;
   1.995 +                if (p.isData) {
   1.996 +                    if (item != null && item != p && e.equals(item) &&
   1.997 +                        p.tryMatchData()) {
   1.998 +                        unsplice(pred, p);
   1.999 +                        return true;
  1.1000 +                    }
  1.1001 +                }
  1.1002 +                else if (item == null)
  1.1003 +                    break;
  1.1004 +                pred = p;
  1.1005 +                if ((p = p.next) == pred) { // stale
  1.1006 +                    pred = null;
  1.1007 +                    p = head;
  1.1008 +                }
  1.1009 +            }
  1.1010 +        }
  1.1011 +        return false;
  1.1012 +    }
  1.1013 +
  1.1014 +
  1.1015 +    /**
  1.1016 +     * Creates an initially empty {@code LinkedTransferQueue}.
  1.1017 +     */
  1.1018 +    public LinkedTransferQueue() {
  1.1019 +    }
  1.1020 +
  1.1021 +    /**
  1.1022 +     * Creates a {@code LinkedTransferQueue}
  1.1023 +     * initially containing the elements of the given collection,
  1.1024 +     * added in traversal order of the collection's iterator.
  1.1025 +     *
  1.1026 +     * @param c the collection of elements to initially contain
  1.1027 +     * @throws NullPointerException if the specified collection or any
  1.1028 +     *         of its elements are null
  1.1029 +     */
  1.1030 +    public LinkedTransferQueue(Collection<? extends E> c) {
  1.1031 +        this();
  1.1032 +        addAll(c);
  1.1033 +    }
  1.1034 +
  1.1035 +    /**
  1.1036 +     * Inserts the specified element at the tail of this queue.
  1.1037 +     * As the queue is unbounded, this method will never block.
  1.1038 +     *
  1.1039 +     * @throws NullPointerException if the specified element is null
  1.1040 +     */
  1.1041 +    public void put(E e) {
  1.1042 +        xfer(e, true, ASYNC, 0);
  1.1043 +    }
  1.1044 +
  1.1045 +    /**
  1.1046 +     * Inserts the specified element at the tail of this queue.
  1.1047 +     * As the queue is unbounded, this method will never block or
  1.1048 +     * return {@code false}.
  1.1049 +     *
  1.1050 +     * @return {@code true} (as specified by
  1.1051 +     *  {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
  1.1052 +     * @throws NullPointerException if the specified element is null
  1.1053 +     */
  1.1054 +    public boolean offer(E e, long timeout, TimeUnit unit) {
  1.1055 +        xfer(e, true, ASYNC, 0);
  1.1056 +        return true;
  1.1057 +    }
  1.1058 +
  1.1059 +    /**
  1.1060 +     * Inserts the specified element at the tail of this queue.
  1.1061 +     * As the queue is unbounded, this method will never return {@code false}.
  1.1062 +     *
  1.1063 +     * @return {@code true} (as specified by {@link Queue#offer})
  1.1064 +     * @throws NullPointerException if the specified element is null
  1.1065 +     */
  1.1066 +    public boolean offer(E e) {
  1.1067 +        xfer(e, true, ASYNC, 0);
  1.1068 +        return true;
  1.1069 +    }
  1.1070 +
  1.1071 +    /**
  1.1072 +     * Inserts the specified element at the tail of this queue.
  1.1073 +     * As the queue is unbounded, this method will never throw
  1.1074 +     * {@link IllegalStateException} or return {@code false}.
  1.1075 +     *
  1.1076 +     * @return {@code true} (as specified by {@link Collection#add})
  1.1077 +     * @throws NullPointerException if the specified element is null
  1.1078 +     */
  1.1079 +    public boolean add(E e) {
  1.1080 +        xfer(e, true, ASYNC, 0);
  1.1081 +        return true;
  1.1082 +    }
  1.1083 +
  1.1084 +    /**
  1.1085 +     * Transfers the element to a waiting consumer immediately, if possible.
  1.1086 +     *
  1.1087 +     * <p>More precisely, transfers the specified element immediately
  1.1088 +     * if there exists a consumer already waiting to receive it (in
  1.1089 +     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
  1.1090 +     * otherwise returning {@code false} without enqueuing the element.
  1.1091 +     *
  1.1092 +     * @throws NullPointerException if the specified element is null
  1.1093 +     */
  1.1094 +    public boolean tryTransfer(E e) {
  1.1095 +        return xfer(e, true, NOW, 0) == null;
  1.1096 +    }
  1.1097 +
  1.1098 +    /**
  1.1099 +     * Transfers the element to a consumer, waiting if necessary to do so.
  1.1100 +     *
  1.1101 +     * <p>More precisely, transfers the specified element immediately
  1.1102 +     * if there exists a consumer already waiting to receive it (in
  1.1103 +     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
  1.1104 +     * else inserts the specified element at the tail of this queue
  1.1105 +     * and waits until the element is received by a consumer.
  1.1106 +     *
  1.1107 +     * @throws NullPointerException if the specified element is null
  1.1108 +     */
  1.1109 +    public void transfer(E e) throws InterruptedException {
  1.1110 +        if (xfer(e, true, SYNC, 0) != null) {
  1.1111 +            Thread.interrupted(); // failure possible only due to interrupt
  1.1112 +            throw new InterruptedException();
  1.1113 +        }
  1.1114 +    }
  1.1115 +
  1.1116 +    /**
  1.1117 +     * Transfers the element to a consumer if it is possible to do so
  1.1118 +     * before the timeout elapses.
  1.1119 +     *
  1.1120 +     * <p>More precisely, transfers the specified element immediately
  1.1121 +     * if there exists a consumer already waiting to receive it (in
  1.1122 +     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
  1.1123 +     * else inserts the specified element at the tail of this queue
  1.1124 +     * and waits until the element is received by a consumer,
  1.1125 +     * returning {@code false} if the specified wait time elapses
  1.1126 +     * before the element can be transferred.
  1.1127 +     *
  1.1128 +     * @throws NullPointerException if the specified element is null
  1.1129 +     */
  1.1130 +    public boolean tryTransfer(E e, long timeout, TimeUnit unit)
  1.1131 +        throws InterruptedException {
  1.1132 +        if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
  1.1133 +            return true;
  1.1134 +        if (!Thread.interrupted())
  1.1135 +            return false;
  1.1136 +        throw new InterruptedException();
  1.1137 +    }
  1.1138 +
  1.1139 +    public E take() throws InterruptedException {
  1.1140 +        E e = xfer(null, false, SYNC, 0);
  1.1141 +        if (e != null)
  1.1142 +            return e;
  1.1143 +        Thread.interrupted();
  1.1144 +        throw new InterruptedException();
  1.1145 +    }
  1.1146 +
  1.1147 +    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
  1.1148 +        E e = xfer(null, false, TIMED, unit.toNanos(timeout));
  1.1149 +        if (e != null || !Thread.interrupted())
  1.1150 +            return e;
  1.1151 +        throw new InterruptedException();
  1.1152 +    }
  1.1153 +
  1.1154 +    public E poll() {
  1.1155 +        return xfer(null, false, NOW, 0);
  1.1156 +    }
  1.1157 +
  1.1158 +    /**
  1.1159 +     * @throws NullPointerException     {@inheritDoc}
  1.1160 +     * @throws IllegalArgumentException {@inheritDoc}
  1.1161 +     */
  1.1162 +    public int drainTo(Collection<? super E> c) {
  1.1163 +        if (c == null)
  1.1164 +            throw new NullPointerException();
  1.1165 +        if (c == this)
  1.1166 +            throw new IllegalArgumentException();
  1.1167 +        int n = 0;
  1.1168 +        E e;
  1.1169 +        while ( (e = poll()) != null) {
  1.1170 +            c.add(e);
  1.1171 +            ++n;
  1.1172 +        }
  1.1173 +        return n;
  1.1174 +    }
  1.1175 +
  1.1176 +    /**
  1.1177 +     * @throws NullPointerException     {@inheritDoc}
  1.1178 +     * @throws IllegalArgumentException {@inheritDoc}
  1.1179 +     */
  1.1180 +    public int drainTo(Collection<? super E> c, int maxElements) {
  1.1181 +        if (c == null)
  1.1182 +            throw new NullPointerException();
  1.1183 +        if (c == this)
  1.1184 +            throw new IllegalArgumentException();
  1.1185 +        int n = 0;
  1.1186 +        E e;
  1.1187 +        while (n < maxElements && (e = poll()) != null) {
  1.1188 +            c.add(e);
  1.1189 +            ++n;
  1.1190 +        }
  1.1191 +        return n;
  1.1192 +    }
  1.1193 +
  1.1194 +    /**
  1.1195 +     * Returns an iterator over the elements in this queue in proper sequence.
  1.1196 +     * The elements will be returned in order from first (head) to last (tail).
  1.1197 +     *
  1.1198 +     * <p>The returned iterator is a "weakly consistent" iterator that
  1.1199 +     * will never throw {@link java.util.ConcurrentModificationException
  1.1200 +     * ConcurrentModificationException}, and guarantees to traverse
  1.1201 +     * elements as they existed upon construction of the iterator, and
  1.1202 +     * may (but is not guaranteed to) reflect any modifications
  1.1203 +     * subsequent to construction.
  1.1204 +     *
  1.1205 +     * @return an iterator over the elements in this queue in proper sequence
  1.1206 +     */
  1.1207 +    public Iterator<E> iterator() {
  1.1208 +        return new Itr();
  1.1209 +    }
  1.1210 +
  1.1211 +    public E peek() {
  1.1212 +        return firstDataItem();
  1.1213 +    }
  1.1214 +
  1.1215 +    /**
  1.1216 +     * Returns {@code true} if this queue contains no elements.
  1.1217 +     *
  1.1218 +     * @return {@code true} if this queue contains no elements
  1.1219 +     */
  1.1220 +    public boolean isEmpty() {
  1.1221 +        for (Node p = head; p != null; p = succ(p)) {
  1.1222 +            if (!p.isMatched())
  1.1223 +                return !p.isData;
  1.1224 +        }
  1.1225 +        return true;
  1.1226 +    }
  1.1227 +
  1.1228 +    public boolean hasWaitingConsumer() {
  1.1229 +        return firstOfMode(false) != null;
  1.1230 +    }
  1.1231 +
  1.1232 +    /**
  1.1233 +     * Returns the number of elements in this queue.  If this queue
  1.1234 +     * contains more than {@code Integer.MAX_VALUE} elements, returns
  1.1235 +     * {@code Integer.MAX_VALUE}.
  1.1236 +     *
  1.1237 +     * <p>Beware that, unlike in most collections, this method is
  1.1238 +     * <em>NOT</em> a constant-time operation. Because of the
  1.1239 +     * asynchronous nature of these queues, determining the current
  1.1240 +     * number of elements requires an O(n) traversal.
  1.1241 +     *
  1.1242 +     * @return the number of elements in this queue
  1.1243 +     */
  1.1244 +    public int size() {
  1.1245 +        return countOfMode(true);
  1.1246 +    }
  1.1247 +
  1.1248 +    public int getWaitingConsumerCount() {
  1.1249 +        return countOfMode(false);
  1.1250 +    }
  1.1251 +
  1.1252 +    /**
  1.1253 +     * Removes a single instance of the specified element from this queue,
  1.1254 +     * if it is present.  More formally, removes an element {@code e} such
  1.1255 +     * that {@code o.equals(e)}, if this queue contains one or more such
  1.1256 +     * elements.
  1.1257 +     * Returns {@code true} if this queue contained the specified element
  1.1258 +     * (or equivalently, if this queue changed as a result of the call).
  1.1259 +     *
  1.1260 +     * @param o element to be removed from this queue, if present
  1.1261 +     * @return {@code true} if this queue changed as a result of the call
  1.1262 +     */
  1.1263 +    public boolean remove(Object o) {
  1.1264 +        return findAndRemove(o);
  1.1265 +    }
  1.1266 +
  1.1267 +    /**
  1.1268 +     * Returns {@code true} if this queue contains the specified element.
  1.1269 +     * More formally, returns {@code true} if and only if this queue contains
  1.1270 +     * at least one element {@code e} such that {@code o.equals(e)}.
  1.1271 +     *
  1.1272 +     * @param o object to be checked for containment in this queue
  1.1273 +     * @return {@code true} if this queue contains the specified element
  1.1274 +     */
  1.1275 +    public boolean contains(Object o) {
  1.1276 +        if (o == null) return false;
  1.1277 +        for (Node p = head; p != null; p = succ(p)) {
  1.1278 +            Object item = p.item;
  1.1279 +            if (p.isData) {
  1.1280 +                if (item != null && item != p && o.equals(item))
  1.1281 +                    return true;
  1.1282 +            }
  1.1283 +            else if (item == null)
  1.1284 +                break;
  1.1285 +        }
  1.1286 +        return false;
  1.1287 +    }
  1.1288 +
  1.1289 +    /**
  1.1290 +     * Always returns {@code Integer.MAX_VALUE} because a
  1.1291 +     * {@code LinkedTransferQueue} is not capacity constrained.
  1.1292 +     *
  1.1293 +     * @return {@code Integer.MAX_VALUE} (as specified by
  1.1294 +     *         {@link BlockingQueue#remainingCapacity()})
  1.1295 +     */
  1.1296 +    public int remainingCapacity() {
  1.1297 +        return Integer.MAX_VALUE;
  1.1298 +    }
  1.1299 +
  1.1300 +    /**
  1.1301 +     * Saves the state to a stream (that is, serializes it).
  1.1302 +     *
  1.1303 +     * @serialData All of the elements (each an {@code E}) in
  1.1304 +     * the proper order, followed by a null
  1.1305 +     * @param s the stream
  1.1306 +     */
  1.1307 +    private void writeObject(java.io.ObjectOutputStream s)
  1.1308 +        throws java.io.IOException {
  1.1309 +        s.defaultWriteObject();
  1.1310 +        for (E e : this)
  1.1311 +            s.writeObject(e);
  1.1312 +        // Use trailing null as sentinel
  1.1313 +        s.writeObject(null);
  1.1314 +    }
  1.1315 +
  1.1316 +    /**
  1.1317 +     * Reconstitutes the Queue instance from a stream (that is,
  1.1318 +     * deserializes it).
  1.1319 +     *
  1.1320 +     * @param s the stream
  1.1321 +     */
  1.1322 +    private void readObject(java.io.ObjectInputStream s)
  1.1323 +        throws java.io.IOException, ClassNotFoundException {
  1.1324 +        s.defaultReadObject();
  1.1325 +        for (;;) {
  1.1326 +            @SuppressWarnings("unchecked") E item = (E) s.readObject();
  1.1327 +            if (item == null)
  1.1328 +                break;
  1.1329 +            else
  1.1330 +                offer(item);
  1.1331 +        }
  1.1332 +    }
  1.1333 +
  1.1334 +    // Unsafe mechanics
  1.1335 +
  1.1336 +    private static final sun.misc.Unsafe UNSAFE;
  1.1337 +    private static final long headOffset;
  1.1338 +    private static final long tailOffset;
  1.1339 +    private static final long sweepVotesOffset;
  1.1340 +    static {
  1.1341 +        try {
  1.1342 +            UNSAFE = sun.misc.Unsafe.getUnsafe();
  1.1343 +            Class k = LinkedTransferQueue.class;
  1.1344 +            headOffset = UNSAFE.objectFieldOffset
  1.1345 +                (k.getDeclaredField("head"));
  1.1346 +            tailOffset = UNSAFE.objectFieldOffset
  1.1347 +                (k.getDeclaredField("tail"));
  1.1348 +            sweepVotesOffset = UNSAFE.objectFieldOffset
  1.1349 +                (k.getDeclaredField("sweepVotes"));
  1.1350 +        } catch (Exception e) {
  1.1351 +            throw new Error(e);
  1.1352 +        }
  1.1353 +    }
  1.1354 +}