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      * @since 9
 893      */
 894     public Object[] toArray() {
 895         return toArrayInternal(null);
 896     }
 897 
 898     /**
 899      * Returns an array containing all of the elements in this queue, in
 900      * proper sequence; the runtime type of the returned array is that of
 901      * the specified array.  If the queue fits in the specified array, it
 902      * is returned therein.  Otherwise, a new array is allocated with the
 903      * runtime type of the specified array and the size of this queue.
 904      *
 905      * <p>If this queue fits in the specified array with room to spare
 906      * (i.e., the array has more elements than this queue), the element in
 907      * the array immediately following the end of the queue is set to
 908      * {@code null}.
 909      *
 910      * <p>Like the {@link #toArray()} method, this method acts as bridge between
 911      * array-based and collection-based APIs.  Further, this method allows
 912      * precise control over the runtime type of the output array, and may,
 913      * under certain circumstances, be used to save allocation costs.
 914      *
 915      * <p>Suppose {@code x} is a queue known to contain only strings.
 916      * The following code can be used to dump the queue into a newly
 917      * allocated array of {@code String}:
 918      *
 919      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
 920      *
 921      * Note that {@code toArray(new Object[0])} is identical in function to
 922      * {@code toArray()}.
 923      *
 924      * @param a the array into which the elements of the queue are to
 925      *          be stored, if it is big enough; otherwise, a new array of the
 926      *          same runtime type is allocated for this purpose
 927      * @return an array containing all of the elements in this queue
 928      * @throws ArrayStoreException if the runtime type of the specified array
 929      *         is not a supertype of the runtime type of every element in
 930      *         this queue
 931      * @throws NullPointerException if the specified array is null
 932      * @since 9
 933      */
 934     @SuppressWarnings("unchecked")
 935     public <T> T[] toArray(T[] a) {
 936         Objects.requireNonNull(a);
 937         return (T[]) toArrayInternal(a);
 938     }
 939 
 940     /**
 941      * Weakly-consistent iterator.
 942      *
 943      * Lazily updated ancestor is expected to be amortized O(1) remove(),
 944      * but O(n) in the worst case, when lastRet is concurrently deleted.
 945      */
 946     final class Itr implements Iterator<E> {
 947         private Node nextNode;   // next node to return item for
 948         private E nextItem;      // the corresponding item
 949         private Node lastRet;    // last returned node, to support remove
 950         private Node ancestor;   // Helps unlink lastRet on remove()
 951 
 952         /**
 953          * Moves to next node after pred, or first node if pred null.
 954          */
 955         @SuppressWarnings("unchecked")
 956         private void advance(Node pred) {
 957             for (Node p = (pred == null) ? head : pred.next, c = p;
 958                  p != null; ) {
 959                 final Object item;
 960                 if ((item = p.item) != null && p.isData) {
 961                     nextNode = p;
 962                     nextItem = (E) item;
 963                     if (c != p)
 964                         tryCasSuccessor(pred, c, p);
 965                     return;
 966                 }
 967                 else if (!p.isData && item == null)
 968                     break;
 969                 if (c != p && !tryCasSuccessor(pred, c, c = p)) {
 970                     pred = p;
 971                     c = p = p.next;
 972                 }
 973                 else if (p == (p = p.next)) {
 974                     pred = null;
 975                     c = p = head;
 976                 }
 977             }
 978             nextItem = null;
 979             nextNode = null;
 980         }
 981 
 982         Itr() {
 983             advance(null);
 984         }
 985 
 986         public final boolean hasNext() {
 987             return nextNode != null;
 988         }
 989 
 990         public final E next() {
 991             final Node p;
 992             if ((p = nextNode) == null) throw new NoSuchElementException();
 993             E e = nextItem;
 994             advance(lastRet = p);
 995             return e;
 996         }
 997 
 998         public void forEachRemaining(Consumer<? super E> action) {
 999             Objects.requireNonNull(action);
1000             Node q = null;
1001             for (Node p; (p = nextNode) != null; advance(q = p))
1002                 action.accept(nextItem);
1003             if (q != null)
1004                 lastRet = q;
1005         }
1006 
1007         public final void remove() {
1008             final Node lastRet = this.lastRet;
1009             if (lastRet == null)
1010                 throw new IllegalStateException();
1011             this.lastRet = null;
1012             if (lastRet.item == null)   // already deleted?
1013                 return;
1014             // Advance ancestor, collapsing intervening dead nodes
1015             Node pred = ancestor;
1016             for (Node p = (pred == null) ? head : pred.next, c = p, q;
1017                  p != null; ) {
1018                 if (p == lastRet) {
1019                     final Object item;
1020                     if ((item = p.item) != null)
1021                         p.tryMatch(item, null);
1022                     if ((q = p.next) == null) q = p;
1023                     if (c != q) tryCasSuccessor(pred, c, q);
1024                     ancestor = pred;
1025                     return;
1026                 }
1027                 final Object item; final boolean pAlive;
1028                 if (pAlive = ((item = p.item) != null && p.isData)) {
1029                     // exceptionally, nothing to do
1030                 }
1031                 else if (!p.isData && item == null)
1032                     break;
1033                 if ((c != p && !tryCasSuccessor(pred, c, c = p)) || pAlive) {
1034                     pred = p;
1035                     c = p = p.next;
1036                 }
1037                 else if (p == (p = p.next)) {
1038                     pred = null;
1039                     c = p = head;
1040                 }
1041             }
1042             // traversal failed to find lastRet; must have been deleted;
1043             // leave ancestor at original location to avoid overshoot;
1044             // better luck next time!
1045 
1046             // assert lastRet.isMatched();
1047         }
1048     }
1049 
1050     /** A customized variant of Spliterators.IteratorSpliterator */
1051     final class LTQSpliterator implements Spliterator<E> {
1052         static final int MAX_BATCH = 1 << 25;  // max batch array size;
1053         Node current;       // current node; null until initialized
1054         int batch;          // batch size for splits
1055         boolean exhausted;  // true when no more nodes
1056         LTQSpliterator() {}
1057 
1058         public Spliterator<E> trySplit() {
1059             Node p, q;
1060             if ((p = current()) == null || (q = p.next) == null)
1061                 return null;
1062             int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
1063             Object[] a = null;
1064             do {
1065                 final Object item = p.item;
1066                 if (p.isData) {
1067                     if (item != null) {
1068                         if (a == null)
1069                             a = new Object[n];
1070                         a[i++] = item;
1071                     }
1072                 } else if (item == null) {
1073                     p = null;
1074                     break;
1075                 }
1076                 if (p == (p = q))
1077                     p = firstDataNode();
1078             } while (p != null && (q = p.next) != null && i < n);
1079             setCurrent(p);
1080             return (i == 0) ? null :
1081                 Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
1082                                                    Spliterator.NONNULL |
1083                                                    Spliterator.CONCURRENT));
1084         }
1085 
1086         public void forEachRemaining(Consumer<? super E> action) {
1087             Objects.requireNonNull(action);
1088             final Node p;
1089             if ((p = current()) != null) {
1090                 current = null;
1091                 exhausted = true;
1092                 forEachFrom(action, p);
1093             }
1094         }
1095 
1096         @SuppressWarnings("unchecked")
1097         public boolean tryAdvance(Consumer<? super E> action) {
1098             Objects.requireNonNull(action);
1099             Node p;
1100             if ((p = current()) != null) {
1101                 E e = null;
1102                 do {
1103                     final Object item = p.item;
1104                     final boolean isData = p.isData;
1105                     if (p == (p = p.next))
1106                         p = head;
1107                     if (isData) {
1108                         if (item != null) {
1109                             e = (E) item;
1110                             break;
1111                         }
1112                     }
1113                     else if (item == null)
1114                         p = null;
1115                 } while (p != null);
1116                 setCurrent(p);
1117                 if (e != null) {
1118                     action.accept(e);
1119                     return true;
1120                 }
1121             }
1122             return false;
1123         }
1124 
1125         private void setCurrent(Node p) {
1126             if ((current = p) == null)
1127                 exhausted = true;
1128         }
1129 
1130         private Node current() {
1131             Node p;
1132             if ((p = current) == null && !exhausted)
1133                 setCurrent(p = firstDataNode());
1134             return p;
1135         }
1136 
1137         public long estimateSize() { return Long.MAX_VALUE; }
1138 
1139         public int characteristics() {
1140             return (Spliterator.ORDERED |
1141                     Spliterator.NONNULL |
1142                     Spliterator.CONCURRENT);
1143         }
1144     }
1145 
1146     /**
1147      * Returns a {@link Spliterator} over the elements in this queue.
1148      *
1149      * <p>The returned spliterator is
1150      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1151      *
1152      * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1153      * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1154      *
1155      * @implNote
1156      * The {@code Spliterator} implements {@code trySplit} to permit limited
1157      * parallelism.
1158      *
1159      * @return a {@code Spliterator} over the elements in this queue
1160      * @since 1.8
1161      */
1162     public Spliterator<E> spliterator() {
1163         return new LTQSpliterator();
1164     }
1165 
1166     /* -------------- Removal methods -------------- */
1167 
1168     /**
1169      * Unsplices (now or later) the given deleted/cancelled node with
1170      * the given predecessor.
1171      *
1172      * @param pred a node that was at one time known to be the
1173      * predecessor of s
1174      * @param s the node to be unspliced
1175      */
1176     final void unsplice(Node pred, Node s) {
1177         // assert pred != null;
1178         // assert pred != s;
1179         // assert s != null;
1180         // assert s.isMatched();
1181         // assert (SWEEP_THRESHOLD & (SWEEP_THRESHOLD - 1)) == 0;
1182         s.waiter = null; // disable signals
1183         /*
1184          * See above for rationale. Briefly: if pred still points to
1185          * s, try to unlink s.  If s cannot be unlinked, because it is
1186          * trailing node or pred might be unlinked, and neither pred
1187          * nor s are head or offlist, add to sweepVotes, and if enough
1188          * votes have accumulated, sweep.
1189          */
1190         if (pred != null && pred.next == s) {
1191             Node n = s.next;
1192             if (n == null ||
1193                 (n != s && pred.casNext(s, n) && pred.isMatched())) {
1194                 for (;;) {               // check if at, or could be, head
1195                     Node h = head;
1196                     if (h == pred || h == s)
1197                         return;          // at head or list empty
1198                     if (!h.isMatched())
1199                         break;
1200                     Node hn = h.next;
1201                     if (hn == null)
1202                         return;          // now empty
1203                     if (hn != h && casHead(h, hn))
1204                         h.selfLink();  // advance head
1205                 }
1206                 // sweep every SWEEP_THRESHOLD votes
1207                 if (pred.next != pred && s.next != s // recheck if offlist
1208                     && (incSweepVotes() & (SWEEP_THRESHOLD - 1)) == 0)
1209                     sweep();
1210             }
1211         }
1212     }
1213 
1214     /**
1215      * Unlinks matched (typically cancelled) nodes encountered in a
1216      * traversal from head.
1217      */
1218     private void sweep() {
1219         for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
1220             if (!s.isMatched())
1221                 // Unmatched nodes are never self-linked
1222                 p = s;
1223             else if ((n = s.next) == null) // trailing node is pinned
1224                 break;
1225             else if (s == n)    // stale
1226                 // No need to also check for p == s, since that implies s == n
1227                 p = head;
1228             else
1229                 p.casNext(s, n);
1230         }
1231     }
1232 
1233     /**
1234      * Creates an initially empty {@code LinkedTransferQueue}.
1235      */
1236     public LinkedTransferQueue() {
1237         head = tail = new Node();
1238     }
1239 
1240     /**
1241      * Creates a {@code LinkedTransferQueue}
1242      * initially containing the elements of the given collection,
1243      * added in traversal order of the collection's iterator.
1244      *
1245      * @param c the collection of elements to initially contain
1246      * @throws NullPointerException if the specified collection or any
1247      *         of its elements are null
1248      */
1249     public LinkedTransferQueue(Collection<? extends E> c) {
1250         Node h = null, t = null;
1251         for (E e : c) {
1252             Node newNode = new Node(Objects.requireNonNull(e));
1253             if (h == null)
1254                 h = t = newNode;
1255             else
1256                 t.appendRelaxed(t = newNode);
1257         }
1258         if (h == null)
1259             h = t = new Node();
1260         head = h;
1261         tail = t;
1262     }
1263 
1264     /**
1265      * Inserts the specified element at the tail of this queue.
1266      * As the queue is unbounded, this method will never block.
1267      *
1268      * @throws NullPointerException if the specified element is null
1269      */
1270     public void put(E e) {
1271         xfer(e, true, ASYNC, 0);
1272     }
1273 
1274     /**
1275      * Inserts the specified element at the tail of this queue.
1276      * As the queue is unbounded, this method will never block or
1277      * return {@code false}.
1278      *
1279      * @return {@code true} (as specified by
1280      *  {@link java.util.concurrent.BlockingQueue#offer(Object,long,TimeUnit)
1281      *  BlockingQueue.offer})
1282      * @throws NullPointerException if the specified element is null
1283      */
1284     public boolean offer(E e, long timeout, TimeUnit unit) {
1285         xfer(e, true, ASYNC, 0);
1286         return true;
1287     }
1288 
1289     /**
1290      * Inserts the specified element at the tail of this queue.
1291      * As the queue is unbounded, this method will never return {@code false}.
1292      *
1293      * @return {@code true} (as specified by {@link Queue#offer})
1294      * @throws NullPointerException if the specified element is null
1295      */
1296     public boolean offer(E e) {
1297         xfer(e, true, ASYNC, 0);
1298         return true;
1299     }
1300 
1301     /**
1302      * Inserts the specified element at the tail of this queue.
1303      * As the queue is unbounded, this method will never throw
1304      * {@link IllegalStateException} or return {@code false}.
1305      *
1306      * @return {@code true} (as specified by {@link Collection#add})
1307      * @throws NullPointerException if the specified element is null
1308      */
1309     public boolean add(E e) {
1310         xfer(e, true, ASYNC, 0);
1311         return true;
1312     }
1313 
1314     /**
1315      * Transfers the element to a waiting consumer immediately, if possible.
1316      *
1317      * <p>More precisely, transfers the specified element immediately
1318      * if there exists a consumer already waiting to receive it (in
1319      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1320      * otherwise returning {@code false} without enqueuing the element.
1321      *
1322      * @throws NullPointerException if the specified element is null
1323      */
1324     public boolean tryTransfer(E e) {
1325         return xfer(e, true, NOW, 0) == null;
1326     }
1327 
1328     /**
1329      * Transfers the element to a consumer, waiting if necessary to do so.
1330      *
1331      * <p>More precisely, transfers the specified element immediately
1332      * if there exists a consumer already waiting to receive it (in
1333      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1334      * else inserts the specified element at the tail of this queue
1335      * and waits until the element is received by a consumer.
1336      *
1337      * @throws NullPointerException if the specified element is null
1338      */
1339     public void transfer(E e) throws InterruptedException {
1340         if (xfer(e, true, SYNC, 0) != null) {
1341             Thread.interrupted(); // failure possible only due to interrupt
1342             throw new InterruptedException();
1343         }
1344     }
1345 
1346     /**
1347      * Transfers the element to a consumer if it is possible to do so
1348      * before the timeout elapses.
1349      *
1350      * <p>More precisely, transfers the specified element immediately
1351      * if there exists a consumer already waiting to receive it (in
1352      * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1353      * else inserts the specified element at the tail of this queue
1354      * and waits until the element is received by a consumer,
1355      * returning {@code false} if the specified wait time elapses
1356      * before the element can be transferred.
1357      *
1358      * @throws NullPointerException if the specified element is null
1359      */
1360     public boolean tryTransfer(E e, long timeout, TimeUnit unit)
1361         throws InterruptedException {
1362         if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
1363             return true;
1364         if (!Thread.interrupted())
1365             return false;
1366         throw new InterruptedException();
1367     }
1368 
1369     public E take() throws InterruptedException {
1370         E e = xfer(null, false, SYNC, 0);
1371         if (e != null)
1372             return e;
1373         Thread.interrupted();
1374         throw new InterruptedException();
1375     }
1376 
1377     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
1378         E e = xfer(null, false, TIMED, unit.toNanos(timeout));
1379         if (e != null || !Thread.interrupted())
1380             return e;
1381         throw new InterruptedException();
1382     }
1383 
1384     public E poll() {
1385         return xfer(null, false, NOW, 0);
1386     }
1387 
1388     /**
1389      * @throws NullPointerException     {@inheritDoc}
1390      * @throws IllegalArgumentException {@inheritDoc}
1391      */
1392     public int drainTo(Collection<? super E> c) {
1393         Objects.requireNonNull(c);
1394         if (c == this)
1395             throw new IllegalArgumentException();
1396         int n = 0;
1397         for (E e; (e = poll()) != null; n++)
1398             c.add(e);
1399         return n;
1400     }
1401 
1402     /**
1403      * @throws NullPointerException     {@inheritDoc}
1404      * @throws IllegalArgumentException {@inheritDoc}
1405      */
1406     public int drainTo(Collection<? super E> c, int maxElements) {
1407         Objects.requireNonNull(c);
1408         if (c == this)
1409             throw new IllegalArgumentException();
1410         int n = 0;
1411         for (E e; n < maxElements && (e = poll()) != null; n++)
1412             c.add(e);
1413         return n;
1414     }
1415 
1416     /**
1417      * Returns an iterator over the elements in this queue in proper sequence.
1418      * The elements will be returned in order from first (head) to last (tail).
1419      *
1420      * <p>The returned iterator is
1421      * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1422      *
1423      * @return an iterator over the elements in this queue in proper sequence
1424      */
1425     public Iterator<E> iterator() {
1426         return new Itr();
1427     }
1428 
1429     public E peek() {
1430         restartFromHead: for (;;) {
1431             for (Node p = head; p != null;) {
1432                 Object item = p.item;
1433                 if (p.isData) {
1434                     if (item != null) {
1435                         @SuppressWarnings("unchecked") E e = (E) item;
1436                         return e;
1437                     }
1438                 }
1439                 else if (item == null)
1440                     break;
1441                 if (p == (p = p.next))
1442                     continue restartFromHead;
1443             }
1444             return null;
1445         }
1446     }
1447 
1448     /**
1449      * Returns {@code true} if this queue contains no elements.
1450      *
1451      * @return {@code true} if this queue contains no elements
1452      */
1453     public boolean isEmpty() {
1454         return firstDataNode() == null;
1455     }
1456 
1457     public boolean hasWaitingConsumer() {
1458         restartFromHead: for (;;) {
1459             for (Node p = head; p != null;) {
1460                 Object item = p.item;
1461                 if (p.isData) {
1462                     if (item != null)
1463                         break;
1464                 }
1465                 else if (item == null)
1466                     return true;
1467                 if (p == (p = p.next))
1468                     continue restartFromHead;
1469             }
1470             return false;
1471         }
1472     }
1473 
1474     /**
1475      * Returns the number of elements in this queue.  If this queue
1476      * contains more than {@code Integer.MAX_VALUE} elements, returns
1477      * {@code Integer.MAX_VALUE}.
1478      *
1479      * <p>Beware that, unlike in most collections, this method is
1480      * <em>NOT</em> a constant-time operation. Because of the
1481      * asynchronous nature of these queues, determining the current
1482      * number of elements requires an O(n) traversal.
1483      *
1484      * @return the number of elements in this queue
1485      */
1486     public int size() {
1487         return countOfMode(true);
1488     }
1489 
1490     public int getWaitingConsumerCount() {
1491         return countOfMode(false);
1492     }
1493 
1494     /**
1495      * Removes a single instance of the specified element from this queue,
1496      * if it is present.  More formally, removes an element {@code e} such
1497      * that {@code o.equals(e)}, if this queue contains one or more such
1498      * elements.
1499      * Returns {@code true} if this queue contained the specified element
1500      * (or equivalently, if this queue changed as a result of the call).
1501      *
1502      * @param o element to be removed from this queue, if present
1503      * @return {@code true} if this queue changed as a result of the call
1504      */
1505     public boolean remove(Object o) {
1506         if (o == null) return false;
1507         restartFromHead: for (;;) {
1508             for (Node p = head, pred = null; p != null; ) {
1509                 Node q = p.next;
1510                 final Object item;
1511                 if ((item = p.item) != null) {
1512                     if (p.isData) {
1513                         if (o.equals(item) && p.tryMatch(item, null)) {
1514                             skipDeadNodes(pred, p, p, q);
1515                             return true;
1516                         }
1517                         pred = p; p = q; continue;
1518                     }
1519                 }
1520                 else if (!p.isData)
1521                     break;
1522                 for (Node c = p;; q = p.next) {
1523                     if (q == null || !q.isMatched()) {
1524                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1525                     }
1526                     if (p == (p = q)) continue restartFromHead;
1527                 }
1528             }
1529             return false;
1530         }
1531     }
1532 
1533     /**
1534      * Returns {@code true} if this queue contains the specified element.
1535      * More formally, returns {@code true} if and only if this queue contains
1536      * at least one element {@code e} such that {@code o.equals(e)}.
1537      *
1538      * @param o object to be checked for containment in this queue
1539      * @return {@code true} if this queue contains the specified element
1540      */
1541     public boolean contains(Object o) {
1542         if (o == null) return false;
1543         restartFromHead: for (;;) {
1544             for (Node p = head, pred = null; p != null; ) {
1545                 Node q = p.next;
1546                 final Object item;
1547                 if ((item = p.item) != null) {
1548                     if (p.isData) {
1549                         if (o.equals(item))
1550                             return true;
1551                         pred = p; p = q; continue;
1552                     }
1553                 }
1554                 else if (!p.isData)
1555                     break;
1556                 for (Node c = p;; q = p.next) {
1557                     if (q == null || !q.isMatched()) {
1558                         pred = skipDeadNodes(pred, c, p, q); p = q; break;
1559                     }
1560                     if (p == (p = q)) continue restartFromHead;
1561                 }
1562             }
1563             return false;
1564         }
1565     }
1566 
1567     /**
1568      * Always returns {@code Integer.MAX_VALUE} because a
1569      * {@code LinkedTransferQueue} is not capacity constrained.
1570      *
1571      * @return {@code Integer.MAX_VALUE} (as specified by
1572      *         {@link java.util.concurrent.BlockingQueue#remainingCapacity()
1573      *         BlockingQueue.remainingCapacity})
1574      */
1575     public int remainingCapacity() {
1576         return Integer.MAX_VALUE;
1577     }
1578 
1579     /**
1580      * Saves this queue to a stream (that is, serializes it).
1581      *
1582      * @param s the stream
1583      * @throws java.io.IOException if an I/O error occurs
1584      * @serialData All of the elements (each an {@code E}) in
1585      * the proper order, followed by a null
1586      */
1587     private void writeObject(java.io.ObjectOutputStream s)
1588         throws java.io.IOException {
1589         s.defaultWriteObject();
1590         for (E e : this)
1591             s.writeObject(e);
1592         // Use trailing null as sentinel
1593         s.writeObject(null);
1594     }
1595 
1596     /**
1597      * Reconstitutes this queue from a stream (that is, deserializes it).
1598      * @param s the stream
1599      * @throws ClassNotFoundException if the class of a serialized object
1600      *         could not be found
1601      * @throws java.io.IOException if an I/O error occurs
1602      */
1603     private void readObject(java.io.ObjectInputStream s)
1604         throws java.io.IOException, ClassNotFoundException {
1605 
1606         // Read in elements until trailing null sentinel found
1607         Node h = null, t = null;
1608         for (Object item; (item = s.readObject()) != null; ) {
1609             @SuppressWarnings("unchecked")
1610             Node newNode = new Node((E) item);
1611             if (h == null)
1612                 h = t = newNode;
1613             else
1614                 t.appendRelaxed(t = newNode);
1615         }
1616         if (h == null)
1617             h = t = new Node();
1618         head = h;
1619         tail = t;
1620     }
1621 
1622     /**
1623      * @throws NullPointerException {@inheritDoc}
1624      * @since 9
1625      */
1626     public boolean removeIf(Predicate<? super E> filter) {
1627         Objects.requireNonNull(filter);
1628         return bulkRemove(filter);
1629     }
1630 
1631     /**
1632      * @throws NullPointerException {@inheritDoc}
1633      * @since 9
1634      */
1635     public boolean removeAll(Collection<?> c) {
1636         Objects.requireNonNull(c);
1637         return bulkRemove(e -> c.contains(e));
1638     }
1639 
1640     /**
1641      * @throws NullPointerException {@inheritDoc}
1642      * @since 9
1643      */
1644     public boolean retainAll(Collection<?> c) {
1645         Objects.requireNonNull(c);
1646         return bulkRemove(e -> !c.contains(e));
1647     }
1648 
1649     public void clear() {
1650         bulkRemove(e -> true);
1651     }
1652 
1653     /**
1654      * Tolerate this many consecutive dead nodes before CAS-collapsing.
1655      * Amortized cost of clear() is (1 + 1/MAX_HOPS) CASes per element.
1656      */
1657     private static final int MAX_HOPS = 8;
1658 
1659     /** Implementation of bulk remove methods. */
1660     @SuppressWarnings("unchecked")
1661     private boolean bulkRemove(Predicate<? super E> filter) {
1662         boolean removed = false;
1663         restartFromHead: for (;;) {
1664             int hops = MAX_HOPS;
1665             // c will be CASed to collapse intervening dead nodes between
1666             // pred (or head if null) and p.
1667             for (Node p = head, c = p, pred = null, q; p != null; p = q) {
1668                 q = p.next;
1669                 final Object item; boolean pAlive;
1670                 if (pAlive = ((item = p.item) != null && p.isData)) {
1671                     if (filter.test((E) item)) {
1672                         if (p.tryMatch(item, null))
1673                             removed = true;
1674                         pAlive = false;
1675                     }
1676                 }
1677                 else if (!p.isData && item == null)
1678                     break;
1679                 if (pAlive || q == null || --hops == 0) {
1680                     // p might already be self-linked here, but if so:
1681                     // - CASing head will surely fail
1682                     // - CASing pred's next will be useless but harmless.
1683                     if ((c != p && !tryCasSuccessor(pred, c, c = p))
1684                         || pAlive) {
1685                         // if CAS failed or alive, abandon old pred
1686                         hops = MAX_HOPS;
1687                         pred = p;
1688                         c = q;
1689                     }
1690                 } else if (p == q)
1691                     continue restartFromHead;
1692             }
1693             return removed;
1694         }
1695     }
1696 
1697     /**
1698      * Runs action on each element found during a traversal starting at p.
1699      * If p is null, the action is not run.
1700      */
1701     @SuppressWarnings("unchecked")
1702     void forEachFrom(Consumer<? super E> action, Node p) {
1703         for (Node pred = null; p != null; ) {
1704             Node q = p.next;
1705             final Object item;
1706             if ((item = p.item) != null) {
1707                 if (p.isData) {
1708                     action.accept((E) item);
1709                     pred = p; p = q; continue;
1710                 }
1711             }
1712             else if (!p.isData)
1713                 break;
1714             for (Node c = p;; q = p.next) {
1715                 if (q == null || !q.isMatched()) {
1716                     pred = skipDeadNodes(pred, c, p, q); p = q; break;
1717                 }
1718                 if (p == (p = q)) { pred = null; p = head; break; }
1719             }
1720         }
1721     }
1722 
1723     /**
1724      * @throws NullPointerException {@inheritDoc}
1725      * @since 9
1726      */
1727     public void forEach(Consumer<? super E> action) {
1728         Objects.requireNonNull(action);
1729         forEachFrom(action, head);
1730     }
1731 
1732     // VarHandle mechanics
1733     private static final VarHandle HEAD;
1734     private static final VarHandle TAIL;
1735     private static final VarHandle SWEEPVOTES;
1736     static final VarHandle ITEM;
1737     static final VarHandle NEXT;
1738     static final VarHandle WAITER;
1739     static {
1740         try {
1741             MethodHandles.Lookup l = MethodHandles.lookup();
1742             HEAD = l.findVarHandle(LinkedTransferQueue.class, "head",
1743                                    Node.class);
1744             TAIL = l.findVarHandle(LinkedTransferQueue.class, "tail",
1745                                    Node.class);
1746             SWEEPVOTES = l.findVarHandle(LinkedTransferQueue.class, "sweepVotes",
1747                                          int.class);
1748             ITEM = l.findVarHandle(Node.class, "item", Object.class);
1749             NEXT = l.findVarHandle(Node.class, "next", Node.class);
1750             WAITER = l.findVarHandle(Node.class, "waiter", Thread.class);
1751         } catch (ReflectiveOperationException e) {
1752             throw new Error(e);
1753         }
1754 
1755         // Reduce the risk of rare disastrous classloading in first call to
1756         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1757         Class<?> ensureLoaded = LockSupport.class;
1758     }
1759 }
--- EOF ---