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}/../technotes/guides/collections/index.html">
  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             for (; p != null;) {
 776                 final Object item;
 777                 if ((item = p.item) != null) {
 778                     if (p.isData) {
 779                         first = p;
 780                         break;
 781                     }
 782                 }
 783                 else if (!p.isData)
 784                     break;
 785                 final Node q;
 786                 if ((q = p.next) == null)
 787                     break;
 788                 if (p == (p = q))
 789                     continue restartFromHead;
 790             }
 791             if (p != h && casHead(h, p))
 792                 h.selfLink();
 793             return first;
 794         }
 795     }
 796 
 797     /**
 798      * Traverses and counts unmatched nodes of the given mode.
 799      * Used by methods size and getWaitingConsumerCount.
 800      */
 801     private int countOfMode(boolean data) {
 802         restartFromHead: for (;;) {
 803             int count = 0;
 804             for (Node p = head; p != null;) {
 805                 if (!p.isMatched()) {
 806                     if (p.isData != data)
 807                         return 0;
 808                     if (++count == Integer.MAX_VALUE)
 809                         break;  // @see Collection.size()
 810                 }
 811                 if (p == (p = p.next))
 812                     continue restartFromHead;
 813             }
 814             return count;
 815         }
 816     }
 817 
 818     public String toString() {
 819         String[] a = null;
 820         restartFromHead: for (;;) {
 821             int charLength = 0;
 822             int size = 0;
 823             for (Node p = head; p != null;) {
 824                 Object item = p.item;
 825                 if (p.isData) {
 826                     if (item != null) {
 827                         if (a == null)
 828                             a = new String[4];
 829                         else if (size == a.length)
 830                             a = Arrays.copyOf(a, 2 * size);
 831                         String s = item.toString();
 832                         a[size++] = s;
 833                         charLength += s.length();
 834                     }
 835                 } else if (item == null)
 836                     break;
 837                 if (p == (p = p.next))
 838                     continue restartFromHead;
 839             }
 840 
 841             if (size == 0)
 842                 return "[]";
 843 
 844             return Helpers.toString(a, size, charLength);
 845         }
 846     }
 847 
 848     private Object[] toArrayInternal(Object[] a) {
 849         Object[] x = a;
 850         restartFromHead: for (;;) {
 851             int size = 0;
 852             for (Node p = head; p != null;) {
 853                 Object item = p.item;
 854                 if (p.isData) {
 855                     if (item != null) {
 856                         if (x == null)
 857                             x = new Object[4];
 858                         else if (size == x.length)
 859                             x = Arrays.copyOf(x, 2 * (size + 4));
 860                         x[size++] = item;
 861                     }
 862                 } else if (item == null)
 863                     break;
 864                 if (p == (p = p.next))
 865                     continue restartFromHead;
 866             }
 867             if (x == null)
 868                 return new Object[0];
 869             else if (a != null && size <= a.length) {
 870                 if (a != x)
 871                     System.arraycopy(x, 0, a, 0, size);
 872                 if (size < a.length)
 873                     a[size] = null;
 874                 return a;
 875             }
 876             return (size == x.length) ? x : Arrays.copyOf(x, size);
 877         }
 878     }
 879 
 880     /**
 881      * Returns an array containing all of the elements in this queue, in
 882      * proper sequence.
 883      *
 884      * <p>The returned array will be "safe" in that no references to it are
 885      * maintained by this queue.  (In other words, this method must allocate
 886      * a new array).  The caller is thus free to modify the returned array.
 887      *
 888      * <p>This method acts as bridge between array-based and collection-based
 889      * APIs.
 890      *
 891      * @return an array containing all of the elements in this queue

 892      */
 893     public Object[] toArray() {
 894         return toArrayInternal(null);
 895     }
 896 
 897     /**
 898      * Returns an array containing all of the elements in this queue, in
 899      * proper sequence; the runtime type of the returned array is that of
 900      * the specified array.  If the queue fits in the specified array, it
 901      * is returned therein.  Otherwise, a new array is allocated with the
 902      * runtime type of the specified array and the size of this queue.
 903      *
 904      * <p>If this queue fits in the specified array with room to spare
 905      * (i.e., the array has more elements than this queue), the element in
 906      * the array immediately following the end of the queue is set to
 907      * {@code null}.
 908      *
 909      * <p>Like the {@link #toArray()} method, this method acts as bridge between
 910      * array-based and collection-based APIs.  Further, this method allows
 911      * precise control over the runtime type of the output array, and may,
 912      * under certain circumstances, be used to save allocation costs.
 913      *
 914      * <p>Suppose {@code x} is a queue known to contain only strings.
 915      * The following code can be used to dump the queue into a newly
 916      * allocated array of {@code String}:
 917      *
 918      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
 919      *
 920      * Note that {@code toArray(new Object[0])} is identical in function to
 921      * {@code toArray()}.
 922      *
 923      * @param a the array into which the elements of the queue are to
 924      *          be stored, if it is big enough; otherwise, a new array of the
 925      *          same runtime type is allocated for this purpose
 926      * @return an array containing all of the elements in this queue
 927      * @throws ArrayStoreException if the runtime type of the specified array
 928      *         is not a supertype of the runtime type of every element in
 929      *         this queue
 930      * @throws NullPointerException if the specified array is null

 931      */
 932     @SuppressWarnings("unchecked")
 933     public <T> T[] toArray(T[] a) {
 934         Objects.requireNonNull(a);
 935         return (T[]) toArrayInternal(a);
 936     }
 937 
 938     /**
 939      * Weakly-consistent iterator.
 940      *
 941      * Lazily updated ancestor is expected to be amortized O(1) remove(),
 942      * but O(n) in the worst case, when lastRet is concurrently deleted.
 943      */
 944     final class Itr implements Iterator<E> {
 945         private Node nextNode;   // next node to return item for
 946         private E nextItem;      // the corresponding item
 947         private Node lastRet;    // last returned node, to support remove
 948         private Node ancestor;   // Helps unlink lastRet on remove()
 949 
 950         /**
 951          * Moves to next node after pred, or first node if pred null.
 952          */
 953         @SuppressWarnings("unchecked")
 954         private void advance(Node pred) {
 955             for (Node p = (pred == null) ? head : pred.next, c = p;
 956                  p != null; ) {
 957                 final Object item;
 958                 if ((item = p.item) != null && p.isData) {
 959                     nextNode = p;
 960                     nextItem = (E) item;
 961                     if (c != p)
 962                         tryCasSuccessor(pred, c, p);
 963                     return;
 964                 }
 965                 else if (!p.isData && item == null)
 966                     break;
 967                 if (c != p && !tryCasSuccessor(pred, c, c = p)) {
 968                     pred = p;
 969                     c = p = p.next;
 970                 }
 971                 else if (p == (p = p.next)) {
 972                     pred = null;
 973                     c = p = head;
 974                 }
 975             }
 976             nextItem = null;
 977             nextNode = null;
 978         }
 979 
 980         Itr() {
 981             advance(null);
 982         }
 983 
 984         public final boolean hasNext() {
 985             return nextNode != null;
 986         }
 987 
 988         public final E next() {
 989             final Node p;
 990             if ((p = nextNode) == null) throw new NoSuchElementException();
 991             E e = nextItem;
 992             advance(lastRet = p);
 993             return e;
 994         }
 995 
 996         public void forEachRemaining(Consumer<? super E> action) {
 997             Objects.requireNonNull(action);
 998             Node q = null;
 999             for (Node p; (p = nextNode) != null; advance(q = p))
1000                 action.accept(nextItem);
1001             if (q != null)
1002                 lastRet = q;
1003         }
1004 
1005         public final void remove() {
1006             final Node lastRet = this.lastRet;
1007             if (lastRet == null)
1008                 throw new IllegalStateException();
1009             this.lastRet = null;
1010             if (lastRet.item == null)   // already deleted?
1011                 return;
1012             // Advance ancestor, collapsing intervening dead nodes
1013             Node pred = ancestor;
1014             for (Node p = (pred == null) ? head : pred.next, c = p, q;
1015                  p != null; ) {
1016                 if (p == lastRet) {
1017                     final Object item;
1018                     if ((item = p.item) != null)
1019                         p.tryMatch(item, null);
1020                     if ((q = p.next) == null) q = p;
1021                     if (c != q) tryCasSuccessor(pred, c, q);
1022                     ancestor = pred;
1023                     return;
1024                 }
1025                 final Object item; final boolean pAlive;
1026                 if (pAlive = ((item = p.item) != null && p.isData)) {
1027                     // exceptionally, nothing to do
1028                 }
1029                 else if (!p.isData && item == null)
1030                     break;
1031                 if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
1032                     pred = p;
1033                     c = p = p.next;
1034                 }
1035                 else if (p == (p = p.next)) {
1036                     pred = null;
1037                     c = p = head;
1038                 }
1039             }
1040             // traversal failed to find lastRet; must have been deleted;
1041             // leave ancestor at original location to avoid overshoot;
1042             // better luck next time!
1043 
1044             // assert lastRet.isMatched();
1045         }
1046     }
1047 
1048     /** A customized variant of Spliterators.IteratorSpliterator */
1049     final class LTQSpliterator implements Spliterator<E> {
1050         static final int MAX_BATCH = 1 << 25;  // max batch array size;
1051         Node current;       // current node; null until initialized
1052         int batch;          // batch size for splits
1053         boolean exhausted;  // true when no more nodes
1054         LTQSpliterator() {}
1055 
1056         public Spliterator<E> trySplit() {
1057             Node p, q;
1058             if ((p = current()) == null || (q = p.next) == null)
1059                 return null;
1060             int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
1061             Object[] a = null;
1062             do {
1063                 final Object item = p.item;
1064                 if (p.isData) {
1065                     if (item != null) {
1066                         if (a == null)
1067                             a = new Object[n];
1068                         a[i++] = item;
1069                     }
1070                 } else if (item == null) {
1071                     p = null;
1072                     break;
1073                 }
1074                 if (p == (p = q))
1075                     p = firstDataNode();
1076             } while (p != null && (q = p.next) != null && i < n);
1077             setCurrent(p);
1078             return (i == 0) ? null :
1079                 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
1080                                                    Spliterator.NONNULL |
1081                                                    Spliterator.CONCURRENT));
1082         }
1083 
1084         public void forEachRemaining(Consumer<? super E> action) {
1085             Objects.requireNonNull(action);
1086             final Node p;
1087             if ((p = current()) != null) {
1088                 current = null;
1089                 exhausted = true;
1090                 forEachFrom(action, p);
1091             }
1092         }
1093 
1094         @SuppressWarnings("unchecked")
1095         public boolean tryAdvance(Consumer<? super E> action) {
1096             Objects.requireNonNull(action);
1097             Node p;
1098             if ((p = current()) != null) {
1099                 E e = null;
1100                 do {
1101                     final Object item = p.item;
1102                     final boolean isData = p.isData;
1103                     if (p == (p = p.next))
1104                         p = head;
1105                     if (isData) {
1106                         if (item != null) {
1107                             e = (E) item;
1108                             break;
1109                         }
1110                     }
1111                     else if (item == null)
1112                         p = null;
1113                 } while (p != null);
1114                 setCurrent(p);
1115                 if (e != null) {
1116                     action.accept(e);
1117                     return true;
1118                 }
1119             }
1120             return false;
1121         }
1122 
1123         private void setCurrent(Node p) {
1124             if ((current = p) == null)
1125                 exhausted = true;
1126         }
1127 
1128         private Node current() {
1129             Node p;
1130             if ((p = current) == null && !exhausted)
1131                 setCurrent(p = firstDataNode());
1132             return p;
1133         }
1134 
1135         public long estimateSize() { return Long.MAX_VALUE; }
1136 
1137         public int characteristics() {
1138             return (Spliterator.ORDERED |
1139                     Spliterator.NONNULL |
1140                     Spliterator.CONCURRENT);
1141         }
1142     }
1143 
1144     /**
1145      * Returns a {@link Spliterator} over the elements in this queue.
1146      *
1147      * <p>The returned spliterator is
1148      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1149      *
1150      * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1151      * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1152      *
1153      * @implNote
1154      * The {@code Spliterator} implements {@code trySplit} to permit limited
1155      * parallelism.
1156      *
1157      * @return a {@code Spliterator} over the elements in this queue
1158      * @since 1.8
1159      */
1160     public Spliterator<E> spliterator() {
1161         return new LTQSpliterator();
1162     }
1163 
1164     /* -------------- Removal methods -------------- */
1165 
1166     /**
1167      * Unsplices (now or later) the given deleted/cancelled node with
1168      * the given predecessor.
1169      *
1170      * @param pred a node that was at one time known to be the
1171      * predecessor of s
1172      * @param s the node to be unspliced
1173      */
1174     final void unsplice(Node pred, Node s) {
1175         // assert pred != null;
1176         // assert pred != s;
1177         // assert s != null;
1178         // assert s.isMatched();
1179         // assert (SWEEP_THRESHOLD & (SWEEP_THRESHOLD - 1)) == 0;
1180         s.waiter = null; // disable signals
1181         /*
1182          * See above for rationale. Briefly: if pred still points to
1183          * s, try to unlink s.  If s cannot be unlinked, because it is
1184          * trailing node or pred might be unlinked, and neither pred
1185          * nor s are head or offlist, add to sweepVotes, and if enough
1186          * votes have accumulated, sweep.
1187          */
1188         if (pred != null && pred.next == s) {
1189             Node n = s.next;
1190             if (n == null ||
1191                 (n != s && pred.casNext(s, n) && pred.isMatched())) {
1192                 for (;;) {               // check if at, or could be, head
1193                     Node h = head;
1194                     if (h == pred || h == s)
1195                         return;          // at head or list empty
1196                     if (!h.isMatched())
1197                         break;
1198                     Node hn = h.next;
1199                     if (hn == null)
1200                         return;          // now empty
1201                     if (hn != h && casHead(h, hn))
1202                         h.selfLink();  // advance head
1203                 }
1204                 // sweep every SWEEP_THRESHOLD votes
1205                 if (pred.next != pred && s.next != s // recheck if offlist
1206                     && (incSweepVotes() & (SWEEP_THRESHOLD - 1)) == 0)
1207                     sweep();
1208             }
1209         }
1210     }
1211 
1212     /**
1213      * Unlinks matched (typically cancelled) nodes encountered in a
1214      * traversal from head.
1215      */
1216     private void sweep() {
1217         for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
1218             if (!s.isMatched())
1219                 // Unmatched nodes are never self-linked
1220                 p = s;
1221             else if ((n = s.next) == null) // trailing node is pinned
1222                 break;
1223             else if (s == n)    // stale
1224                 // No need to also check for p == s, since that implies s == n
1225                 p = head;
1226             else
1227                 p.casNext(s, n);
1228         }
1229     }
1230 
1231     /**
1232      * Creates an initially empty {@code LinkedTransferQueue}.
1233      */
1234     public LinkedTransferQueue() {
1235         head = tail = new Node();
1236     }
1237 
1238     /**
1239      * Creates a {@code LinkedTransferQueue}
1240      * initially containing the elements of the given collection,
1241      * added in traversal order of the collection's iterator.
1242      *
1243      * @param c the collection of elements to initially contain
1244      * @throws NullPointerException if the specified collection or any
1245      *         of its elements are null
1246      */
1247     public LinkedTransferQueue(Collection<? extends E> c) {
1248         Node h = null, t = null;
1249         for (E e : c) {
1250             Node newNode = new Node(Objects.requireNonNull(e));
1251             if (h == null)
1252                 h = t = newNode;
1253             else
1254                 t.appendRelaxed(t = newNode);
1255         }
1256         if (h == null)
1257             h = t = new Node();
1258         head = h;
1259         tail = t;
1260     }
1261 
1262     /**
1263      * Inserts the specified element at the tail of this queue.
1264      * As the queue is unbounded, this method will never block.
1265      *
1266      * @throws NullPointerException if the specified element is null
1267      */
1268     public void put(E e) {
1269         xfer(e, true, ASYNC, 0);
1270     }
1271 
1272     /**
1273      * Inserts the specified element at the tail of this queue.
1274      * As the queue is unbounded, this method will never block or
1275      * return {@code false}.
1276      *
1277      * @return {@code true} (as specified by
1278      *  {@link java.util.concurrent.BlockingQueue#offer(Object,long,TimeUnit)
1279      *  BlockingQueue.offer})
1280      * @throws NullPointerException if the specified element is null
1281      */
1282     public boolean offer(E e, long timeout, TimeUnit unit) {
1283         xfer(e, true, ASYNC, 0);
1284         return true;
1285     }
1286 
1287     /**
1288      * Inserts the specified element at the tail of this queue.
1289      * As the queue is unbounded, this method will never return {@code false}.
1290      *
1291      * @return {@code true} (as specified by {@link Queue#offer})
1292      * @throws NullPointerException if the specified element is null
1293      */
1294     public boolean offer(E e) {
1295         xfer(e, true, ASYNC, 0);
1296         return true;
1297     }
1298 
1299     /**
1300      * Inserts the specified element at the tail of this queue.
1301      * As the queue is unbounded, this method will never throw
1302      * {@link IllegalStateException} or return {@code false}.
1303      *
1304      * @return {@code true} (as specified by {@link Collection#add})
1305      * @throws NullPointerException if the specified element is null
1306      */
1307     public boolean add(E e) {
1308         xfer(e, true, ASYNC, 0);
1309         return true;
1310     }
1311 
1312     /**
1313      * Transfers the element to a waiting consumer immediately, if possible.
1314      *
1315      * <p>More precisely, transfers the specified element immediately
1316      * if there exists a consumer already waiting to receive it (in
1317      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1318      * otherwise returning {@code false} without enqueuing the element.
1319      *
1320      * @throws NullPointerException if the specified element is null
1321      */
1322     public boolean tryTransfer(E e) {
1323         return xfer(e, true, NOW, 0) == null;
1324     }
1325 
1326     /**
1327      * Transfers the element to a consumer, waiting if necessary to do so.
1328      *
1329      * <p>More precisely, transfers the specified element immediately
1330      * if there exists a consumer already waiting to receive it (in
1331      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1332      * else inserts the specified element at the tail of this queue
1333      * and waits until the element is received by a consumer.
1334      *
1335      * @throws NullPointerException if the specified element is null
1336      */
1337     public void transfer(E e) throws InterruptedException {
1338         if (xfer(e, true, SYNC, 0) != null) {
1339             Thread.interrupted(); // failure possible only due to interrupt
1340             throw new InterruptedException();
1341         }
1342     }
1343 
1344     /**
1345      * Transfers the element to a consumer if it is possible to do so
1346      * before the timeout elapses.
1347      *
1348      * <p>More precisely, transfers the specified element immediately
1349      * if there exists a consumer already waiting to receive it (in
1350      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1351      * else inserts the specified element at the tail of this queue
1352      * and waits until the element is received by a consumer,
1353      * returning {@code false} if the specified wait time elapses
1354      * before the element can be transferred.
1355      *
1356      * @throws NullPointerException if the specified element is null
1357      */
1358     public boolean tryTransfer(E e, long timeout, TimeUnit unit)
1359         throws InterruptedException {
1360         if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
1361             return true;
1362         if (!Thread.interrupted())
1363             return false;
1364         throw new InterruptedException();
1365     }
1366 
1367     public E take() throws InterruptedException {
1368         E e = xfer(null, false, SYNC, 0);
1369         if (e != null)
1370             return e;
1371         Thread.interrupted();
1372         throw new InterruptedException();
1373     }
1374 
1375     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
1376         E e = xfer(null, false, TIMED, unit.toNanos(timeout));
1377         if (e != null || !Thread.interrupted())
1378             return e;
1379         throw new InterruptedException();
1380     }
1381 
1382     public E poll() {
1383         return xfer(null, false, NOW, 0);
1384     }
1385 
1386     /**
1387      * @throws NullPointerException     {@inheritDoc}
1388      * @throws IllegalArgumentException {@inheritDoc}
1389      */
1390     public int drainTo(Collection<? super E> c) {
1391         Objects.requireNonNull(c);
1392         if (c == this)
1393             throw new IllegalArgumentException();
1394         int n = 0;
1395         for (E e; (e = poll()) != null; n++)
1396             c.add(e);
1397         return n;
1398     }
1399 
1400     /**
1401      * @throws NullPointerException     {@inheritDoc}
1402      * @throws IllegalArgumentException {@inheritDoc}
1403      */
1404     public int drainTo(Collection<? super E> c, int maxElements) {
1405         Objects.requireNonNull(c);
1406         if (c == this)
1407             throw new IllegalArgumentException();
1408         int n = 0;
1409         for (E e; n < maxElements && (e = poll()) != null; n++)
1410             c.add(e);
1411         return n;
1412     }
1413 
1414     /**
1415      * Returns an iterator over the elements in this queue in proper sequence.
1416      * The elements will be returned in order from first (head) to last (tail).
1417      *
1418      * <p>The returned iterator is
1419      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1420      *
1421      * @return an iterator over the elements in this queue in proper sequence
1422      */
1423     public Iterator<E> iterator() {
1424         return new Itr();
1425     }
1426 
1427     public E peek() {
1428         restartFromHead: for (;;) {
1429             for (Node p = head; p != null;) {
1430                 Object item = p.item;
1431                 if (p.isData) {
1432                     if (item != null) {
1433                         @SuppressWarnings("unchecked") E e = (E) item;
1434                         return e;
1435                     }
1436                 }
1437                 else if (item == null)
1438                     break;
1439                 if (p == (p = p.next))
1440                     continue restartFromHead;
1441             }
1442             return null;
1443         }
1444     }
1445 
1446     /**
1447      * Returns {@code true} if this queue contains no elements.
1448      *
1449      * @return {@code true} if this queue contains no elements
1450      */
1451     public boolean isEmpty() {
1452         return firstDataNode() == null;
1453     }
1454 
1455     public boolean hasWaitingConsumer() {
1456         restartFromHead: for (;;) {
1457             for (Node p = head; p != null;) {
1458                 Object item = p.item;
1459                 if (p.isData) {
1460                     if (item != null)
1461                         break;
1462                 }
1463                 else if (item == null)
1464                     return true;
1465                 if (p == (p = p.next))
1466                     continue restartFromHead;
1467             }
1468             return false;
1469         }
1470     }
1471 
1472     /**
1473      * Returns the number of elements in this queue.  If this queue
1474      * contains more than {@code Integer.MAX_VALUE} elements, returns
1475      * {@code Integer.MAX_VALUE}.
1476      *
1477      * <p>Beware that, unlike in most collections, this method is
1478      * <em>NOT</em> a constant-time operation. Because of the
1479      * asynchronous nature of these queues, determining the current
1480      * number of elements requires an O(n) traversal.
1481      *
1482      * @return the number of elements in this queue
1483      */
1484     public int size() {
1485         return countOfMode(true);
1486     }
1487 
1488     public int getWaitingConsumerCount() {
1489         return countOfMode(false);
1490     }
1491 
1492     /**
1493      * Removes a single instance of the specified element from this queue,
1494      * if it is present.  More formally, removes an element {@code e} such
1495      * that {@code o.equals(e)}, if this queue contains one or more such
1496      * elements.
1497      * Returns {@code true} if this queue contained the specified element
1498      * (or equivalently, if this queue changed as a result of the call).
1499      *
1500      * @param o element to be removed from this queue, if present
1501      * @return {@code true} if this queue changed as a result of the call
1502      */
1503     public boolean remove(Object o) {
1504         if (o == null) return false;
1505         restartFromHead: for (;;) {
1506             for (Node p = head, pred = null; p != null; ) {
1507                 Node q = p.next;
1508                 final Object item;
1509                 if ((item = p.item) != null) {
1510                     if (p.isData) {
1511                         if (o.equals(item) && p.tryMatch(item, null)) {
1512                             skipDeadNodes(pred, p, p, q);
1513                             return true;
1514                         }
1515                         pred = p; p = q; continue;
1516                     }
1517                 }
1518                 else if (!p.isData)
1519                     break;
1520                 for (Node c = p;; q = p.next) {
1521                     if (q == null || !q.isMatched()) {
1522                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1523                     }
1524                     if (p == (p = q)) continue restartFromHead;
1525                 }
1526             }
1527             return false;
1528         }
1529     }
1530 
1531     /**
1532      * Returns {@code true} if this queue contains the specified element.
1533      * More formally, returns {@code true} if and only if this queue contains
1534      * at least one element {@code e} such that {@code o.equals(e)}.
1535      *
1536      * @param o object to be checked for containment in this queue
1537      * @return {@code true} if this queue contains the specified element
1538      */
1539     public boolean contains(Object o) {
1540         if (o == null) return false;
1541         restartFromHead: for (;;) {
1542             for (Node p = head, pred = null; p != null; ) {
1543                 Node q = p.next;
1544                 final Object item;
1545                 if ((item = p.item) != null) {
1546                     if (p.isData) {
1547                         if (o.equals(item))
1548                             return true;
1549                         pred = p; p = q; continue;
1550                     }
1551                 }
1552                 else if (!p.isData)
1553                     break;
1554                 for (Node c = p;; q = p.next) {
1555                     if (q == null || !q.isMatched()) {
1556                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1557                     }
1558                     if (p == (p = q)) continue restartFromHead;
1559                 }
1560             }
1561             return false;
1562         }
1563     }
1564 
1565     /**
1566      * Always returns {@code Integer.MAX_VALUE} because a
1567      * {@code LinkedTransferQueue} is not capacity constrained.
1568      *
1569      * @return {@code Integer.MAX_VALUE} (as specified by
1570      *         {@link java.util.concurrent.BlockingQueue#remainingCapacity()
1571      *         BlockingQueue.remainingCapacity})
1572      */
1573     public int remainingCapacity() {
1574         return Integer.MAX_VALUE;
1575     }
1576 
1577     /**
1578      * Saves this queue to a stream (that is, serializes it).
1579      *
1580      * @param s the stream
1581      * @throws java.io.IOException if an I/O error occurs
1582      * @serialData All of the elements (each an {@code E}) in
1583      * the proper order, followed by a null
1584      */
1585     private void writeObject(java.io.ObjectOutputStream s)
1586         throws java.io.IOException {
1587         s.defaultWriteObject();
1588         for (E e : this)
1589             s.writeObject(e);
1590         // Use trailing null as sentinel
1591         s.writeObject(null);
1592     }
1593 
1594     /**
1595      * Reconstitutes this queue from a stream (that is, deserializes it).
1596      * @param s the stream
1597      * @throws ClassNotFoundException if the class of a serialized object
1598      *         could not be found
1599      * @throws java.io.IOException if an I/O error occurs
1600      */
1601     private void readObject(java.io.ObjectInputStream s)
1602         throws java.io.IOException, ClassNotFoundException {
1603 
1604         // Read in elements until trailing null sentinel found
1605         Node h = null, t = null;
1606         for (Object item; (item = s.readObject()) != null; ) {
1607             @SuppressWarnings("unchecked")
1608             Node newNode = new Node((E) item);
1609             if (h == null)
1610                 h = t = newNode;
1611             else
1612                 t.appendRelaxed(t = newNode);
1613         }
1614         if (h == null)
1615             h = t = new Node();
1616         head = h;
1617         tail = t;
1618     }
1619 
1620     /**
1621      * @throws NullPointerException {@inheritDoc}

1622      */
1623     public boolean removeIf(Predicate<? super E> filter) {
1624         Objects.requireNonNull(filter);
1625         return bulkRemove(filter);
1626     }
1627 
1628     /**
1629      * @throws NullPointerException {@inheritDoc}

1630      */
1631     public boolean removeAll(Collection<?> c) {
1632         Objects.requireNonNull(c);
1633         return bulkRemove(e -> c.contains(e));
1634     }
1635 
1636     /**
1637      * @throws NullPointerException {@inheritDoc}

1638      */
1639     public boolean retainAll(Collection<?> c) {
1640         Objects.requireNonNull(c);
1641         return bulkRemove(e -> !c.contains(e));
1642     }
1643 
1644     public void clear() {
1645         bulkRemove(e -> true);
1646     }
1647 
1648     /**
1649      * Tolerate this many consecutive dead nodes before CAS-collapsing.
1650      * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
1651      */
1652     private static final int MAX_HOPS = 8;
1653 
1654     /** Implementation of bulk remove methods. */
1655     @SuppressWarnings("unchecked")
1656     private boolean bulkRemove(Predicate<? super E> filter) {
1657         boolean removed = false;
1658         restartFromHead: for (;;) {
1659             int hops = MAX_HOPS;
1660             // c will be CASed to collapse intervening dead nodes between
1661             // pred (or head if null) and p.
1662             for (Node p = head, c = p, pred = null, q; p != null; p = q) {
1663                 q = p.next;
1664                 final Object item; boolean pAlive;
1665                 if (pAlive = ((item = p.item) != null && p.isData)) {
1666                     if (filter.test((E) item)) {
1667                         if (p.tryMatch(item, null))
1668                             removed = true;
1669                         pAlive = false;
1670                     }
1671                 }
1672                 else if (!p.isData && item == null)
1673                     break;
1674                 if (pAlive || q == null || --hops == 0) {
1675                     // p might already be self-linked here, but if so:
1676                     // - CASing head will surely fail
1677                     // - CASing pred's next will be useless but harmless.
1678                     if ((c != p && !tryCasSuccessor(pred, c, c = p))
1679                         || pAlive) {
1680                         // if CAS failed or alive, abandon old pred
1681                         hops = MAX_HOPS;
1682                         pred = p;
1683                         c = q;
1684                     }
1685                 } else if (p == q)
1686                     continue restartFromHead;
1687             }
1688             return removed;
1689         }
1690     }
1691 
1692     /**
1693      * Runs action on each element found during a traversal starting at p.
1694      * If p is null, the action is not run.
1695      */
1696     @SuppressWarnings("unchecked")
1697     void forEachFrom(Consumer<? super E> action, Node p) {
1698         for (Node pred = null; p != null; ) {
1699             Node q = p.next;
1700             final Object item;
1701             if ((item = p.item) != null) {
1702                 if (p.isData) {
1703                     action.accept((E) item);
1704                     pred = p; p = q; continue;
1705                 }
1706             }
1707             else if (!p.isData)
1708                 break;
1709             for (Node c = p;; q = p.next) {
1710                 if (q == null || !q.isMatched()) {
1711                     pred = skipDeadNodes(pred, c, p, q); p = q; break;
1712                 }
1713                 if (p == (p = q)) { pred = null; p = head; break; }
1714             }
1715         }
1716     }
1717 
1718     /**
1719      * @throws NullPointerException {@inheritDoc}

1720      */
1721     public void forEach(Consumer<? super E> action) {
1722         Objects.requireNonNull(action);
1723         forEachFrom(action, head);
1724     }
1725 
1726     // VarHandle mechanics
1727     private static final VarHandle HEAD;
1728     private static final VarHandle TAIL;
1729     private static final VarHandle SWEEPVOTES;
1730     static final VarHandle ITEM;
1731     static final VarHandle NEXT;
1732     static final VarHandle WAITER;
1733     static {
1734         try {
1735             MethodHandles.Lookup l = MethodHandles.lookup();
1736             HEAD = l.findVarHandle(LinkedTransferQueue.class, "head",
1737                                    Node.class);
1738             TAIL = l.findVarHandle(LinkedTransferQueue.class, "tail",
1739                                    Node.class);
1740             SWEEPVOTES = l.findVarHandle(LinkedTransferQueue.class, "sweepVotes",
1741                                          int.class);
1742             ITEM = l.findVarHandle(Node.class, "item", Object.class);
1743             NEXT = l.findVarHandle(Node.class, "next", Node.class);
1744             WAITER = l.findVarHandle(Node.class, "waiter", Thread.class);
1745         } catch (ReflectiveOperationException e) {
1746             throw new Error(e);
1747         }
1748 
1749         // Reduce the risk of rare disastrous classloading in first call to
1750         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1751         Class<?> ensureLoaded = LockSupport.class;
1752     }
1753 }
--- EOF ---