jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent; jaroslav@1890: jaroslav@1890: import java.util.AbstractQueue; jaroslav@1890: import java.util.Collection; jaroslav@1890: import java.util.Iterator; jaroslav@1890: import java.util.NoSuchElementException; jaroslav@1890: import java.util.Queue; jaroslav@1890: import java.util.concurrent.TimeUnit; jaroslav@1890: import java.util.concurrent.locks.LockSupport; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * An unbounded {@link TransferQueue} based on linked nodes. jaroslav@1890: * This queue orders elements FIFO (first-in-first-out) with respect jaroslav@1890: * to any given producer. The head of the queue is that jaroslav@1890: * element that has been on the queue the longest time for some jaroslav@1890: * producer. The tail of the queue is that element that has jaroslav@1890: * been on the queue the shortest time for some producer. jaroslav@1890: * jaroslav@1890: *

Beware that, unlike in most collections, the {@code size} method jaroslav@1890: * is NOT a constant-time operation. Because of the jaroslav@1890: * asynchronous nature of these queues, determining the current number jaroslav@1890: * of elements requires a traversal of the elements, and so may report jaroslav@1890: * inaccurate results if this collection is modified during traversal. jaroslav@1890: * Additionally, the bulk operations {@code addAll}, jaroslav@1890: * {@code removeAll}, {@code retainAll}, {@code containsAll}, jaroslav@1890: * {@code equals}, and {@code toArray} are not guaranteed jaroslav@1890: * to be performed atomically. For example, an iterator operating jaroslav@1890: * concurrently with an {@code addAll} operation might view only some jaroslav@1890: * of the added elements. jaroslav@1890: * jaroslav@1890: *

This class and its iterator implement all of the jaroslav@1890: * optional methods of the {@link Collection} and {@link jaroslav@1890: * Iterator} interfaces. jaroslav@1890: * jaroslav@1890: *

Memory consistency effects: As with other concurrent jaroslav@1890: * collections, actions in a thread prior to placing an object into a jaroslav@1890: * {@code LinkedTransferQueue} jaroslav@1890: * happen-before jaroslav@1890: * actions subsequent to the access or removal of that element from jaroslav@1890: * the {@code LinkedTransferQueue} in another thread. jaroslav@1890: * jaroslav@1890: *

This class is a member of the jaroslav@1890: * jaroslav@1890: * Java Collections Framework. jaroslav@1890: * jaroslav@1890: * @since 1.7 jaroslav@1890: * @author Doug Lea jaroslav@1890: * @param the type of elements held in this collection jaroslav@1890: */ jaroslav@1890: public class LinkedTransferQueue extends AbstractQueue jaroslav@1890: implements TransferQueue, java.io.Serializable { jaroslav@1890: private static final long serialVersionUID = -3223113410248163686L; jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * *** Overview of Dual Queues with Slack *** jaroslav@1890: * jaroslav@1890: * Dual Queues, introduced by Scherer and Scott jaroslav@1890: * (http://www.cs.rice.edu/~wns1/papers/2004-DISC-DDS.pdf) are jaroslav@1890: * (linked) queues in which nodes may represent either data or jaroslav@1890: * requests. When a thread tries to enqueue a data node, but jaroslav@1890: * encounters a request node, it instead "matches" and removes it; jaroslav@1890: * and vice versa for enqueuing requests. Blocking Dual Queues jaroslav@1890: * arrange that threads enqueuing unmatched requests block until jaroslav@1890: * other threads provide the match. Dual Synchronous Queues (see jaroslav@1890: * Scherer, Lea, & Scott jaroslav@1890: * http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf) jaroslav@1890: * additionally arrange that threads enqueuing unmatched data also jaroslav@1890: * block. Dual Transfer Queues support all of these modes, as jaroslav@1890: * dictated by callers. jaroslav@1890: * jaroslav@1890: * A FIFO dual queue may be implemented using a variation of the jaroslav@1890: * Michael & Scott (M&S) lock-free queue algorithm jaroslav@1890: * (http://www.cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf). jaroslav@1890: * It maintains two pointer fields, "head", pointing to a jaroslav@1890: * (matched) node that in turn points to the first actual jaroslav@1890: * (unmatched) queue node (or null if empty); and "tail" that jaroslav@1890: * points to the last node on the queue (or again null if jaroslav@1890: * empty). For example, here is a possible queue with four data jaroslav@1890: * elements: jaroslav@1890: * jaroslav@1890: * head tail jaroslav@1890: * | | jaroslav@1890: * v v jaroslav@1890: * M -> U -> U -> U -> U jaroslav@1890: * jaroslav@1890: * The M&S queue algorithm is known to be prone to scalability and jaroslav@1890: * overhead limitations when maintaining (via CAS) these head and jaroslav@1890: * tail pointers. This has led to the development of jaroslav@1890: * contention-reducing variants such as elimination arrays (see jaroslav@1890: * Moir et al http://portal.acm.org/citation.cfm?id=1074013) and jaroslav@1890: * optimistic back pointers (see Ladan-Mozes & Shavit jaroslav@1890: * http://people.csail.mit.edu/edya/publications/OptimisticFIFOQueue-journal.pdf). jaroslav@1890: * However, the nature of dual queues enables a simpler tactic for jaroslav@1890: * improving M&S-style implementations when dual-ness is needed. jaroslav@1890: * jaroslav@1890: * In a dual queue, each node must atomically maintain its match jaroslav@1890: * status. While there are other possible variants, we implement jaroslav@1890: * this here as: for a data-mode node, matching entails CASing an jaroslav@1890: * "item" field from a non-null data value to null upon match, and jaroslav@1890: * vice-versa for request nodes, CASing from null to a data jaroslav@1890: * value. (Note that the linearization properties of this style of jaroslav@1890: * queue are easy to verify -- elements are made available by jaroslav@1890: * linking, and unavailable by matching.) Compared to plain M&S jaroslav@1890: * queues, this property of dual queues requires one additional jaroslav@1890: * successful atomic operation per enq/deq pair. But it also jaroslav@1890: * enables lower cost variants of queue maintenance mechanics. (A jaroslav@1890: * variation of this idea applies even for non-dual queues that jaroslav@1890: * support deletion of interior elements, such as jaroslav@1890: * j.u.c.ConcurrentLinkedQueue.) jaroslav@1890: * jaroslav@1890: * Once a node is matched, its match status can never again jaroslav@1890: * change. We may thus arrange that the linked list of them jaroslav@1890: * contain a prefix of zero or more matched nodes, followed by a jaroslav@1890: * suffix of zero or more unmatched nodes. (Note that we allow jaroslav@1890: * both the prefix and suffix to be zero length, which in turn jaroslav@1890: * means that we do not use a dummy header.) If we were not jaroslav@1890: * concerned with either time or space efficiency, we could jaroslav@1890: * correctly perform enqueue and dequeue operations by traversing jaroslav@1890: * from a pointer to the initial node; CASing the item of the jaroslav@1890: * first unmatched node on match and CASing the next field of the jaroslav@1890: * trailing node on appends. (Plus some special-casing when jaroslav@1890: * initially empty). While this would be a terrible idea in jaroslav@1890: * itself, it does have the benefit of not requiring ANY atomic jaroslav@1890: * updates on head/tail fields. jaroslav@1890: * jaroslav@1890: * We introduce here an approach that lies between the extremes of jaroslav@1890: * never versus always updating queue (head and tail) pointers. jaroslav@1890: * This offers a tradeoff between sometimes requiring extra jaroslav@1890: * traversal steps to locate the first and/or last unmatched jaroslav@1890: * nodes, versus the reduced overhead and contention of fewer jaroslav@1890: * updates to queue pointers. For example, a possible snapshot of jaroslav@1890: * a queue is: jaroslav@1890: * jaroslav@1890: * head tail jaroslav@1890: * | | jaroslav@1890: * v v jaroslav@1890: * M -> M -> U -> U -> U -> U jaroslav@1890: * jaroslav@1890: * The best value for this "slack" (the targeted maximum distance jaroslav@1890: * between the value of "head" and the first unmatched node, and jaroslav@1890: * similarly for "tail") is an empirical matter. We have found jaroslav@1890: * that using very small constants in the range of 1-3 work best jaroslav@1890: * over a range of platforms. Larger values introduce increasing jaroslav@1890: * costs of cache misses and risks of long traversal chains, while jaroslav@1890: * smaller values increase CAS contention and overhead. jaroslav@1890: * jaroslav@1890: * Dual queues with slack differ from plain M&S dual queues by jaroslav@1890: * virtue of only sometimes updating head or tail pointers when jaroslav@1890: * matching, appending, or even traversing nodes; in order to jaroslav@1890: * maintain a targeted slack. The idea of "sometimes" may be jaroslav@1890: * operationalized in several ways. The simplest is to use a jaroslav@1890: * per-operation counter incremented on each traversal step, and jaroslav@1890: * to try (via CAS) to update the associated queue pointer jaroslav@1890: * whenever the count exceeds a threshold. Another, that requires jaroslav@1890: * more overhead, is to use random number generators to update jaroslav@1890: * with a given probability per traversal step. jaroslav@1890: * jaroslav@1890: * In any strategy along these lines, because CASes updating jaroslav@1890: * fields may fail, the actual slack may exceed targeted jaroslav@1890: * slack. However, they may be retried at any time to maintain jaroslav@1890: * targets. Even when using very small slack values, this jaroslav@1890: * approach works well for dual queues because it allows all jaroslav@1890: * operations up to the point of matching or appending an item jaroslav@1890: * (hence potentially allowing progress by another thread) to be jaroslav@1890: * read-only, thus not introducing any further contention. As jaroslav@1890: * described below, we implement this by performing slack jaroslav@1890: * maintenance retries only after these points. jaroslav@1890: * jaroslav@1890: * As an accompaniment to such techniques, traversal overhead can jaroslav@1890: * be further reduced without increasing contention of head jaroslav@1890: * pointer updates: Threads may sometimes shortcut the "next" link jaroslav@1890: * path from the current "head" node to be closer to the currently jaroslav@1890: * known first unmatched node, and similarly for tail. Again, this jaroslav@1890: * may be triggered with using thresholds or randomization. jaroslav@1890: * jaroslav@1890: * These ideas must be further extended to avoid unbounded amounts jaroslav@1890: * of costly-to-reclaim garbage caused by the sequential "next" jaroslav@1890: * links of nodes starting at old forgotten head nodes: As first jaroslav@1890: * described in detail by Boehm jaroslav@1890: * (http://portal.acm.org/citation.cfm?doid=503272.503282) if a GC jaroslav@1890: * delays noticing that any arbitrarily old node has become jaroslav@1890: * garbage, all newer dead nodes will also be unreclaimed. jaroslav@1890: * (Similar issues arise in non-GC environments.) To cope with jaroslav@1890: * this in our implementation, upon CASing to advance the head jaroslav@1890: * pointer, we set the "next" link of the previous head to point jaroslav@1890: * only to itself; thus limiting the length of connected dead lists. jaroslav@1890: * (We also take similar care to wipe out possibly garbage jaroslav@1890: * retaining values held in other Node fields.) However, doing so jaroslav@1890: * adds some further complexity to traversal: If any "next" jaroslav@1890: * pointer links to itself, it indicates that the current thread jaroslav@1890: * has lagged behind a head-update, and so the traversal must jaroslav@1890: * continue from the "head". Traversals trying to find the jaroslav@1890: * current tail starting from "tail" may also encounter jaroslav@1890: * self-links, in which case they also continue at "head". jaroslav@1890: * jaroslav@1890: * It is tempting in slack-based scheme to not even use CAS for jaroslav@1890: * updates (similarly to Ladan-Mozes & Shavit). However, this jaroslav@1890: * cannot be done for head updates under the above link-forgetting jaroslav@1890: * mechanics because an update may leave head at a detached node. jaroslav@1890: * And while direct writes are possible for tail updates, they jaroslav@1890: * increase the risk of long retraversals, and hence long garbage jaroslav@1890: * chains, which can be much more costly than is worthwhile jaroslav@1890: * considering that the cost difference of performing a CAS vs jaroslav@1890: * write is smaller when they are not triggered on each operation jaroslav@1890: * (especially considering that writes and CASes equally require jaroslav@1890: * additional GC bookkeeping ("write barriers") that are sometimes jaroslav@1890: * more costly than the writes themselves because of contention). jaroslav@1890: * jaroslav@1890: * *** Overview of implementation *** jaroslav@1890: * jaroslav@1890: * We use a threshold-based approach to updates, with a slack jaroslav@1890: * threshold of two -- that is, we update head/tail when the jaroslav@1890: * current pointer appears to be two or more steps away from the jaroslav@1890: * first/last node. The slack value is hard-wired: a path greater jaroslav@1890: * than one is naturally implemented by checking equality of jaroslav@1890: * traversal pointers except when the list has only one element, jaroslav@1890: * in which case we keep slack threshold at one. Avoiding tracking jaroslav@1890: * explicit counts across method calls slightly simplifies an jaroslav@1890: * already-messy implementation. Using randomization would jaroslav@1890: * probably work better if there were a low-quality dirt-cheap jaroslav@1890: * per-thread one available, but even ThreadLocalRandom is too jaroslav@1890: * heavy for these purposes. jaroslav@1890: * jaroslav@1890: * With such a small slack threshold value, it is not worthwhile jaroslav@1890: * to augment this with path short-circuiting (i.e., unsplicing jaroslav@1890: * interior nodes) except in the case of cancellation/removal (see jaroslav@1890: * below). jaroslav@1890: * jaroslav@1890: * We allow both the head and tail fields to be null before any jaroslav@1890: * nodes are enqueued; initializing upon first append. This jaroslav@1890: * simplifies some other logic, as well as providing more jaroslav@1890: * efficient explicit control paths instead of letting JVMs insert jaroslav@1890: * implicit NullPointerExceptions when they are null. While not jaroslav@1890: * currently fully implemented, we also leave open the possibility jaroslav@1890: * of re-nulling these fields when empty (which is complicated to jaroslav@1890: * arrange, for little benefit.) jaroslav@1890: * jaroslav@1890: * All enqueue/dequeue operations are handled by the single method jaroslav@1890: * "xfer" with parameters indicating whether to act as some form jaroslav@1890: * of offer, put, poll, take, or transfer (each possibly with jaroslav@1890: * timeout). The relative complexity of using one monolithic jaroslav@1890: * method outweighs the code bulk and maintenance problems of jaroslav@1890: * using separate methods for each case. jaroslav@1890: * jaroslav@1890: * Operation consists of up to three phases. The first is jaroslav@1890: * implemented within method xfer, the second in tryAppend, and jaroslav@1890: * the third in method awaitMatch. jaroslav@1890: * jaroslav@1890: * 1. Try to match an existing node jaroslav@1890: * jaroslav@1890: * Starting at head, skip already-matched nodes until finding jaroslav@1890: * an unmatched node of opposite mode, if one exists, in which jaroslav@1890: * case matching it and returning, also if necessary updating jaroslav@1890: * head to one past the matched node (or the node itself if the jaroslav@1890: * list has no other unmatched nodes). If the CAS misses, then jaroslav@1890: * a loop retries advancing head by two steps until either jaroslav@1890: * success or the slack is at most two. By requiring that each jaroslav@1890: * attempt advances head by two (if applicable), we ensure that jaroslav@1890: * the slack does not grow without bound. Traversals also check jaroslav@1890: * if the initial head is now off-list, in which case they jaroslav@1890: * start at the new head. jaroslav@1890: * jaroslav@1890: * If no candidates are found and the call was untimed jaroslav@1890: * poll/offer, (argument "how" is NOW) return. jaroslav@1890: * jaroslav@1890: * 2. Try to append a new node (method tryAppend) jaroslav@1890: * jaroslav@1890: * Starting at current tail pointer, find the actual last node jaroslav@1890: * and try to append a new node (or if head was null, establish jaroslav@1890: * the first node). Nodes can be appended only if their jaroslav@1890: * predecessors are either already matched or are of the same jaroslav@1890: * mode. If we detect otherwise, then a new node with opposite jaroslav@1890: * mode must have been appended during traversal, so we must jaroslav@1890: * restart at phase 1. The traversal and update steps are jaroslav@1890: * otherwise similar to phase 1: Retrying upon CAS misses and jaroslav@1890: * checking for staleness. In particular, if a self-link is jaroslav@1890: * encountered, then we can safely jump to a node on the list jaroslav@1890: * by continuing the traversal at current head. jaroslav@1890: * jaroslav@1890: * On successful append, if the call was ASYNC, return. jaroslav@1890: * jaroslav@1890: * 3. Await match or cancellation (method awaitMatch) jaroslav@1890: * jaroslav@1890: * Wait for another thread to match node; instead cancelling if jaroslav@1890: * the current thread was interrupted or the wait timed out. On jaroslav@1890: * multiprocessors, we use front-of-queue spinning: If a node jaroslav@1890: * appears to be the first unmatched node in the queue, it jaroslav@1890: * spins a bit before blocking. In either case, before blocking jaroslav@1890: * it tries to unsplice any nodes between the current "head" jaroslav@1890: * and the first unmatched node. jaroslav@1890: * jaroslav@1890: * Front-of-queue spinning vastly improves performance of jaroslav@1890: * heavily contended queues. And so long as it is relatively jaroslav@1890: * brief and "quiet", spinning does not much impact performance jaroslav@1890: * of less-contended queues. During spins threads check their jaroslav@1890: * interrupt status and generate a thread-local random number jaroslav@1890: * to decide to occasionally perform a Thread.yield. While jaroslav@1890: * yield has underdefined specs, we assume that might it help, jaroslav@1890: * and will not hurt in limiting impact of spinning on busy jaroslav@1890: * systems. We also use smaller (1/2) spins for nodes that are jaroslav@1890: * not known to be front but whose predecessors have not jaroslav@1890: * blocked -- these "chained" spins avoid artifacts of jaroslav@1890: * front-of-queue rules which otherwise lead to alternating jaroslav@1890: * nodes spinning vs blocking. Further, front threads that jaroslav@1890: * represent phase changes (from data to request node or vice jaroslav@1890: * versa) compared to their predecessors receive additional jaroslav@1890: * chained spins, reflecting longer paths typically required to jaroslav@1890: * unblock threads during phase changes. jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * ** Unlinking removed interior nodes ** jaroslav@1890: * jaroslav@1890: * In addition to minimizing garbage retention via self-linking jaroslav@1890: * described above, we also unlink removed interior nodes. These jaroslav@1890: * may arise due to timed out or interrupted waits, or calls to jaroslav@1890: * remove(x) or Iterator.remove. Normally, given a node that was jaroslav@1890: * at one time known to be the predecessor of some node s that is jaroslav@1890: * to be removed, we can unsplice s by CASing the next field of jaroslav@1890: * its predecessor if it still points to s (otherwise s must jaroslav@1890: * already have been removed or is now offlist). But there are two jaroslav@1890: * situations in which we cannot guarantee to make node s jaroslav@1890: * unreachable in this way: (1) If s is the trailing node of list jaroslav@1890: * (i.e., with null next), then it is pinned as the target node jaroslav@1890: * for appends, so can only be removed later after other nodes are jaroslav@1890: * appended. (2) We cannot necessarily unlink s given a jaroslav@1890: * predecessor node that is matched (including the case of being jaroslav@1890: * cancelled): the predecessor may already be unspliced, in which jaroslav@1890: * case some previous reachable node may still point to s. jaroslav@1890: * (For further explanation see Herlihy & Shavit "The Art of jaroslav@1890: * Multiprocessor Programming" chapter 9). Although, in both jaroslav@1890: * cases, we can rule out the need for further action if either s jaroslav@1890: * or its predecessor are (or can be made to be) at, or fall off jaroslav@1890: * from, the head of list. jaroslav@1890: * jaroslav@1890: * Without taking these into account, it would be possible for an jaroslav@1890: * unbounded number of supposedly removed nodes to remain jaroslav@1890: * reachable. Situations leading to such buildup are uncommon but jaroslav@1890: * can occur in practice; for example when a series of short timed jaroslav@1890: * calls to poll repeatedly time out but never otherwise fall off jaroslav@1890: * the list because of an untimed call to take at the front of the jaroslav@1890: * queue. jaroslav@1890: * jaroslav@1890: * When these cases arise, rather than always retraversing the jaroslav@1890: * entire list to find an actual predecessor to unlink (which jaroslav@1890: * won't help for case (1) anyway), we record a conservative jaroslav@1890: * estimate of possible unsplice failures (in "sweepVotes"). jaroslav@1890: * We trigger a full sweep when the estimate exceeds a threshold jaroslav@1890: * ("SWEEP_THRESHOLD") indicating the maximum number of estimated jaroslav@1890: * removal failures to tolerate before sweeping through, unlinking jaroslav@1890: * cancelled nodes that were not unlinked upon initial removal. jaroslav@1890: * We perform sweeps by the thread hitting threshold (rather than jaroslav@1890: * background threads or by spreading work to other threads) jaroslav@1890: * because in the main contexts in which removal occurs, the jaroslav@1890: * caller is already timed-out, cancelled, or performing a jaroslav@1890: * potentially O(n) operation (e.g. remove(x)), none of which are jaroslav@1890: * time-critical enough to warrant the overhead that alternatives jaroslav@1890: * would impose on other threads. jaroslav@1890: * jaroslav@1890: * Because the sweepVotes estimate is conservative, and because jaroslav@1890: * nodes become unlinked "naturally" as they fall off the head of jaroslav@1890: * the queue, and because we allow votes to accumulate even while jaroslav@1890: * sweeps are in progress, there are typically significantly fewer jaroslav@1890: * such nodes than estimated. Choice of a threshold value jaroslav@1890: * balances the likelihood of wasted effort and contention, versus jaroslav@1890: * providing a worst-case bound on retention of interior nodes in jaroslav@1890: * quiescent queues. The value defined below was chosen jaroslav@1890: * empirically to balance these under various timeout scenarios. jaroslav@1890: * jaroslav@1890: * Note that we cannot self-link unlinked interior nodes during jaroslav@1890: * sweeps. However, the associated garbage chains terminate when jaroslav@1890: * some successor ultimately falls off the head of the list and is jaroslav@1890: * self-linked. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /** True if on multiprocessor */ jaroslav@1890: private static final boolean MP = jaroslav@1890: Runtime.getRuntime().availableProcessors() > 1; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of times to spin (with randomly interspersed calls jaroslav@1890: * to Thread.yield) on multiprocessor before blocking when a node jaroslav@1890: * is apparently the first waiter in the queue. See above for jaroslav@1890: * explanation. Must be a power of two. The value is empirically jaroslav@1890: * derived -- it works pretty well across a variety of processors, jaroslav@1890: * numbers of CPUs, and OSes. jaroslav@1890: */ jaroslav@1890: private static final int FRONT_SPINS = 1 << 7; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of times to spin before blocking when a node is jaroslav@1890: * preceded by another node that is apparently spinning. Also jaroslav@1890: * serves as an increment to FRONT_SPINS on phase changes, and as jaroslav@1890: * base average frequency for yielding during spins. Must be a jaroslav@1890: * power of two. jaroslav@1890: */ jaroslav@1890: private static final int CHAINED_SPINS = FRONT_SPINS >>> 1; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The maximum number of estimated removal failures (sweepVotes) jaroslav@1890: * to tolerate before sweeping through the queue unlinking jaroslav@1890: * cancelled nodes that were not unlinked upon initial jaroslav@1890: * removal. See above for explanation. The value must be at least jaroslav@1890: * two to avoid useless sweeps when removing trailing nodes. jaroslav@1890: */ jaroslav@1890: static final int SWEEP_THRESHOLD = 32; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queue nodes. Uses Object, not E, for items to allow forgetting jaroslav@1890: * them after use. Relies heavily on Unsafe mechanics to minimize jaroslav@1890: * unnecessary ordering constraints: Writes that are intrinsically jaroslav@1890: * ordered wrt other accesses or CASes use simple relaxed forms. jaroslav@1890: */ jaroslav@1890: static final class Node { jaroslav@1890: final boolean isData; // false if this is a request node jaroslav@1890: volatile Object item; // initially non-null if isData; CASed to match jaroslav@1890: volatile Node next; jaroslav@1890: volatile Thread waiter; // null until waiting jaroslav@1890: jaroslav@1890: // CAS methods for fields jaroslav@1890: final boolean casNext(Node cmp, Node val) { jaroslav@1890: return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); jaroslav@1890: } jaroslav@1890: jaroslav@1890: final boolean casItem(Object cmp, Object val) { jaroslav@1890: // assert cmp == null || cmp.getClass() != Node.class; jaroslav@1890: return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Constructs a new node. Uses relaxed write because item can jaroslav@1890: * only be seen after publication via casNext. jaroslav@1890: */ jaroslav@1890: Node(Object item, boolean isData) { jaroslav@1890: UNSAFE.putObject(this, itemOffset, item); // relaxed write jaroslav@1890: this.isData = isData; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Links node to itself to avoid garbage retention. Called jaroslav@1890: * only after CASing head field, so uses relaxed write. jaroslav@1890: */ jaroslav@1890: final void forgetNext() { jaroslav@1890: UNSAFE.putObject(this, nextOffset, this); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Sets item to self and waiter to null, to avoid garbage jaroslav@1890: * retention after matching or cancelling. Uses relaxed writes jaroslav@1890: * because order is already constrained in the only calling jaroslav@1890: * contexts: item is forgotten only after volatile/atomic jaroslav@1890: * mechanics that extract items. Similarly, clearing waiter jaroslav@1890: * follows either CAS or return from park (if ever parked; jaroslav@1890: * else we don't care). jaroslav@1890: */ jaroslav@1890: final void forgetContents() { jaroslav@1890: UNSAFE.putObject(this, itemOffset, this); jaroslav@1890: UNSAFE.putObject(this, waiterOffset, null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if this node has been matched, including the jaroslav@1890: * case of artificial matches due to cancellation. jaroslav@1890: */ jaroslav@1890: final boolean isMatched() { jaroslav@1890: Object x = item; jaroslav@1890: return (x == this) || ((x == null) == isData); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if this is an unmatched request node. jaroslav@1890: */ jaroslav@1890: final boolean isUnmatchedRequest() { jaroslav@1890: return !isData && item == null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if a node with the given mode cannot be jaroslav@1890: * appended to this node because this node is unmatched and jaroslav@1890: * has opposite data mode. jaroslav@1890: */ jaroslav@1890: final boolean cannotPrecede(boolean haveData) { jaroslav@1890: boolean d = isData; jaroslav@1890: Object x; jaroslav@1890: return d != haveData && (x = item) != this && (x != null) == d; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to artificially match a data node -- used by remove. jaroslav@1890: */ jaroslav@1890: final boolean tryMatchData() { jaroslav@1890: // assert isData; jaroslav@1890: Object x = item; jaroslav@1890: if (x != null && x != this && casItem(x, null)) { jaroslav@1890: LockSupport.unpark(waiter); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: private static final long serialVersionUID = -3375979862319811754L; jaroslav@1890: jaroslav@1890: // Unsafe mechanics jaroslav@1890: private static final sun.misc.Unsafe UNSAFE; jaroslav@1890: private static final long itemOffset; jaroslav@1890: private static final long nextOffset; jaroslav@1890: private static final long waiterOffset; jaroslav@1890: static { jaroslav@1890: try { jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe(); jaroslav@1890: Class k = Node.class; jaroslav@1890: itemOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("item")); jaroslav@1890: nextOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("next")); jaroslav@1890: waiterOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("waiter")); jaroslav@1890: } catch (Exception e) { jaroslav@1890: throw new Error(e); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** head of the queue; null until first enqueue */ jaroslav@1890: transient volatile Node head; jaroslav@1890: jaroslav@1890: /** tail of the queue; null until first append */ jaroslav@1890: private transient volatile Node tail; jaroslav@1890: jaroslav@1890: /** The number of apparent failures to unsplice removed nodes */ jaroslav@1890: private transient volatile int sweepVotes; jaroslav@1890: jaroslav@1890: // CAS methods for fields jaroslav@1890: private boolean casTail(Node cmp, Node val) { jaroslav@1890: return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); jaroslav@1890: } jaroslav@1890: jaroslav@1890: private boolean casHead(Node cmp, Node val) { jaroslav@1890: return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); jaroslav@1890: } jaroslav@1890: jaroslav@1890: private boolean casSweepVotes(int cmp, int val) { jaroslav@1890: return UNSAFE.compareAndSwapInt(this, sweepVotesOffset, cmp, val); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * Possible values for "how" argument in xfer method. jaroslav@1890: */ jaroslav@1890: private static final int NOW = 0; // for untimed poll, tryTransfer jaroslav@1890: private static final int ASYNC = 1; // for offer, put, add jaroslav@1890: private static final int SYNC = 2; // for transfer, take jaroslav@1890: private static final int TIMED = 3; // for timed poll, tryTransfer jaroslav@1890: jaroslav@1890: @SuppressWarnings("unchecked") jaroslav@1890: static E cast(Object item) { jaroslav@1890: // assert item == null || item.getClass() != Node.class; jaroslav@1890: return (E) item; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Implements all queuing methods. See above for explanation. jaroslav@1890: * jaroslav@1890: * @param e the item or null for take jaroslav@1890: * @param haveData true if this is a put, else a take jaroslav@1890: * @param how NOW, ASYNC, SYNC, or TIMED jaroslav@1890: * @param nanos timeout in nanosecs, used only if mode is TIMED jaroslav@1890: * @return an item if matched, else e jaroslav@1890: * @throws NullPointerException if haveData mode but e is null jaroslav@1890: */ jaroslav@1890: private E xfer(E e, boolean haveData, int how, long nanos) { jaroslav@1890: if (haveData && (e == null)) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: Node s = null; // the node to append, if needed jaroslav@1890: jaroslav@1890: retry: jaroslav@1890: for (;;) { // restart on append race jaroslav@1890: jaroslav@1890: for (Node h = head, p = h; p != null;) { // find & match first node jaroslav@1890: boolean isData = p.isData; jaroslav@1890: Object item = p.item; jaroslav@1890: if (item != p && (item != null) == isData) { // unmatched jaroslav@1890: if (isData == haveData) // can't match jaroslav@1890: break; jaroslav@1890: if (p.casItem(item, e)) { // match jaroslav@1890: for (Node q = p; q != h;) { jaroslav@1890: Node n = q.next; // update by 2 unless singleton jaroslav@1890: if (head == h && casHead(h, n == null ? q : n)) { jaroslav@1890: h.forgetNext(); jaroslav@1890: break; jaroslav@1890: } // advance and retry jaroslav@1890: if ((h = head) == null || jaroslav@1890: (q = h.next) == null || !q.isMatched()) jaroslav@1890: break; // unless slack < 2 jaroslav@1890: } jaroslav@1890: LockSupport.unpark(p.waiter); jaroslav@1890: return this.cast(item); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: Node n = p.next; jaroslav@1890: p = (p != n) ? n : (h = head); // Use head if p offlist jaroslav@1890: } jaroslav@1890: jaroslav@1890: if (how != NOW) { // No matches available jaroslav@1890: if (s == null) jaroslav@1890: s = new Node(e, haveData); jaroslav@1890: Node pred = tryAppend(s, haveData); jaroslav@1890: if (pred == null) jaroslav@1890: continue retry; // lost race vs opposite mode jaroslav@1890: if (how != ASYNC) jaroslav@1890: return awaitMatch(s, pred, e, (how == TIMED), nanos); jaroslav@1890: } jaroslav@1890: return e; // not waiting jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to append node s as tail. jaroslav@1890: * jaroslav@1890: * @param s the node to append jaroslav@1890: * @param haveData true if appending in data mode jaroslav@1890: * @return null on failure due to losing race with append in jaroslav@1890: * different mode, else s's predecessor, or s itself if no jaroslav@1890: * predecessor jaroslav@1890: */ jaroslav@1890: private Node tryAppend(Node s, boolean haveData) { jaroslav@1890: for (Node t = tail, p = t;;) { // move p to last node and append jaroslav@1890: Node n, u; // temps for reads of next & tail jaroslav@1890: if (p == null && (p = head) == null) { jaroslav@1890: if (casHead(null, s)) jaroslav@1890: return s; // initialize jaroslav@1890: } jaroslav@1890: else if (p.cannotPrecede(haveData)) jaroslav@1890: return null; // lost race vs opposite mode jaroslav@1890: else if ((n = p.next) != null) // not last; keep traversing jaroslav@1890: p = p != t && t != (u = tail) ? (t = u) : // stale tail jaroslav@1890: (p != n) ? n : null; // restart if off list jaroslav@1890: else if (!p.casNext(null, s)) jaroslav@1890: p = p.next; // re-read on CAS failure jaroslav@1890: else { jaroslav@1890: if (p != t) { // update if slack now >= 2 jaroslav@1890: while ((tail != t || !casTail(t, s)) && jaroslav@1890: (t = tail) != null && jaroslav@1890: (s = t.next) != null && // advance and retry jaroslav@1890: (s = s.next) != null && s != t); jaroslav@1890: } jaroslav@1890: return p; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Spins/yields/blocks until node s is matched or caller gives up. jaroslav@1890: * jaroslav@1890: * @param s the waiting node jaroslav@1890: * @param pred the predecessor of s, or s itself if it has no jaroslav@1890: * predecessor, or null if unknown (the null case does not occur jaroslav@1890: * in any current calls but may in possible future extensions) jaroslav@1890: * @param e the comparison value for checking match jaroslav@1890: * @param timed if true, wait only until timeout elapses jaroslav@1890: * @param nanos timeout in nanosecs, used only if timed is true jaroslav@1890: * @return matched item, or e if unmatched on interrupt or timeout jaroslav@1890: */ jaroslav@1890: private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) { jaroslav@1890: long lastTime = timed ? System.nanoTime() : 0L; jaroslav@1890: Thread w = Thread.currentThread(); jaroslav@1890: int spins = -1; // initialized after first item and cancel checks jaroslav@1890: ThreadLocalRandom randomYields = null; // bound if needed jaroslav@1890: jaroslav@1890: for (;;) { jaroslav@1890: Object item = s.item; jaroslav@1890: if (item != e) { // matched jaroslav@1890: // assert item != s; jaroslav@1890: s.forgetContents(); // avoid garbage jaroslav@1890: return this.cast(item); jaroslav@1890: } jaroslav@1890: if ((w.isInterrupted() || (timed && nanos <= 0)) && jaroslav@1890: s.casItem(e, s)) { // cancel jaroslav@1890: unsplice(pred, s); jaroslav@1890: return e; jaroslav@1890: } jaroslav@1890: jaroslav@1890: if (spins < 0) { // establish spins at/near front jaroslav@1890: if ((spins = spinsFor(pred, s.isData)) > 0) jaroslav@1890: randomYields = ThreadLocalRandom.current(); jaroslav@1890: } jaroslav@1890: else if (spins > 0) { // spin jaroslav@1890: --spins; jaroslav@1890: if (randomYields.nextInt(CHAINED_SPINS) == 0) jaroslav@1890: Thread.yield(); // occasionally yield jaroslav@1890: } jaroslav@1890: else if (s.waiter == null) { jaroslav@1890: s.waiter = w; // request unpark then recheck jaroslav@1890: } jaroslav@1890: else if (timed) { jaroslav@1890: long now = System.nanoTime(); jaroslav@1890: if ((nanos -= now - lastTime) > 0) jaroslav@1890: LockSupport.parkNanos(this, nanos); jaroslav@1890: lastTime = now; jaroslav@1890: } jaroslav@1890: else { jaroslav@1890: LockSupport.park(this); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns spin/yield value for a node with given predecessor and jaroslav@1890: * data mode. See above for explanation. jaroslav@1890: */ jaroslav@1890: private static int spinsFor(Node pred, boolean haveData) { jaroslav@1890: if (MP && pred != null) { jaroslav@1890: if (pred.isData != haveData) // phase change jaroslav@1890: return FRONT_SPINS + CHAINED_SPINS; jaroslav@1890: if (pred.isMatched()) // probably at front jaroslav@1890: return FRONT_SPINS; jaroslav@1890: if (pred.waiter == null) // pred apparently spinning jaroslav@1890: return CHAINED_SPINS; jaroslav@1890: } jaroslav@1890: return 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /* -------------- Traversal methods -------------- */ jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the successor of p, or the head node if p.next has been jaroslav@1890: * linked to self, which will only be true if traversing with a jaroslav@1890: * stale pointer that is now off the list. jaroslav@1890: */ jaroslav@1890: final Node succ(Node p) { jaroslav@1890: Node next = p.next; jaroslav@1890: return (p == next) ? head : next; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the first unmatched node of the given mode, or null if jaroslav@1890: * none. Used by methods isEmpty, hasWaitingConsumer. jaroslav@1890: */ jaroslav@1890: private Node firstOfMode(boolean isData) { jaroslav@1890: for (Node p = head; p != null; p = succ(p)) { jaroslav@1890: if (!p.isMatched()) jaroslav@1890: return (p.isData == isData) ? p : null; jaroslav@1890: } jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the item in the first unmatched node with isData; or jaroslav@1890: * null if none. Used by peek. jaroslav@1890: */ jaroslav@1890: private E firstDataItem() { jaroslav@1890: for (Node p = head; p != null; p = succ(p)) { jaroslav@1890: Object item = p.item; jaroslav@1890: if (p.isData) { jaroslav@1890: if (item != null && item != p) jaroslav@1890: return this.cast(item); jaroslav@1890: } jaroslav@1890: else if (item == null) jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Traverses and counts unmatched nodes of the given mode. jaroslav@1890: * Used by methods size and getWaitingConsumerCount. jaroslav@1890: */ jaroslav@1890: private int countOfMode(boolean data) { jaroslav@1890: int count = 0; jaroslav@1890: for (Node p = head; p != null; ) { jaroslav@1890: if (!p.isMatched()) { jaroslav@1890: if (p.isData != data) jaroslav@1890: return 0; jaroslav@1890: if (++count == Integer.MAX_VALUE) // saturated jaroslav@1890: break; jaroslav@1890: } jaroslav@1890: Node n = p.next; jaroslav@1890: if (n != p) jaroslav@1890: p = n; jaroslav@1890: else { jaroslav@1890: count = 0; jaroslav@1890: p = head; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: return count; jaroslav@1890: } jaroslav@1890: jaroslav@1890: final class Itr implements Iterator { jaroslav@1890: private Node nextNode; // next node to return item for jaroslav@1890: private E nextItem; // the corresponding item jaroslav@1890: private Node lastRet; // last returned node, to support remove jaroslav@1890: private Node lastPred; // predecessor to unlink lastRet jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Moves to next node after prev, or first node if prev null. jaroslav@1890: */ jaroslav@1890: private void advance(Node prev) { jaroslav@1890: /* jaroslav@1890: * To track and avoid buildup of deleted nodes in the face jaroslav@1890: * of calls to both Queue.remove and Itr.remove, we must jaroslav@1890: * include variants of unsplice and sweep upon each jaroslav@1890: * advance: Upon Itr.remove, we may need to catch up links jaroslav@1890: * from lastPred, and upon other removes, we might need to jaroslav@1890: * skip ahead from stale nodes and unsplice deleted ones jaroslav@1890: * found while advancing. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: Node r, b; // reset lastPred upon possible deletion of lastRet jaroslav@1890: if ((r = lastRet) != null && !r.isMatched()) jaroslav@1890: lastPred = r; // next lastPred is old lastRet jaroslav@1890: else if ((b = lastPred) == null || b.isMatched()) jaroslav@1890: lastPred = null; // at start of list jaroslav@1890: else { jaroslav@1890: Node s, n; // help with removal of lastPred.next jaroslav@1890: while ((s = b.next) != null && jaroslav@1890: s != b && s.isMatched() && jaroslav@1890: (n = s.next) != null && n != s) jaroslav@1890: b.casNext(s, n); jaroslav@1890: } jaroslav@1890: jaroslav@1890: this.lastRet = prev; jaroslav@1890: jaroslav@1890: for (Node p = prev, s, n;;) { jaroslav@1890: s = (p == null) ? head : p.next; jaroslav@1890: if (s == null) jaroslav@1890: break; jaroslav@1890: else if (s == p) { jaroslav@1890: p = null; jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: Object item = s.item; jaroslav@1890: if (s.isData) { jaroslav@1890: if (item != null && item != s) { jaroslav@1890: nextItem = LinkedTransferQueue.cast(item); jaroslav@1890: nextNode = s; jaroslav@1890: return; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: else if (item == null) jaroslav@1890: break; jaroslav@1890: // assert s.isMatched(); jaroslav@1890: if (p == null) jaroslav@1890: p = s; jaroslav@1890: else if ((n = s.next) == null) jaroslav@1890: break; jaroslav@1890: else if (s == n) jaroslav@1890: p = null; jaroslav@1890: else jaroslav@1890: p.casNext(s, n); jaroslav@1890: } jaroslav@1890: nextNode = null; jaroslav@1890: nextItem = null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: Itr() { jaroslav@1890: advance(null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public final boolean hasNext() { jaroslav@1890: return nextNode != null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public final E next() { jaroslav@1890: Node p = nextNode; jaroslav@1890: if (p == null) throw new NoSuchElementException(); jaroslav@1890: E e = nextItem; jaroslav@1890: advance(p); jaroslav@1890: return e; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public final void remove() { jaroslav@1890: final Node lastRet = this.lastRet; jaroslav@1890: if (lastRet == null) jaroslav@1890: throw new IllegalStateException(); jaroslav@1890: this.lastRet = null; jaroslav@1890: if (lastRet.tryMatchData()) jaroslav@1890: unsplice(lastPred, lastRet); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /* -------------- Removal methods -------------- */ jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Unsplices (now or later) the given deleted/cancelled node with jaroslav@1890: * the given predecessor. jaroslav@1890: * jaroslav@1890: * @param pred a node that was at one time known to be the jaroslav@1890: * predecessor of s, or null or s itself if s is/was at head jaroslav@1890: * @param s the node to be unspliced jaroslav@1890: */ jaroslav@1890: final void unsplice(Node pred, Node s) { jaroslav@1890: s.forgetContents(); // forget unneeded fields jaroslav@1890: /* jaroslav@1890: * See above for rationale. Briefly: if pred still points to jaroslav@1890: * s, try to unlink s. If s cannot be unlinked, because it is jaroslav@1890: * trailing node or pred might be unlinked, and neither pred jaroslav@1890: * nor s are head or offlist, add to sweepVotes, and if enough jaroslav@1890: * votes have accumulated, sweep. jaroslav@1890: */ jaroslav@1890: if (pred != null && pred != s && pred.next == s) { jaroslav@1890: Node n = s.next; jaroslav@1890: if (n == null || jaroslav@1890: (n != s && pred.casNext(s, n) && pred.isMatched())) { jaroslav@1890: for (;;) { // check if at, or could be, head jaroslav@1890: Node h = head; jaroslav@1890: if (h == pred || h == s || h == null) jaroslav@1890: return; // at head or list empty jaroslav@1890: if (!h.isMatched()) jaroslav@1890: break; jaroslav@1890: Node hn = h.next; jaroslav@1890: if (hn == null) jaroslav@1890: return; // now empty jaroslav@1890: if (hn != h && casHead(h, hn)) jaroslav@1890: h.forgetNext(); // advance head jaroslav@1890: } jaroslav@1890: if (pred.next != pred && s.next != s) { // recheck if offlist jaroslav@1890: for (;;) { // sweep now if enough votes jaroslav@1890: int v = sweepVotes; jaroslav@1890: if (v < SWEEP_THRESHOLD) { jaroslav@1890: if (casSweepVotes(v, v + 1)) jaroslav@1890: break; jaroslav@1890: } jaroslav@1890: else if (casSweepVotes(v, 0)) { jaroslav@1890: sweep(); jaroslav@1890: break; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Unlinks matched (typically cancelled) nodes encountered in a jaroslav@1890: * traversal from head. jaroslav@1890: */ jaroslav@1890: private void sweep() { jaroslav@1890: for (Node p = head, s, n; p != null && (s = p.next) != null; ) { jaroslav@1890: if (!s.isMatched()) jaroslav@1890: // Unmatched nodes are never self-linked jaroslav@1890: p = s; jaroslav@1890: else if ((n = s.next) == null) // trailing node is pinned jaroslav@1890: break; jaroslav@1890: else if (s == n) // stale jaroslav@1890: // No need to also check for p == s, since that implies s == n jaroslav@1890: p = head; jaroslav@1890: else jaroslav@1890: p.casNext(s, n); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Main implementation of remove(Object) jaroslav@1890: */ jaroslav@1890: private boolean findAndRemove(Object e) { jaroslav@1890: if (e != null) { jaroslav@1890: for (Node pred = null, p = head; p != null; ) { jaroslav@1890: Object item = p.item; jaroslav@1890: if (p.isData) { jaroslav@1890: if (item != null && item != p && e.equals(item) && jaroslav@1890: p.tryMatchData()) { jaroslav@1890: unsplice(pred, p); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: else if (item == null) jaroslav@1890: break; jaroslav@1890: pred = p; jaroslav@1890: if ((p = p.next) == pred) { // stale jaroslav@1890: pred = null; jaroslav@1890: p = head; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates an initially empty {@code LinkedTransferQueue}. jaroslav@1890: */ jaroslav@1890: public LinkedTransferQueue() { jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code LinkedTransferQueue} jaroslav@1890: * initially containing the elements of the given collection, jaroslav@1890: * added in traversal order of the collection's iterator. jaroslav@1890: * jaroslav@1890: * @param c the collection of elements to initially contain jaroslav@1890: * @throws NullPointerException if the specified collection or any jaroslav@1890: * of its elements are null jaroslav@1890: */ jaroslav@1890: public LinkedTransferQueue(Collection c) { jaroslav@1890: this(); jaroslav@1890: addAll(c); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element at the tail of this queue. jaroslav@1890: * As the queue is unbounded, this method will never block. jaroslav@1890: * jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public void put(E e) { jaroslav@1890: xfer(e, true, ASYNC, 0); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element at the tail of this queue. jaroslav@1890: * As the queue is unbounded, this method will never block or jaroslav@1890: * return {@code false}. jaroslav@1890: * jaroslav@1890: * @return {@code true} (as specified by jaroslav@1890: * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer}) jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean offer(E e, long timeout, TimeUnit unit) { jaroslav@1890: xfer(e, true, ASYNC, 0); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element at the tail of this queue. jaroslav@1890: * As the queue is unbounded, this method will never return {@code false}. jaroslav@1890: * jaroslav@1890: * @return {@code true} (as specified by {@link Queue#offer}) jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean offer(E e) { jaroslav@1890: xfer(e, true, ASYNC, 0); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element at the tail of this queue. jaroslav@1890: * As the queue is unbounded, this method will never throw jaroslav@1890: * {@link IllegalStateException} or return {@code false}. jaroslav@1890: * jaroslav@1890: * @return {@code true} (as specified by {@link Collection#add}) jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean add(E e) { jaroslav@1890: xfer(e, true, ASYNC, 0); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Transfers the element to a waiting consumer immediately, if possible. jaroslav@1890: * jaroslav@1890: *

More precisely, transfers the specified element immediately jaroslav@1890: * if there exists a consumer already waiting to receive it (in jaroslav@1890: * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), jaroslav@1890: * otherwise returning {@code false} without enqueuing the element. jaroslav@1890: * jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean tryTransfer(E e) { jaroslav@1890: return xfer(e, true, NOW, 0) == null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Transfers the element to a consumer, waiting if necessary to do so. jaroslav@1890: * jaroslav@1890: *

More precisely, transfers the specified element immediately jaroslav@1890: * if there exists a consumer already waiting to receive it (in jaroslav@1890: * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), jaroslav@1890: * else inserts the specified element at the tail of this queue jaroslav@1890: * and waits until the element is received by a consumer. jaroslav@1890: * jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public void transfer(E e) throws InterruptedException { jaroslav@1890: if (xfer(e, true, SYNC, 0) != null) { jaroslav@1890: Thread.interrupted(); // failure possible only due to interrupt jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Transfers the element to a consumer if it is possible to do so jaroslav@1890: * before the timeout elapses. jaroslav@1890: * jaroslav@1890: *

More precisely, transfers the specified element immediately jaroslav@1890: * if there exists a consumer already waiting to receive it (in jaroslav@1890: * {@link #take} or timed {@link #poll(long,TimeUnit) poll}), jaroslav@1890: * else inserts the specified element at the tail of this queue jaroslav@1890: * and waits until the element is received by a consumer, jaroslav@1890: * returning {@code false} if the specified wait time elapses jaroslav@1890: * before the element can be transferred. jaroslav@1890: * jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean tryTransfer(E e, long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null) jaroslav@1890: return true; jaroslav@1890: if (!Thread.interrupted()) jaroslav@1890: return false; jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E take() throws InterruptedException { jaroslav@1890: E e = xfer(null, false, SYNC, 0); jaroslav@1890: if (e != null) jaroslav@1890: return e; jaroslav@1890: Thread.interrupted(); jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E poll(long timeout, TimeUnit unit) throws InterruptedException { jaroslav@1890: E e = xfer(null, false, TIMED, unit.toNanos(timeout)); jaroslav@1890: if (e != null || !Thread.interrupted()) jaroslav@1890: return e; jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E poll() { jaroslav@1890: return xfer(null, false, NOW, 0); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while ( (e = poll()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c, int maxElements) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while (n < maxElements && (e = poll()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an iterator over the elements in this queue in proper sequence. jaroslav@1890: * The elements will be returned in order from first (head) to last (tail). jaroslav@1890: * jaroslav@1890: *

The returned iterator is a "weakly consistent" iterator that jaroslav@1890: * will never throw {@link java.util.ConcurrentModificationException jaroslav@1890: * ConcurrentModificationException}, and guarantees to traverse jaroslav@1890: * elements as they existed upon construction of the iterator, and jaroslav@1890: * may (but is not guaranteed to) reflect any modifications jaroslav@1890: * subsequent to construction. jaroslav@1890: * jaroslav@1890: * @return an iterator over the elements in this queue in proper sequence jaroslav@1890: */ jaroslav@1890: public Iterator iterator() { jaroslav@1890: return new Itr(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public E peek() { jaroslav@1890: return firstDataItem(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this queue contains no elements. jaroslav@1890: * jaroslav@1890: * @return {@code true} if this queue contains no elements jaroslav@1890: */ jaroslav@1890: public boolean isEmpty() { jaroslav@1890: for (Node p = head; p != null; p = succ(p)) { jaroslav@1890: if (!p.isMatched()) jaroslav@1890: return !p.isData; jaroslav@1890: } jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: public boolean hasWaitingConsumer() { jaroslav@1890: return firstOfMode(false) != null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the number of elements in this queue. If this queue jaroslav@1890: * contains more than {@code Integer.MAX_VALUE} elements, returns jaroslav@1890: * {@code Integer.MAX_VALUE}. jaroslav@1890: * jaroslav@1890: *

Beware that, unlike in most collections, this method is jaroslav@1890: * NOT a constant-time operation. Because of the jaroslav@1890: * asynchronous nature of these queues, determining the current jaroslav@1890: * number of elements requires an O(n) traversal. jaroslav@1890: * jaroslav@1890: * @return the number of elements in this queue jaroslav@1890: */ jaroslav@1890: public int size() { jaroslav@1890: return countOfMode(true); jaroslav@1890: } jaroslav@1890: jaroslav@1890: public int getWaitingConsumerCount() { jaroslav@1890: return countOfMode(false); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Removes a single instance of the specified element from this queue, jaroslav@1890: * if it is present. More formally, removes an element {@code e} such jaroslav@1890: * that {@code o.equals(e)}, if this queue contains one or more such jaroslav@1890: * elements. jaroslav@1890: * Returns {@code true} if this queue contained the specified element jaroslav@1890: * (or equivalently, if this queue changed as a result of the call). jaroslav@1890: * jaroslav@1890: * @param o element to be removed from this queue, if present jaroslav@1890: * @return {@code true} if this queue changed as a result of the call jaroslav@1890: */ jaroslav@1890: public boolean remove(Object o) { jaroslav@1890: return findAndRemove(o); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this queue contains the specified element. jaroslav@1890: * More formally, returns {@code true} if and only if this queue contains jaroslav@1890: * at least one element {@code e} such that {@code o.equals(e)}. jaroslav@1890: * jaroslav@1890: * @param o object to be checked for containment in this queue jaroslav@1890: * @return {@code true} if this queue contains the specified element jaroslav@1890: */ jaroslav@1890: public boolean contains(Object o) { jaroslav@1890: if (o == null) return false; jaroslav@1890: for (Node p = head; p != null; p = succ(p)) { jaroslav@1890: Object item = p.item; jaroslav@1890: if (p.isData) { jaroslav@1890: if (item != null && item != p && o.equals(item)) jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: else if (item == null) jaroslav@1890: break; jaroslav@1890: } jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns {@code Integer.MAX_VALUE} because a jaroslav@1890: * {@code LinkedTransferQueue} is not capacity constrained. jaroslav@1890: * jaroslav@1890: * @return {@code Integer.MAX_VALUE} (as specified by jaroslav@1890: * {@link BlockingQueue#remainingCapacity()}) jaroslav@1890: */ jaroslav@1890: public int remainingCapacity() { jaroslav@1890: return Integer.MAX_VALUE; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Saves the state to a stream (that is, serializes it). jaroslav@1890: * jaroslav@1890: * @serialData All of the elements (each an {@code E}) in jaroslav@1890: * the proper order, followed by a null jaroslav@1890: * @param s the stream jaroslav@1890: */ jaroslav@1890: private void writeObject(java.io.ObjectOutputStream s) jaroslav@1890: throws java.io.IOException { jaroslav@1890: s.defaultWriteObject(); jaroslav@1890: for (E e : this) jaroslav@1890: s.writeObject(e); jaroslav@1890: // Use trailing null as sentinel jaroslav@1890: s.writeObject(null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Reconstitutes the Queue instance from a stream (that is, jaroslav@1890: * deserializes it). jaroslav@1890: * jaroslav@1890: * @param s the stream jaroslav@1890: */ jaroslav@1890: private void readObject(java.io.ObjectInputStream s) jaroslav@1890: throws java.io.IOException, ClassNotFoundException { jaroslav@1890: s.defaultReadObject(); jaroslav@1890: for (;;) { jaroslav@1890: @SuppressWarnings("unchecked") E item = (E) s.readObject(); jaroslav@1890: if (item == null) jaroslav@1890: break; jaroslav@1890: else jaroslav@1890: offer(item); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: // Unsafe mechanics jaroslav@1890: jaroslav@1890: private static final sun.misc.Unsafe UNSAFE; jaroslav@1890: private static final long headOffset; jaroslav@1890: private static final long tailOffset; jaroslav@1890: private static final long sweepVotesOffset; jaroslav@1890: static { jaroslav@1890: try { jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe(); jaroslav@1890: Class k = LinkedTransferQueue.class; jaroslav@1890: headOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("head")); jaroslav@1890: tailOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("tail")); jaroslav@1890: sweepVotesOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("sweepVotes")); jaroslav@1890: } catch (Exception e) { jaroslav@1890: throw new Error(e); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: }