1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  31  * Written by Doug Lea with assistance from members of JCP JSR-166
  32  * Expert Group and released to the public domain, as explained at
  33  * http://creativecommons.org/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent;
  37 
  38 import java.lang.invoke.MethodHandles;
  39 import java.lang.invoke.VarHandle;
  40 import java.util.AbstractQueue;
  41 import java.util.Arrays;
  42 import java.util.Collection;
  43 import java.util.Iterator;
  44 import java.util.NoSuchElementException;
  45 import java.util.Objects;
  46 import java.util.Queue;
  47 import java.util.Spliterator;
  48 import java.util.Spliterators;
  49 import java.util.concurrent.locks.LockSupport;
  50 import java.util.function.Consumer;
  51 import java.util.function.Predicate;
  52 
  53 /**
  54  * An unbounded {@link TransferQueue} based on linked nodes.
  55  * This queue orders elements FIFO (first-in-first-out) with respect
  56  * to any given producer.  The <em>head</em> of the queue is that
  57  * element that has been on the queue the longest time for some
  58  * producer.  The <em>tail</em> of the queue is that element that has
  59  * been on the queue the shortest time for some producer.
  60  *
  61  * <p>Beware that, unlike in most collections, the {@code size} method
  62  * is <em>NOT</em> a constant-time operation. Because of the
  63  * asynchronous nature of these queues, determining the current number
  64  * of elements requires a traversal of the elements, and so may report
  65  * inaccurate results if this collection is modified during traversal.
  66  *
  67  * <p>Bulk operations that add, remove, or examine multiple elements,
  68  * such as {@link #addAll}, {@link #removeIf} or {@link #forEach},
  69  * are <em>not</em> guaranteed to be performed atomically.
  70  * For example, a {@code forEach} traversal concurrent with an {@code
  71  * addAll} operation might observe only some of the added elements.
  72  *
  73  * <p>This class and its iterator implement all of the <em>optional</em>
  74  * methods of the {@link Collection} and {@link Iterator} interfaces.
  75  *
  76  * <p>Memory consistency effects: As with other concurrent
  77  * collections, actions in a thread prior to placing an object into a
  78  * {@code LinkedTransferQueue}
  79  * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
  80  * actions subsequent to the access or removal of that element from
  81  * the {@code LinkedTransferQueue} in another thread.
  82  *
  83  * <p>This class is a member of the
  84  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
  85  * Java Collections Framework</a>.
  86  *
  87  * @since 1.7
  88  * @author Doug Lea
  89  * @param <E> the type of elements held in this queue
  90  */
  91 public class LinkedTransferQueue<E> extends AbstractQueue<E>
  92     implements TransferQueue<E>, java.io.Serializable {
  93     private static final long serialVersionUID = -3223113410248163686L;
  94 
  95     /*
  96      * *** Overview of Dual Queues with Slack ***
  97      *
  98      * Dual Queues, introduced by Scherer and Scott
  99      * (http://www.cs.rochester.edu/~scott/papers/2004_DISC_dual_DS.pdf)
 100      * are (linked) queues in which nodes may represent either data or
 101      * requests.  When a thread tries to enqueue a data node, but
 102      * encounters a request node, it instead "matches" and removes it;
 103      * and vice versa for enqueuing requests. Blocking Dual Queues
 104      * arrange that threads enqueuing unmatched requests block until
 105      * other threads provide the match. Dual Synchronous Queues (see
 106      * Scherer, Lea, & Scott
 107      * http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf)
 108      * additionally arrange that threads enqueuing unmatched data also
 109      * block.  Dual Transfer Queues support all of these modes, as
 110      * dictated by callers.
 111      *
 112      * A FIFO dual queue may be implemented using a variation of the
 113      * Michael & Scott (M&S) lock-free queue algorithm
 114      * (http://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf).
 115      * It maintains two pointer fields, "head", pointing to a
 116      * (matched) node that in turn points to the first actual
 117      * (unmatched) queue node (or null if empty); and "tail" that
 118      * points to the last node on the queue (or again null if
 119      * empty). For example, here is a possible queue with four data
 120      * elements:
 121      *
 122      *  head                tail
 123      *    |                   |
 124      *    v                   v
 125      *    M -> U -> U -> U -> U
 126      *
 127      * The M&S queue algorithm is known to be prone to scalability and
 128      * overhead limitations when maintaining (via CAS) these head and
 129      * tail pointers. This has led to the development of
 130      * contention-reducing variants such as elimination arrays (see
 131      * Moir et al http://portal.acm.org/citation.cfm?id=1074013) and
 132      * optimistic back pointers (see Ladan-Mozes & Shavit
 133      * http://people.csail.mit.edu/edya/publications/OptimisticFIFOQueue-journal.pdf).
 134      * However, the nature of dual queues enables a simpler tactic for
 135      * improving M&S-style implementations when dual-ness is needed.
 136      *
 137      * In a dual queue, each node must atomically maintain its match
 138      * status. While there are other possible variants, we implement
 139      * this here as: for a data-mode node, matching entails CASing an
 140      * "item" field from a non-null data value to null upon match, and
 141      * vice-versa for request nodes, CASing from null to a data
 142      * value. (Note that the linearization properties of this style of
 143      * queue are easy to verify -- elements are made available by
 144      * linking, and unavailable by matching.) Compared to plain M&S
 145      * queues, this property of dual queues requires one additional
 146      * successful atomic operation per enq/deq pair. But it also
 147      * enables lower cost variants of queue maintenance mechanics. (A
 148      * variation of this idea applies even for non-dual queues that
 149      * support deletion of interior elements, such as
 150      * j.u.c.ConcurrentLinkedQueue.)
 151      *
 152      * Once a node is matched, its match status can never again
 153      * change.  We may thus arrange that the linked list of them
 154      * contain a prefix of zero or more matched nodes, followed by a
 155      * suffix of zero or more unmatched nodes. (Note that we allow
 156      * both the prefix and suffix to be zero length, which in turn
 157      * means that we do not use a dummy header.)  If we were not
 158      * concerned with either time or space efficiency, we could
 159      * correctly perform enqueue and dequeue operations by traversing
 160      * from a pointer to the initial node; CASing the item of the
 161      * first unmatched node on match and CASing the next field of the
 162      * trailing node on appends.  While this would be a terrible idea
 163      * in itself, it does have the benefit of not requiring ANY atomic
 164      * updates on head/tail fields.
 165      *
 166      * We introduce here an approach that lies between the extremes of
 167      * never versus always updating queue (head and tail) pointers.
 168      * This offers a tradeoff between sometimes requiring extra
 169      * traversal steps to locate the first and/or last unmatched
 170      * nodes, versus the reduced overhead and contention of fewer
 171      * updates to queue pointers. For example, a possible snapshot of
 172      * a queue is:
 173      *
 174      *  head           tail
 175      *    |              |
 176      *    v              v
 177      *    M -> M -> U -> U -> U -> U
 178      *
 179      * The best value for this "slack" (the targeted maximum distance
 180      * between the value of "head" and the first unmatched node, and
 181      * similarly for "tail") is an empirical matter. We have found
 182      * that using very small constants in the range of 1-3 work best
 183      * over a range of platforms. Larger values introduce increasing
 184      * costs of cache misses and risks of long traversal chains, while
 185      * smaller values increase CAS contention and overhead.
 186      *
 187      * Dual queues with slack differ from plain M&S dual queues by
 188      * virtue of only sometimes updating head or tail pointers when
 189      * matching, appending, or even traversing nodes; in order to
 190      * maintain a targeted slack.  The idea of "sometimes" may be
 191      * operationalized in several ways. The simplest is to use a
 192      * per-operation counter incremented on each traversal step, and
 193      * to try (via CAS) to update the associated queue pointer
 194      * whenever the count exceeds a threshold. Another, that requires
 195      * more overhead, is to use random number generators to update
 196      * with a given probability per traversal step.
 197      *
 198      * In any strategy along these lines, because CASes updating
 199      * fields may fail, the actual slack may exceed targeted slack.
 200      * However, they may be retried at any time to maintain targets.
 201      * Even when using very small slack values, this approach works
 202      * well for dual queues because it allows all operations up to the
 203      * point of matching or appending an item (hence potentially
 204      * allowing progress by another thread) to be read-only, thus not
 205      * introducing any further contention.  As described below, we
 206      * implement this by performing slack maintenance retries only
 207      * after these points.
 208      *
 209      * As an accompaniment to such techniques, traversal overhead can
 210      * be further reduced without increasing contention of head
 211      * pointer updates: Threads may sometimes shortcut the "next" link
 212      * path from the current "head" node to be closer to the currently
 213      * known first unmatched node, and similarly for tail. Again, this
 214      * may be triggered with using thresholds or randomization.
 215      *
 216      * These ideas must be further extended to avoid unbounded amounts
 217      * of costly-to-reclaim garbage caused by the sequential "next"
 218      * links of nodes starting at old forgotten head nodes: As first
 219      * described in detail by Boehm
 220      * (http://portal.acm.org/citation.cfm?doid=503272.503282), if a GC
 221      * delays noticing that any arbitrarily old node has become
 222      * garbage, all newer dead nodes will also be unreclaimed.
 223      * (Similar issues arise in non-GC environments.)  To cope with
 224      * this in our implementation, upon CASing to advance the head
 225      * pointer, we set the "next" link of the previous head to point
 226      * only to itself; thus limiting the length of chains of dead nodes.
 227      * (We also take similar care to wipe out possibly garbage
 228      * retaining values held in other Node fields.)  However, doing so
 229      * adds some further complexity to traversal: If any "next"
 230      * pointer links to itself, it indicates that the current thread
 231      * has lagged behind a head-update, and so the traversal must
 232      * continue from the "head".  Traversals trying to find the
 233      * current tail starting from "tail" may also encounter
 234      * self-links, in which case they also continue at "head".
 235      *
 236      * It is tempting in slack-based scheme to not even use CAS for
 237      * updates (similarly to Ladan-Mozes & Shavit). However, this
 238      * cannot be done for head updates under the above link-forgetting
 239      * mechanics because an update may leave head at a detached node.
 240      * And while direct writes are possible for tail updates, they
 241      * increase the risk of long retraversals, and hence long garbage
 242      * chains, which can be much more costly than is worthwhile
 243      * considering that the cost difference of performing a CAS vs
 244      * write is smaller when they are not triggered on each operation
 245      * (especially considering that writes and CASes equally require
 246      * additional GC bookkeeping ("write barriers") that are sometimes
 247      * more costly than the writes themselves because of contention).
 248      *
 249      * *** Overview of implementation ***
 250      *
 251      * We use a threshold-based approach to updates, with a slack
 252      * threshold of two -- that is, we update head/tail when the
 253      * current pointer appears to be two or more steps away from the
 254      * first/last node. The slack value is hard-wired: a path greater
 255      * than one is naturally implemented by checking equality of
 256      * traversal pointers except when the list has only one element,
 257      * in which case we keep slack threshold at one. Avoiding tracking
 258      * explicit counts across method calls slightly simplifies an
 259      * already-messy implementation. Using randomization would
 260      * probably work better if there were a low-quality dirt-cheap
 261      * per-thread one available, but even ThreadLocalRandom is too
 262      * heavy for these purposes.
 263      *
 264      * With such a small slack threshold value, it is not worthwhile
 265      * to augment this with path short-circuiting (i.e., unsplicing
 266      * interior nodes) except in the case of cancellation/removal (see
 267      * below).
 268      *
 269      * All enqueue/dequeue operations are handled by the single method
 270      * "xfer" with parameters indicating whether to act as some form
 271      * of offer, put, poll, take, or transfer (each possibly with
 272      * timeout). The relative complexity of using one monolithic
 273      * method outweighs the code bulk and maintenance problems of
 274      * using separate methods for each case.
 275      *
 276      * Operation consists of up to two phases. The first is implemented
 277      * in method xfer, the second in method awaitMatch.
 278      *
 279      * 1. Traverse until matching or appending (method xfer)
 280      *
 281      *    Conceptually, we simply traverse all nodes starting from head.
 282      *    If we encounter an unmatched node of opposite mode, we match
 283      *    it and return, also updating head (by at least 2 hops) to
 284      *    one past the matched node (or the node itself if it's the
 285      *    pinned trailing node).  Traversals also check for the
 286      *    possibility of falling off-list, in which case they restart.
 287      *
 288      *    If the trailing node of the list is reached, a match is not
 289      *    possible.  If this call was untimed poll or tryTransfer
 290      *    (argument "how" is NOW), return empty-handed immediately.
 291      *    Else a new node is CAS-appended.  On successful append, if
 292      *    this call was ASYNC (e.g. offer), an element was
 293      *    successfully added to the end of the queue and we return.
 294      *
 295      *    Of course, this naive traversal is O(n) when no match is
 296      *    possible.  We optimize the traversal by maintaining a tail
 297      *    pointer, which is expected to be "near" the end of the list.
 298      *    It is only safe to fast-forward to tail (in the presence of
 299      *    arbitrary concurrent changes) if it is pointing to a node of
 300      *    the same mode, even if it is dead (in this case no preceding
 301      *    node could still be matchable by this traversal).  If we
 302      *    need to restart due to falling off-list, we can again
 303      *    fast-forward to tail, but only if it has changed since the
 304      *    last traversal (else we might loop forever).  If tail cannot
 305      *    be used, traversal starts at head (but in this case we
 306      *    expect to be able to match near head).  As with head, we
 307      *    CAS-advance the tail pointer by at least two hops.
 308      *
 309      * 2. Await match or cancellation (method awaitMatch)
 310      *
 311      *    Wait for another thread to match node; instead cancelling if
 312      *    the current thread was interrupted or the wait timed out. On
 313      *    multiprocessors, we use front-of-queue spinning: If a node
 314      *    appears to be the first unmatched node in the queue, it
 315      *    spins a bit before blocking. In either case, before blocking
 316      *    it tries to unsplice any nodes between the current "head"
 317      *    and the first unmatched node.
 318      *
 319      *    Front-of-queue spinning vastly improves performance of
 320      *    heavily contended queues. And so long as it is relatively
 321      *    brief and "quiet", spinning does not much impact performance
 322      *    of less-contended queues.  During spins threads check their
 323      *    interrupt status and generate a thread-local random number
 324      *    to decide to occasionally perform a Thread.yield. While
 325      *    yield has underdefined specs, we assume that it might help,
 326      *    and will not hurt, in limiting impact of spinning on busy
 327      *    systems.  We also use smaller (1/2) spins for nodes that are
 328      *    not known to be front but whose predecessors have not
 329      *    blocked -- these "chained" spins avoid artifacts of
 330      *    front-of-queue rules which otherwise lead to alternating
 331      *    nodes spinning vs blocking. Further, front threads that
 332      *    represent phase changes (from data to request node or vice
 333      *    versa) compared to their predecessors receive additional
 334      *    chained spins, reflecting longer paths typically required to
 335      *    unblock threads during phase changes.
 336      *
 337      *
 338      * ** Unlinking removed interior nodes **
 339      *
 340      * In addition to minimizing garbage retention via self-linking
 341      * described above, we also unlink removed interior nodes. These
 342      * may arise due to timed out or interrupted waits, or calls to
 343      * remove(x) or Iterator.remove.  Normally, given a node that was
 344      * at one time known to be the predecessor of some node s that is
 345      * to be removed, we can unsplice s by CASing the next field of
 346      * its predecessor if it still points to s (otherwise s must
 347      * already have been removed or is now offlist). But there are two
 348      * situations in which we cannot guarantee to make node s
 349      * unreachable in this way: (1) If s is the trailing node of list
 350      * (i.e., with null next), then it is pinned as the target node
 351      * for appends, so can only be removed later after other nodes are
 352      * appended. (2) We cannot necessarily unlink s given a
 353      * predecessor node that is matched (including the case of being
 354      * cancelled): the predecessor may already be unspliced, in which
 355      * case some previous reachable node may still point to s.
 356      * (For further explanation see Herlihy & Shavit "The Art of
 357      * Multiprocessor Programming" chapter 9).  Although, in both
 358      * cases, we can rule out the need for further action if either s
 359      * or its predecessor are (or can be made to be) at, or fall off
 360      * from, the head of list.
 361      *
 362      * Without taking these into account, it would be possible for an
 363      * unbounded number of supposedly removed nodes to remain reachable.
 364      * Situations leading to such buildup are uncommon but can occur
 365      * in practice; for example when a series of short timed calls to
 366      * poll repeatedly time out at the trailing node but otherwise
 367      * never fall off the list because of an untimed call to take() at
 368      * the front of the queue.
 369      *
 370      * When these cases arise, rather than always retraversing the
 371      * entire list to find an actual predecessor to unlink (which
 372      * won't help for case (1) anyway), we record a conservative
 373      * estimate of possible unsplice failures (in "sweepVotes").
 374      * We trigger a full sweep when the estimate exceeds a threshold
 375      * ("SWEEP_THRESHOLD") indicating the maximum number of estimated
 376      * removal failures to tolerate before sweeping through, unlinking
 377      * cancelled nodes that were not unlinked upon initial removal.
 378      * We perform sweeps by the thread hitting threshold (rather than
 379      * background threads or by spreading work to other threads)
 380      * because in the main contexts in which removal occurs, the
 381      * caller is timed-out or cancelled, which are not time-critical
 382      * enough to warrant the overhead that alternatives would impose
 383      * on other threads.
 384      *
 385      * Because the sweepVotes estimate is conservative, and because
 386      * nodes become unlinked "naturally" as they fall off the head of
 387      * the queue, and because we allow votes to accumulate even while
 388      * sweeps are in progress, there are typically significantly fewer
 389      * such nodes than estimated.  Choice of a threshold value
 390      * balances the likelihood of wasted effort and contention, versus
 391      * providing a worst-case bound on retention of interior nodes in
 392      * quiescent queues. The value defined below was chosen
 393      * empirically to balance these under various timeout scenarios.
 394      *
 395      * Because traversal operations on the linked list of nodes are a
 396      * natural opportunity to sweep dead nodes, we generally do so,
 397      * including all the operations that might remove elements as they
 398      * traverse, such as removeIf and Iterator.remove.  This largely
 399      * eliminates long chains of dead interior nodes, except from
 400      * cancelled or timed out blocking operations.
 401      *
 402      * Note that we cannot self-link unlinked interior nodes during
 403      * sweeps. However, the associated garbage chains terminate when
 404      * some successor ultimately falls off the head of the list and is
 405      * self-linked.
 406      */
 407 
 408     /** True if on multiprocessor */
 409     private static final boolean MP =
 410         Runtime.getRuntime().availableProcessors() > 1;
 411 
 412     /**
 413      * The number of times to spin (with randomly interspersed calls
 414      * to Thread.yield) on multiprocessor before blocking when a node
 415      * is apparently the first waiter in the queue.  See above for
 416      * explanation. Must be a power of two. The value is empirically
 417      * derived -- it works pretty well across a variety of processors,
 418      * numbers of CPUs, and OSes.
 419      */
 420     private static final int FRONT_SPINS   = 1 << 7;
 421 
 422     /**
 423      * The number of times to spin before blocking when a node is
 424      * preceded by another node that is apparently spinning.  Also
 425      * serves as an increment to FRONT_SPINS on phase changes, and as
 426      * base average frequency for yielding during spins. Must be a
 427      * power of two.
 428      */
 429     private static final int CHAINED_SPINS = FRONT_SPINS >>> 1;
 430 
 431     /**
 432      * The maximum number of estimated removal failures (sweepVotes)
 433      * to tolerate before sweeping through the queue unlinking
 434      * cancelled nodes that were not unlinked upon initial
 435      * removal. See above for explanation. The value must be at least
 436      * two to avoid useless sweeps when removing trailing nodes.
 437      */
 438     static final int SWEEP_THRESHOLD = 32;
 439 
 440     /**
 441      * Queue nodes. Uses Object, not E, for items to allow forgetting
 442      * them after use.  Writes that are intrinsically ordered wrt
 443      * other accesses or CASes use simple relaxed forms.
 444      */
 445     static final class Node {
 446         final boolean isData;   // false if this is a request node
 447         volatile Object item;   // initially non-null if isData; CASed to match
 448         volatile Node next;
 449         volatile Thread waiter; // null when not waiting for a match
 450 
 451         /**
 452          * Constructs a data node holding item if item is non-null,
 453          * else a request node.  Uses relaxed write because item can
 454          * only be seen after piggy-backing publication via CAS.
 455          */
 456         Node(Object item) {
 457             ITEM.set(this, item);
 458             isData = (item != null);
 459         }
 460 
 461         /** Constructs a (matched data) dummy node. */
 462         Node() {
 463             isData = true;
 464         }
 465 
 466         final boolean casNext(Node cmp, Node val) {
 467             // assert val != null;
 468             return NEXT.compareAndSet(this, cmp, val);
 469         }
 470 
 471         final boolean casItem(Object cmp, Object val) {
 472             // assert isData == (cmp != null);
 473             // assert isData == (val == null);
 474             // assert !(cmp instanceof Node);
 475             return ITEM.compareAndSet(this, cmp, val);
 476         }
 477 
 478         /**
 479          * Links node to itself to avoid garbage retention.  Called
 480          * only after CASing head field, so uses relaxed write.
 481          */
 482         final void selfLink() {
 483             // assert isMatched();
 484             NEXT.setRelease(this, this);
 485         }
 486 
 487         final void appendRelaxed(Node next) {
 488             // assert next != null;
 489             // assert this.next == null;
 490             NEXT.set(this, next);
 491         }
 492 
 493         /**
 494          * Sets item (of a request node) to self and waiter to null,
 495          * to avoid garbage retention after matching or cancelling.
 496          * Uses relaxed writes because order is already constrained in
 497          * the only calling contexts: item is forgotten only after
 498          * volatile/atomic mechanics that extract items, and visitors
 499          * of request nodes only ever check whether item is null.
 500          * Similarly, clearing waiter follows either CAS or return
 501          * from park (if ever parked; else we don't care).
 502          */
 503         final void forgetContents() {
 504             // assert isMatched();
 505             if (!isData)
 506                 ITEM.set(this, this);
 507             WAITER.set(this, null);
 508         }
 509 
 510         /**
 511          * Returns true if this node has been matched, including the
 512          * case of artificial matches due to cancellation.
 513          */
 514         final boolean isMatched() {
 515             return isData == (item == null);
 516         }
 517 
 518         /** Tries to CAS-match this node; if successful, wakes waiter. */
 519         final boolean tryMatch(Object cmp, Object val) {
 520             if (casItem(cmp, val)) {
 521                 LockSupport.unpark(waiter);
 522                 return true;
 523             }
 524             return false;
 525         }
 526 
 527         /**
 528          * Returns true if a node with the given mode cannot be
 529          * appended to this node because this node is unmatched and
 530          * has opposite data mode.
 531          */
 532         final boolean cannotPrecede(boolean haveData) {
 533             boolean d = isData;
 534             return d != haveData && d != (item == null);
 535         }
 536 
 537         private static final long serialVersionUID = -3375979862319811754L;
 538     }
 539 
 540     /**
 541      * A node from which the first live (non-matched) node (if any)
 542      * can be reached in O(1) time.
 543      * Invariants:
 544      * - all live nodes are reachable from head via .next
 545      * - head != null
 546      * - (tmp = head).next != tmp || tmp != head
 547      * Non-invariants:
 548      * - head may or may not be live
 549      * - it is permitted for tail to lag behind head, that is, for tail
 550      *   to not be reachable from head!
 551      */
 552     transient volatile Node head;
 553 
 554     /**
 555      * A node from which the last node on list (that is, the unique
 556      * node with node.next == null) can be reached in O(1) time.
 557      * Invariants:
 558      * - the last node is always reachable from tail via .next
 559      * - tail != null
 560      * Non-invariants:
 561      * - tail may or may not be live
 562      * - it is permitted for tail to lag behind head, that is, for tail
 563      *   to not be reachable from head!
 564      * - tail.next may or may not be self-linked.
 565      */
 566     private transient volatile Node tail;
 567 
 568     /** The number of apparent failures to unsplice cancelled nodes */
 569     private transient volatile int sweepVotes;
 570 
 571     private boolean casTail(Node cmp, Node val) {
 572         // assert cmp != null;
 573         // assert val != null;
 574         return TAIL.compareAndSet(this, cmp, val);
 575     }
 576 
 577     private boolean casHead(Node cmp, Node val) {
 578         return HEAD.compareAndSet(this, cmp, val);
 579     }
 580 
 581     /** Atomic version of ++sweepVotes. */
 582     private int incSweepVotes() {
 583         return (int) SWEEPVOTES.getAndAdd(this, 1) + 1;
 584     }
 585 
 586     /**
 587      * Tries to CAS pred.next (or head, if pred is null) from c to p.
 588      * Caller must ensure that we're not unlinking the trailing node.
 589      */
 590     private boolean tryCasSuccessor(Node pred, Node c, Node p) {
 591         // assert p != null;
 592         // assert c.isData != (c.item != null);
 593         // assert c != p;
 594         if (pred != null)
 595             return pred.casNext(c, p);
 596         if (casHead(c, p)) {
 597             c.selfLink();
 598             return true;
 599         }
 600         return false;
 601     }
 602 
 603     /**
 604      * Collapses dead (matched) nodes between pred and q.
 605      * @param pred the last known live node, or null if none
 606      * @param c the first dead node
 607      * @param p the last dead node
 608      * @param q p.next: the next live node, or null if at end
 609      * @return pred if pred still alive and CAS succeeded; else p
 610      */
 611     private Node skipDeadNodes(Node pred, Node c, Node p, Node q) {
 612         // assert pred != c;
 613         // assert p != q;
 614         // assert c.isMatched();
 615         // assert p.isMatched();
 616         if (q == null) {
 617             // Never unlink trailing node.
 618             if (c == p) return pred;
 619             q = p;
 620         }
 621         return (tryCasSuccessor(pred, c, q)
 622                 && (pred == null || !pred.isMatched()))
 623             ? pred : p;
 624     }
 625 
 626     /**
 627      * Collapses dead (matched) nodes from h (which was once head) to p.
 628      * Caller ensures all nodes from h up to and including p are dead.
 629      */
 630     private void skipDeadNodesNearHead(Node h, Node p) {
 631         // assert h != null;
 632         // assert h != p;
 633         // assert p.isMatched();
 634         for (;;) {
 635             final Node q;
 636             if ((q = p.next) == null) break;
 637             else if (!q.isMatched()) { p = q; break; }
 638             else if (p == (p = q)) return;
 639         }
 640         if (casHead(h, p))
 641             h.selfLink();
 642     }
 643 
 644     /* Possible values for "how" argument in xfer method. */
 645 
 646     private static final int NOW   = 0; // for untimed poll, tryTransfer
 647     private static final int ASYNC = 1; // for offer, put, add
 648     private static final int SYNC  = 2; // for transfer, take
 649     private static final int TIMED = 3; // for timed poll, tryTransfer
 650 
 651     /**
 652      * Implements all queuing methods. See above for explanation.
 653      *
 654      * @param e the item or null for take
 655      * @param haveData true if this is a put, else a take
 656      * @param how NOW, ASYNC, SYNC, or TIMED
 657      * @param nanos timeout in nanosecs, used only if mode is TIMED
 658      * @return an item if matched, else e
 659      * @throws NullPointerException if haveData mode but e is null
 660      */
 661     @SuppressWarnings("unchecked")
 662     private E xfer(E e, boolean haveData, int how, long nanos) {
 663         if (haveData && (e == null))
 664             throw new NullPointerException();
 665 
 666         restart: for (Node s = null, t = null, h = null;;) {
 667             for (Node p = (t != (t = tail) && t.isData == haveData) ? t
 668                      : (h = head);; ) {
 669                 final Node q; final Object item;
 670                 if (p.isData != haveData
 671                     && haveData == ((item = p.item) == null)) {
 672                     if (h == null) h = head;
 673                     if (p.tryMatch(item, e)) {
 674                         if (h != p) skipDeadNodesNearHead(h, p);
 675                         return (E) item;
 676                     }
 677                 }
 678                 if ((q = p.next) == null) {
 679                     if (how == NOW) return e;
 680                     if (s == null) s = new Node(e);
 681                     if (!p.casNext(null, s)) continue;
 682                     if (p != t) casTail(t, s);
 683                     if (how == ASYNC) return e;
 684                     return awaitMatch(s, p, e, (how == TIMED), nanos);
 685                 }
 686                 if (p == (p = q)) continue restart;
 687             }
 688         }
 689     }
 690 
 691     /**
 692      * Spins/yields/blocks until node s is matched or caller gives up.
 693      *
 694      * @param s the waiting node
 695      * @param pred the predecessor of s, or null if unknown (the null
 696      * case does not occur in any current calls but may in possible
 697      * future extensions)
 698      * @param e the comparison value for checking match
 699      * @param timed if true, wait only until timeout elapses
 700      * @param nanos timeout in nanosecs, used only if timed is true
 701      * @return matched item, or e if unmatched on interrupt or timeout
 702      */
 703     private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
 704         final long deadline = timed ? System.nanoTime() + nanos : 0L;
 705         Thread w = Thread.currentThread();
 706         int spins = -1; // initialized after first item and cancel checks
 707         ThreadLocalRandom randomYields = null; // bound if needed
 708 
 709         for (;;) {
 710             final Object item;
 711             if ((item = s.item) != e) {       // matched
 712                 // assert item != s;
 713                 s.forgetContents();           // avoid garbage
 714                 @SuppressWarnings("unchecked") E itemE = (E) item;
 715                 return itemE;
 716             }
 717             else if (w.isInterrupted() || (timed && nanos <= 0L)) {
 718                 // try to cancel and unlink
 719                 if (s.casItem(e, s.isData ? null : s)) {
 720                     unsplice(pred, s);
 721                     return e;
 722                 }
 723                 // return normally if lost CAS
 724             }
 725             else if (spins < 0) {            // establish spins at/near front
 726                 if ((spins = spinsFor(pred, s.isData)) > 0)
 727                     randomYields = ThreadLocalRandom.current();
 728             }
 729             else if (spins > 0) {             // spin
 730                 --spins;
 731                 if (randomYields.nextInt(CHAINED_SPINS) == 0)
 732                     Thread.yield();           // occasionally yield
 733             }
 734             else if (s.waiter == null) {
 735                 s.waiter = w;                 // request unpark then recheck
 736             }
 737             else if (timed) {
 738                 nanos = deadline - System.nanoTime();
 739                 if (nanos > 0L)
 740                     LockSupport.parkNanos(this, nanos);
 741             }
 742             else {
 743                 LockSupport.park(this);
 744             }
 745         }
 746     }
 747 
 748     /**
 749      * Returns spin/yield value for a node with given predecessor and
 750      * data mode. See above for explanation.
 751      */
 752     private static int spinsFor(Node pred, boolean haveData) {
 753         if (MP && pred != null) {
 754             if (pred.isData != haveData)      // phase change
 755                 return FRONT_SPINS + CHAINED_SPINS;
 756             if (pred.isMatched())             // probably at front
 757                 return FRONT_SPINS;
 758             if (pred.waiter == null)          // pred apparently spinning
 759                 return CHAINED_SPINS;
 760         }
 761         return 0;
 762     }
 763 
 764     /* -------------- Traversal methods -------------- */
 765 
 766     /**
 767      * Returns the first unmatched data node, or null if none.
 768      * Callers must recheck if the returned node is unmatched
 769      * before using.
 770      */
 771     final Node firstDataNode() {
 772         Node first = null;
 773         restartFromHead: for (;;) {
 774             Node h = head, p = h;
 775             while (p != null) {
 776                 if (p.item != null) {
 777                     if (p.isData) {
 778                         first = p;
 779                         break;
 780                     }
 781                 }
 782                 else if (!p.isData)
 783                     break;
 784                 final Node q;
 785                 if ((q = p.next) == null)
 786                     break;
 787                 if (p == (p = q))
 788                     continue restartFromHead;
 789             }
 790             if (p != h && casHead(h, p))
 791                 h.selfLink();
 792             return first;
 793         }
 794     }
 795 
 796     /**
 797      * Traverses and counts unmatched nodes of the given mode.
 798      * Used by methods size and getWaitingConsumerCount.
 799      */
 800     private int countOfMode(boolean data) {
 801         restartFromHead: for (;;) {
 802             int count = 0;
 803             for (Node p = head; p != null;) {
 804                 if (!p.isMatched()) {
 805                     if (p.isData != data)
 806                         return 0;
 807                     if (++count == Integer.MAX_VALUE)
 808                         break;  // @see Collection.size()
 809                 }
 810                 if (p == (p = p.next))
 811                     continue restartFromHead;
 812             }
 813             return count;
 814         }
 815     }
 816 
 817     public String toString() {
 818         String[] a = null;
 819         restartFromHead: for (;;) {
 820             int charLength = 0;
 821             int size = 0;
 822             for (Node p = head; p != null;) {
 823                 Object item = p.item;
 824                 if (p.isData) {
 825                     if (item != null) {
 826                         if (a == null)
 827                             a = new String[4];
 828                         else if (size == a.length)
 829                             a = Arrays.copyOf(a, 2 * size);
 830                         String s = item.toString();
 831                         a[size++] = s;
 832                         charLength += s.length();
 833                     }
 834                 } else if (item == null)
 835                     break;
 836                 if (p == (p = p.next))
 837                     continue restartFromHead;
 838             }
 839 
 840             if (size == 0)
 841                 return "[]";
 842 
 843             return Helpers.toString(a, size, charLength);
 844         }
 845     }
 846 
 847     private Object[] toArrayInternal(Object[] a) {
 848         Object[] x = a;
 849         restartFromHead: for (;;) {
 850             int size = 0;
 851             for (Node p = head; p != null;) {
 852                 Object item = p.item;
 853                 if (p.isData) {
 854                     if (item != null) {
 855                         if (x == null)
 856                             x = new Object[4];
 857                         else if (size == x.length)
 858                             x = Arrays.copyOf(x, 2 * (size + 4));
 859                         x[size++] = item;
 860                     }
 861                 } else if (item == null)
 862                     break;
 863                 if (p == (p = p.next))
 864                     continue restartFromHead;
 865             }
 866             if (x == null)
 867                 return new Object[0];
 868             else if (a != null && size <= a.length) {
 869                 if (a != x)
 870                     System.arraycopy(x, 0, a, 0, size);
 871                 if (size < a.length)
 872                     a[size] = null;
 873                 return a;
 874             }
 875             return (size == x.length) ? x : Arrays.copyOf(x, size);
 876         }
 877     }
 878 
 879     /**
 880      * Returns an array containing all of the elements in this queue, in
 881      * proper sequence.
 882      *
 883      * <p>The returned array will be "safe" in that no references to it are
 884      * maintained by this queue.  (In other words, this method must allocate
 885      * a new array).  The caller is thus free to modify the returned array.
 886      *
 887      * <p>This method acts as bridge between array-based and collection-based
 888      * APIs.
 889      *
 890      * @return an array containing all of the elements in this queue
 891      */
 892     public Object[] toArray() {
 893         return toArrayInternal(null);
 894     }
 895 
 896     /**
 897      * Returns an array containing all of the elements in this queue, in
 898      * proper sequence; the runtime type of the returned array is that of
 899      * the specified array.  If the queue fits in the specified array, it
 900      * is returned therein.  Otherwise, a new array is allocated with the
 901      * runtime type of the specified array and the size of this queue.
 902      *
 903      * <p>If this queue fits in the specified array with room to spare
 904      * (i.e., the array has more elements than this queue), the element in
 905      * the array immediately following the end of the queue is set to
 906      * {@code null}.
 907      *
 908      * <p>Like the {@link #toArray()} method, this method acts as bridge between
 909      * array-based and collection-based APIs.  Further, this method allows
 910      * precise control over the runtime type of the output array, and may,
 911      * under certain circumstances, be used to save allocation costs.
 912      *
 913      * <p>Suppose {@code x} is a queue known to contain only strings.
 914      * The following code can be used to dump the queue into a newly
 915      * allocated array of {@code String}:
 916      *
 917      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
 918      *
 919      * Note that {@code toArray(new Object[0])} is identical in function to
 920      * {@code toArray()}.
 921      *
 922      * @param a the array into which the elements of the queue are to
 923      *          be stored, if it is big enough; otherwise, a new array of the
 924      *          same runtime type is allocated for this purpose
 925      * @return an array containing all of the elements in this queue
 926      * @throws ArrayStoreException if the runtime type of the specified array
 927      *         is not a supertype of the runtime type of every element in
 928      *         this queue
 929      * @throws NullPointerException if the specified array is null
 930      */
 931     @SuppressWarnings("unchecked")
 932     public <T> T[] toArray(T[] a) {
 933         Objects.requireNonNull(a);
 934         return (T[]) toArrayInternal(a);
 935     }
 936 
 937     /**
 938      * Weakly-consistent iterator.
 939      *
 940      * Lazily updated ancestor is expected to be amortized O(1) remove(),
 941      * but O(n) in the worst case, when lastRet is concurrently deleted.
 942      */
 943     final class Itr implements Iterator<E> {
 944         private Node nextNode;   // next node to return item for
 945         private E nextItem;      // the corresponding item
 946         private Node lastRet;    // last returned node, to support remove
 947         private Node ancestor;   // Helps unlink lastRet on remove()
 948 
 949         /**
 950          * Moves to next node after pred, or first node if pred null.
 951          */
 952         @SuppressWarnings("unchecked")
 953         private void advance(Node pred) {
 954             for (Node p = (pred == null) ? head : pred.next, c = p;
 955                  p != null; ) {
 956                 final Object item;
 957                 if ((item = p.item) != null && p.isData) {
 958                     nextNode = p;
 959                     nextItem = (E) item;
 960                     if (c != p)
 961                         tryCasSuccessor(pred, c, p);
 962                     return;
 963                 }
 964                 else if (!p.isData && item == null)
 965                     break;
 966                 if (c != p && !tryCasSuccessor(pred, c, c = p)) {
 967                     pred = p;
 968                     c = p = p.next;
 969                 }
 970                 else if (p == (p = p.next)) {
 971                     pred = null;
 972                     c = p = head;
 973                 }
 974             }
 975             nextItem = null;
 976             nextNode = null;
 977         }
 978 
 979         Itr() {
 980             advance(null);
 981         }
 982 
 983         public final boolean hasNext() {
 984             return nextNode != null;
 985         }
 986 
 987         public final E next() {
 988             final Node p;
 989             if ((p = nextNode) == null) throw new NoSuchElementException();
 990             E e = nextItem;
 991             advance(lastRet = p);
 992             return e;
 993         }
 994 
 995         public void forEachRemaining(Consumer<? super E> action) {
 996             Objects.requireNonNull(action);
 997             Node q = null;
 998             for (Node p; (p = nextNode) != null; advance(q = p))
 999                 action.accept(nextItem);
1000             if (q != null)
1001                 lastRet = q;
1002         }
1003 
1004         public final void remove() {
1005             final Node lastRet = this.lastRet;
1006             if (lastRet == null)
1007                 throw new IllegalStateException();
1008             this.lastRet = null;
1009             if (lastRet.item == null)   // already deleted?
1010                 return;
1011             // Advance ancestor, collapsing intervening dead nodes
1012             Node pred = ancestor;
1013             for (Node p = (pred == null) ? head : pred.next, c = p, q;
1014                  p != null; ) {
1015                 if (p == lastRet) {
1016                     final Object item;
1017                     if ((item = p.item) != null)
1018                         p.tryMatch(item, null);
1019                     if ((q = p.next) == null) q = p;
1020                     if (c != q) tryCasSuccessor(pred, c, q);
1021                     ancestor = pred;
1022                     return;
1023                 }
1024                 final Object item; final boolean pAlive;
1025                 if (pAlive = ((item = p.item) != null && p.isData)) {
1026                     // exceptionally, nothing to do
1027                 }
1028                 else if (!p.isData && item == null)
1029                     break;
1030                 if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
1031                     pred = p;
1032                     c = p = p.next;
1033                 }
1034                 else if (p == (p = p.next)) {
1035                     pred = null;
1036                     c = p = head;
1037                 }
1038             }
1039             // traversal failed to find lastRet; must have been deleted;
1040             // leave ancestor at original location to avoid overshoot;
1041             // better luck next time!
1042 
1043             // assert lastRet.isMatched();
1044         }
1045     }
1046 
1047     /** A customized variant of Spliterators.IteratorSpliterator */
1048     final class LTQSpliterator implements Spliterator<E> {
1049         static final int MAX_BATCH = 1 << 25;  // max batch array size;
1050         Node current;       // current node; null until initialized
1051         int batch;          // batch size for splits
1052         boolean exhausted;  // true when no more nodes
1053         LTQSpliterator() {}
1054 
1055         public Spliterator<E> trySplit() {
1056             Node p, q;
1057             if ((p = current()) == null || (q = p.next) == null)
1058                 return null;
1059             int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
1060             Object[] a = null;
1061             do {
1062                 final Object item = p.item;
1063                 if (p.isData) {
1064                     if (item != null) {
1065                         if (a == null)
1066                             a = new Object[n];
1067                         a[i++] = item;
1068                     }
1069                 } else if (item == null) {
1070                     p = null;
1071                     break;
1072                 }
1073                 if (p == (p = q))
1074                     p = firstDataNode();
1075             } while (p != null && (q = p.next) != null && i < n);
1076             setCurrent(p);
1077             return (i == 0) ? null :
1078                 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
1079                                                    Spliterator.NONNULL |
1080                                                    Spliterator.CONCURRENT));
1081         }
1082 
1083         public void forEachRemaining(Consumer<? super E> action) {
1084             Objects.requireNonNull(action);
1085             final Node p;
1086             if ((p = current()) != null) {
1087                 current = null;
1088                 exhausted = true;
1089                 forEachFrom(action, p);
1090             }
1091         }
1092 
1093         @SuppressWarnings("unchecked")
1094         public boolean tryAdvance(Consumer<? super E> action) {
1095             Objects.requireNonNull(action);
1096             Node p;
1097             if ((p = current()) != null) {
1098                 E e = null;
1099                 do {
1100                     final Object item = p.item;
1101                     final boolean isData = p.isData;
1102                     if (p == (p = p.next))
1103                         p = head;
1104                     if (isData) {
1105                         if (item != null) {
1106                             e = (E) item;
1107                             break;
1108                         }
1109                     }
1110                     else if (item == null)
1111                         p = null;
1112                 } while (p != null);
1113                 setCurrent(p);
1114                 if (e != null) {
1115                     action.accept(e);
1116                     return true;
1117                 }
1118             }
1119             return false;
1120         }
1121 
1122         private void setCurrent(Node p) {
1123             if ((current = p) == null)
1124                 exhausted = true;
1125         }
1126 
1127         private Node current() {
1128             Node p;
1129             if ((p = current) == null && !exhausted)
1130                 setCurrent(p = firstDataNode());
1131             return p;
1132         }
1133 
1134         public long estimateSize() { return Long.MAX_VALUE; }
1135 
1136         public int characteristics() {
1137             return (Spliterator.ORDERED |
1138                     Spliterator.NONNULL |
1139                     Spliterator.CONCURRENT);
1140         }
1141     }
1142 
1143     /**
1144      * Returns a {@link Spliterator} over the elements in this queue.
1145      *
1146      * <p>The returned spliterator is
1147      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1148      *
1149      * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1150      * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1151      *
1152      * @implNote
1153      * The {@code Spliterator} implements {@code trySplit} to permit limited
1154      * parallelism.
1155      *
1156      * @return a {@code Spliterator} over the elements in this queue
1157      * @since 1.8
1158      */
1159     public Spliterator<E> spliterator() {
1160         return new LTQSpliterator();
1161     }
1162 
1163     /* -------------- Removal methods -------------- */
1164 
1165     /**
1166      * Unsplices (now or later) the given deleted/cancelled node with
1167      * the given predecessor.
1168      *
1169      * @param pred a node that was at one time known to be the
1170      * predecessor of s
1171      * @param s the node to be unspliced
1172      */
1173     final void unsplice(Node pred, Node s) {
1174         // assert pred != null;
1175         // assert pred != s;
1176         // assert s != null;
1177         // assert s.isMatched();
1178         // assert (SWEEP_THRESHOLD & (SWEEP_THRESHOLD - 1)) == 0;
1179         s.waiter = null; // disable signals
1180         /*
1181          * See above for rationale. Briefly: if pred still points to
1182          * s, try to unlink s.  If s cannot be unlinked, because it is
1183          * trailing node or pred might be unlinked, and neither pred
1184          * nor s are head or offlist, add to sweepVotes, and if enough
1185          * votes have accumulated, sweep.
1186          */
1187         if (pred != null && pred.next == s) {
1188             Node n = s.next;
1189             if (n == null ||
1190                 (n != s && pred.casNext(s, n) && pred.isMatched())) {
1191                 for (;;) {               // check if at, or could be, head
1192                     Node h = head;
1193                     if (h == pred || h == s)
1194                         return;          // at head or list empty
1195                     if (!h.isMatched())
1196                         break;
1197                     Node hn = h.next;
1198                     if (hn == null)
1199                         return;          // now empty
1200                     if (hn != h && casHead(h, hn))
1201                         h.selfLink();  // advance head
1202                 }
1203                 // sweep every SWEEP_THRESHOLD votes
1204                 if (pred.next != pred && s.next != s // recheck if offlist
1205                     && (incSweepVotes() & (SWEEP_THRESHOLD - 1)) == 0)
1206                     sweep();
1207             }
1208         }
1209     }
1210 
1211     /**
1212      * Unlinks matched (typically cancelled) nodes encountered in a
1213      * traversal from head.
1214      */
1215     private void sweep() {
1216         for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
1217             if (!s.isMatched())
1218                 // Unmatched nodes are never self-linked
1219                 p = s;
1220             else if ((n = s.next) == null) // trailing node is pinned
1221                 break;
1222             else if (s == n)    // stale
1223                 // No need to also check for p == s, since that implies s == n
1224                 p = head;
1225             else
1226                 p.casNext(s, n);
1227         }
1228     }
1229 
1230     /**
1231      * Creates an initially empty {@code LinkedTransferQueue}.
1232      */
1233     public LinkedTransferQueue() {
1234         head = tail = new Node();
1235     }
1236 
1237     /**
1238      * Creates a {@code LinkedTransferQueue}
1239      * initially containing the elements of the given collection,
1240      * added in traversal order of the collection's iterator.
1241      *
1242      * @param c the collection of elements to initially contain
1243      * @throws NullPointerException if the specified collection or any
1244      *         of its elements are null
1245      */
1246     public LinkedTransferQueue(Collection<? extends E> c) {
1247         Node h = null, t = null;
1248         for (E e : c) {
1249             Node newNode = new Node(Objects.requireNonNull(e));
1250             if (h == null)
1251                 h = t = newNode;
1252             else
1253                 t.appendRelaxed(t = newNode);
1254         }
1255         if (h == null)
1256             h = t = new Node();
1257         head = h;
1258         tail = t;
1259     }
1260 
1261     /**
1262      * Inserts the specified element at the tail of this queue.
1263      * As the queue is unbounded, this method will never block.
1264      *
1265      * @throws NullPointerException if the specified element is null
1266      */
1267     public void put(E e) {
1268         xfer(e, true, ASYNC, 0);
1269     }
1270 
1271     /**
1272      * Inserts the specified element at the tail of this queue.
1273      * As the queue is unbounded, this method will never block or
1274      * return {@code false}.
1275      *
1276      * @return {@code true} (as specified by
1277      *  {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
1278      * @throws NullPointerException if the specified element is null
1279      */
1280     public boolean offer(E e, long timeout, TimeUnit unit) {
1281         xfer(e, true, ASYNC, 0);
1282         return true;
1283     }
1284 
1285     /**
1286      * Inserts the specified element at the tail of this queue.
1287      * As the queue is unbounded, this method will never return {@code false}.
1288      *
1289      * @return {@code true} (as specified by {@link Queue#offer})
1290      * @throws NullPointerException if the specified element is null
1291      */
1292     public boolean offer(E e) {
1293         xfer(e, true, ASYNC, 0);
1294         return true;
1295     }
1296 
1297     /**
1298      * Inserts the specified element at the tail of this queue.
1299      * As the queue is unbounded, this method will never throw
1300      * {@link IllegalStateException} or return {@code false}.
1301      *
1302      * @return {@code true} (as specified by {@link Collection#add})
1303      * @throws NullPointerException if the specified element is null
1304      */
1305     public boolean add(E e) {
1306         xfer(e, true, ASYNC, 0);
1307         return true;
1308     }
1309 
1310     /**
1311      * Transfers the element to a waiting consumer immediately, if possible.
1312      *
1313      * <p>More precisely, transfers the specified element immediately
1314      * if there exists a consumer already waiting to receive it (in
1315      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1316      * otherwise returning {@code false} without enqueuing the element.
1317      *
1318      * @throws NullPointerException if the specified element is null
1319      */
1320     public boolean tryTransfer(E e) {
1321         return xfer(e, true, NOW, 0) == null;
1322     }
1323 
1324     /**
1325      * Transfers the element to a consumer, waiting if necessary to do so.
1326      *
1327      * <p>More precisely, transfers the specified element immediately
1328      * if there exists a consumer already waiting to receive it (in
1329      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1330      * else inserts the specified element at the tail of this queue
1331      * and waits until the element is received by a consumer.
1332      *
1333      * @throws NullPointerException if the specified element is null
1334      */
1335     public void transfer(E e) throws InterruptedException {
1336         if (xfer(e, true, SYNC, 0) != null) {
1337             Thread.interrupted(); // failure possible only due to interrupt
1338             throw new InterruptedException();
1339         }
1340     }
1341 
1342     /**
1343      * Transfers the element to a consumer if it is possible to do so
1344      * before the timeout elapses.
1345      *
1346      * <p>More precisely, transfers the specified element immediately
1347      * if there exists a consumer already waiting to receive it (in
1348      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1349      * else inserts the specified element at the tail of this queue
1350      * and waits until the element is received by a consumer,
1351      * returning {@code false} if the specified wait time elapses
1352      * before the element can be transferred.
1353      *
1354      * @throws NullPointerException if the specified element is null
1355      */
1356     public boolean tryTransfer(E e, long timeout, TimeUnit unit)
1357         throws InterruptedException {
1358         if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
1359             return true;
1360         if (!Thread.interrupted())
1361             return false;
1362         throw new InterruptedException();
1363     }
1364 
1365     public E take() throws InterruptedException {
1366         E e = xfer(null, false, SYNC, 0);
1367         if (e != null)
1368             return e;
1369         Thread.interrupted();
1370         throw new InterruptedException();
1371     }
1372 
1373     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
1374         E e = xfer(null, false, TIMED, unit.toNanos(timeout));
1375         if (e != null || !Thread.interrupted())
1376             return e;
1377         throw new InterruptedException();
1378     }
1379 
1380     public E poll() {
1381         return xfer(null, false, NOW, 0);
1382     }
1383 
1384     /**
1385      * @throws NullPointerException     {@inheritDoc}
1386      * @throws IllegalArgumentException {@inheritDoc}
1387      */
1388     public int drainTo(Collection<? super E> c) {
1389         Objects.requireNonNull(c);
1390         if (c == this)
1391             throw new IllegalArgumentException();
1392         int n = 0;
1393         for (E e; (e = poll()) != null; n++)
1394             c.add(e);
1395         return n;
1396     }
1397 
1398     /**
1399      * @throws NullPointerException     {@inheritDoc}
1400      * @throws IllegalArgumentException {@inheritDoc}
1401      */
1402     public int drainTo(Collection<? super E> c, int maxElements) {
1403         Objects.requireNonNull(c);
1404         if (c == this)
1405             throw new IllegalArgumentException();
1406         int n = 0;
1407         for (E e; n < maxElements && (e = poll()) != null; n++)
1408             c.add(e);
1409         return n;
1410     }
1411 
1412     /**
1413      * Returns an iterator over the elements in this queue in proper sequence.
1414      * The elements will be returned in order from first (head) to last (tail).
1415      *
1416      * <p>The returned iterator is
1417      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1418      *
1419      * @return an iterator over the elements in this queue in proper sequence
1420      */
1421     public Iterator<E> iterator() {
1422         return new Itr();
1423     }
1424 
1425     public E peek() {
1426         restartFromHead: for (;;) {
1427             for (Node p = head; p != null;) {
1428                 Object item = p.item;
1429                 if (p.isData) {
1430                     if (item != null) {
1431                         @SuppressWarnings("unchecked") E e = (E) item;
1432                         return e;
1433                     }
1434                 }
1435                 else if (item == null)
1436                     break;
1437                 if (p == (p = p.next))
1438                     continue restartFromHead;
1439             }
1440             return null;
1441         }
1442     }
1443 
1444     /**
1445      * Returns {@code true} if this queue contains no elements.
1446      *
1447      * @return {@code true} if this queue contains no elements
1448      */
1449     public boolean isEmpty() {
1450         return firstDataNode() == null;
1451     }
1452 
1453     public boolean hasWaitingConsumer() {
1454         restartFromHead: for (;;) {
1455             for (Node p = head; p != null;) {
1456                 Object item = p.item;
1457                 if (p.isData) {
1458                     if (item != null)
1459                         break;
1460                 }
1461                 else if (item == null)
1462                     return true;
1463                 if (p == (p = p.next))
1464                     continue restartFromHead;
1465             }
1466             return false;
1467         }
1468     }
1469 
1470     /**
1471      * Returns the number of elements in this queue.  If this queue
1472      * contains more than {@code Integer.MAX_VALUE} elements, returns
1473      * {@code Integer.MAX_VALUE}.
1474      *
1475      * <p>Beware that, unlike in most collections, this method is
1476      * <em>NOT</em> a constant-time operation. Because of the
1477      * asynchronous nature of these queues, determining the current
1478      * number of elements requires an O(n) traversal.
1479      *
1480      * @return the number of elements in this queue
1481      */
1482     public int size() {
1483         return countOfMode(true);
1484     }
1485 
1486     public int getWaitingConsumerCount() {
1487         return countOfMode(false);
1488     }
1489 
1490     /**
1491      * Removes a single instance of the specified element from this queue,
1492      * if it is present.  More formally, removes an element {@code e} such
1493      * that {@code o.equals(e)}, if this queue contains one or more such
1494      * elements.
1495      * Returns {@code true} if this queue contained the specified element
1496      * (or equivalently, if this queue changed as a result of the call).
1497      *
1498      * @param o element to be removed from this queue, if present
1499      * @return {@code true} if this queue changed as a result of the call
1500      */
1501     public boolean remove(Object o) {
1502         if (o == null) return false;
1503         restartFromHead: for (;;) {
1504             for (Node p = head, pred = null; p != null; ) {
1505                 Node q = p.next;
1506                 final Object item;
1507                 if ((item = p.item) != null) {
1508                     if (p.isData) {
1509                         if (o.equals(item) && p.tryMatch(item, null)) {
1510                             skipDeadNodes(pred, p, p, q);
1511                             return true;
1512                         }
1513                         pred = p; p = q; continue;
1514                     }
1515                 }
1516                 else if (!p.isData)
1517                     break;
1518                 for (Node c = p;; q = p.next) {
1519                     if (q == null || !q.isMatched()) {
1520                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1521                     }
1522                     if (p == (p = q)) continue restartFromHead;
1523                 }
1524             }
1525             return false;
1526         }
1527     }
1528 
1529     /**
1530      * Returns {@code true} if this queue contains the specified element.
1531      * More formally, returns {@code true} if and only if this queue contains
1532      * at least one element {@code e} such that {@code o.equals(e)}.
1533      *
1534      * @param o object to be checked for containment in this queue
1535      * @return {@code true} if this queue contains the specified element
1536      */
1537     public boolean contains(Object o) {
1538         if (o == null) return false;
1539         restartFromHead: for (;;) {
1540             for (Node p = head, pred = null; p != null; ) {
1541                 Node q = p.next;
1542                 final Object item;
1543                 if ((item = p.item) != null) {
1544                     if (p.isData) {
1545                         if (o.equals(item))
1546                             return true;
1547                         pred = p; p = q; continue;
1548                     }
1549                 }
1550                 else if (!p.isData)
1551                     break;
1552                 for (Node c = p;; q = p.next) {
1553                     if (q == null || !q.isMatched()) {
1554                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1555                     }
1556                     if (p == (p = q)) continue restartFromHead;
1557                 }
1558             }
1559             return false;
1560         }
1561     }
1562 
1563     /**
1564      * Always returns {@code Integer.MAX_VALUE} because a
1565      * {@code LinkedTransferQueue} is not capacity constrained.
1566      *
1567      * @return {@code Integer.MAX_VALUE} (as specified by
1568      *         {@link BlockingQueue#remainingCapacity()})
1569      */
1570     public int remainingCapacity() {
1571         return Integer.MAX_VALUE;
1572     }
1573 
1574     /**
1575      * Saves this queue to a stream (that is, serializes it).
1576      *
1577      * @param s the stream
1578      * @throws java.io.IOException if an I/O error occurs
1579      * @serialData All of the elements (each an {@code E}) in
1580      * the proper order, followed by a null
1581      */
1582     private void writeObject(java.io.ObjectOutputStream s)
1583         throws java.io.IOException {
1584         s.defaultWriteObject();
1585         for (E e : this)
1586             s.writeObject(e);
1587         // Use trailing null as sentinel
1588         s.writeObject(null);
1589     }
1590 
1591     /**
1592      * Reconstitutes this queue from a stream (that is, deserializes it).
1593      * @param s the stream
1594      * @throws ClassNotFoundException if the class of a serialized object
1595      *         could not be found
1596      * @throws java.io.IOException if an I/O error occurs
1597      */
1598     private void readObject(java.io.ObjectInputStream s)
1599         throws java.io.IOException, ClassNotFoundException {
1600 
1601         // Read in elements until trailing null sentinel found
1602         Node h = null, t = null;
1603         for (Object item; (item = s.readObject()) != null; ) {
1604             Node newNode = new Node(item);
1605             if (h == null)
1606                 h = t = newNode;
1607             else
1608                 t.appendRelaxed(t = newNode);
1609         }
1610         if (h == null)
1611             h = t = new Node();
1612         head = h;
1613         tail = t;
1614     }
1615 
1616     /**
1617      * @throws NullPointerException {@inheritDoc}
1618      */
1619     public boolean removeIf(Predicate<? super E> filter) {
1620         Objects.requireNonNull(filter);
1621         return bulkRemove(filter);
1622     }
1623 
1624     /**
1625      * @throws NullPointerException {@inheritDoc}
1626      */
1627     public boolean removeAll(Collection<?> c) {
1628         Objects.requireNonNull(c);
1629         return bulkRemove(e -> c.contains(e));
1630     }
1631 
1632     /**
1633      * @throws NullPointerException {@inheritDoc}
1634      */
1635     public boolean retainAll(Collection<?> c) {
1636         Objects.requireNonNull(c);
1637         return bulkRemove(e -> !c.contains(e));
1638     }
1639 
1640     public void clear() {
1641         bulkRemove(e -> true);
1642     }
1643 
1644     /**
1645      * Tolerate this many consecutive dead nodes before CAS-collapsing.
1646      * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
1647      */
1648     private static final int MAX_HOPS = 8;
1649 
1650     /** Implementation of bulk remove methods. */
1651     @SuppressWarnings("unchecked")
1652     private boolean bulkRemove(Predicate<? super E> filter) {
1653         boolean removed = false;
1654         restartFromHead: for (;;) {
1655             int hops = MAX_HOPS;
1656             // c will be CASed to collapse intervening dead nodes between
1657             // pred (or head if null) and p.
1658             for (Node p = head, c = p, pred = null, q; p != null; p = q) {
1659                 q = p.next;
1660                 final Object item; boolean pAlive;
1661                 if (pAlive = ((item = p.item) != null && p.isData)) {
1662                     if (filter.test((E) item)) {
1663                         if (p.tryMatch(item, null))
1664                             removed = true;
1665                         pAlive = false;
1666                     }
1667                 }
1668                 else if (!p.isData && item == null)
1669                     break;
1670                 if (pAlive || q == null || --hops == 0) {
1671                     // p might already be self-linked here, but if so:
1672                     // - CASing head will surely fail
1673                     // - CASing pred's next will be useless but harmless.
1674                     if ((c != p && !tryCasSuccessor(pred, c, c = p))
1675                         || pAlive) {
1676                         // if CAS failed or alive, abandon old pred
1677                         hops = MAX_HOPS;
1678                         pred = p;
1679                         c = q;
1680                     }
1681                 } else if (p == q)
1682                     continue restartFromHead;
1683             }
1684             return removed;
1685         }
1686     }
1687 
1688     /**
1689      * Runs action on each element found during a traversal starting at p.
1690      * If p is null, the action is not run.
1691      */
1692     @SuppressWarnings("unchecked")
1693     void forEachFrom(Consumer<? super E> action, Node p) {
1694         for (Node pred = null; p != null; ) {
1695             Node q = p.next;
1696             final Object item;
1697             if ((item = p.item) != null) {
1698                 if (p.isData) {
1699                     action.accept((E) item);
1700                     pred = p; p = q; continue;
1701                 }
1702             }
1703             else if (!p.isData)
1704                 break;
1705             for (Node c = p;; q = p.next) {
1706                 if (q == null || !q.isMatched()) {
1707                     pred = skipDeadNodes(pred, c, p, q); p = q; break;
1708                 }
1709                 if (p == (p = q)) { pred = null; p = head; break; }
1710             }
1711         }
1712     }
1713 
1714     /**
1715      * @throws NullPointerException {@inheritDoc}
1716      */
1717     public void forEach(Consumer<? super E> action) {
1718         Objects.requireNonNull(action);
1719         forEachFrom(action, head);
1720     }
1721 
1722     // VarHandle mechanics
1723     private static final VarHandle HEAD;
1724     private static final VarHandle TAIL;
1725     private static final VarHandle SWEEPVOTES;
1726     static final VarHandle ITEM;
1727     static final VarHandle NEXT;
1728     static final VarHandle WAITER;
1729     static {
1730         try {
1731             MethodHandles.Lookup l = MethodHandles.lookup();
1732             HEAD = l.findVarHandle(LinkedTransferQueue.class, "head",
1733                                    Node.class);
1734             TAIL = l.findVarHandle(LinkedTransferQueue.class, "tail",
1735                                    Node.class);
1736             SWEEPVOTES = l.findVarHandle(LinkedTransferQueue.class, "sweepVotes",
1737                                          int.class);
1738             ITEM = l.findVarHandle(Node.class, "item", Object.class);
1739             NEXT = l.findVarHandle(Node.class, "next", Node.class);
1740             WAITER = l.findVarHandle(Node.class, "waiter", Thread.class);
1741         } catch (ReflectiveOperationException e) {
1742             throw new ExceptionInInitializerError(e);
1743         }
1744 
1745         // Reduce the risk of rare disastrous classloading in first call to
1746         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1747         Class<?> ensureLoaded = LockSupport.class;
1748     }
1749 }