ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.4
Committed: Mon Mar 23 18:56:40 2015 UTC (9 years, 2 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.3: +4 -0 lines
Log Message:
JDK-8074773: Reduce the risk of rare disastrous classloading in first call to LockSupport.park

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/publicdomain/zero/1.0/
5     */
6    
7     package java.util.concurrent;
8    
9     import java.util.AbstractQueue;
10     import java.util.Collection;
11     import java.util.Iterator;
12     import java.util.NoSuchElementException;
13     import java.util.Queue;
14     import java.util.concurrent.locks.LockSupport;
15    
16     /**
17     * An unbounded {@link TransferQueue} based on linked nodes.
18     * This queue orders elements FIFO (first-in-first-out) with respect
19     * to any given producer. The <em>head</em> of the queue is that
20     * element that has been on the queue the longest time for some
21     * producer. The <em>tail</em> of the queue is that element that has
22     * been on the queue the shortest time for some producer.
23     *
24     * <p>Beware that, unlike in most collections, the {@code size} method
25     * is <em>NOT</em> a constant-time operation. Because of the
26     * asynchronous nature of these queues, determining the current number
27     * of elements requires a traversal of the elements, and so may report
28     * inaccurate results if this collection is modified during traversal.
29     * Additionally, the bulk operations {@code addAll},
30     * {@code removeAll}, {@code retainAll}, {@code containsAll},
31     * {@code equals}, and {@code toArray} are <em>not</em> guaranteed
32     * to be performed atomically. For example, an iterator operating
33     * concurrently with an {@code addAll} operation might view only some
34     * of the added elements.
35     *
36     * <p>This class and its iterator implement all of the
37     * <em>optional</em> methods of the {@link Collection} and {@link
38     * Iterator} interfaces.
39     *
40     * <p>Memory consistency effects: As with other concurrent
41     * collections, actions in a thread prior to placing an object into a
42     * {@code LinkedTransferQueue}
43     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
44     * actions subsequent to the access or removal of that element from
45     * the {@code LinkedTransferQueue} in another thread.
46     *
47     * <p>This class is a member of the
48     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
49     * Java Collections Framework</a>.
50     *
51     * @since 1.7
52     * @author Doug Lea
53     * @param <E> the type of elements held in this collection
54     */
55     public class LinkedTransferQueue<E> extends AbstractQueue<E>
56     implements TransferQueue<E>, java.io.Serializable {
57     private static final long serialVersionUID = -3223113410248163686L;
58    
59     /*
60     * *** Overview of Dual Queues with Slack ***
61     *
62     * Dual Queues, introduced by Scherer and Scott
63     * (http://www.cs.rice.edu/~wns1/papers/2004-DISC-DDS.pdf) are
64     * (linked) queues in which nodes may represent either data or
65     * requests. When a thread tries to enqueue a data node, but
66     * encounters a request node, it instead "matches" and removes it;
67     * and vice versa for enqueuing requests. Blocking Dual Queues
68     * arrange that threads enqueuing unmatched requests block until
69     * other threads provide the match. Dual Synchronous Queues (see
70     * Scherer, Lea, & Scott
71     * http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf)
72     * additionally arrange that threads enqueuing unmatched data also
73     * block. Dual Transfer Queues support all of these modes, as
74     * dictated by callers.
75     *
76     * A FIFO dual queue may be implemented using a variation of the
77     * Michael & Scott (M&S) lock-free queue algorithm
78 jsr166 1.2 * (http://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf).
79 dl 1.1 * It maintains two pointer fields, "head", pointing to a
80     * (matched) node that in turn points to the first actual
81     * (unmatched) queue node (or null if empty); and "tail" that
82     * points to the last node on the queue (or again null if
83     * empty). For example, here is a possible queue with four data
84     * elements:
85     *
86     * head tail
87     * | |
88     * v v
89     * M -> U -> U -> U -> U
90     *
91     * The M&S queue algorithm is known to be prone to scalability and
92     * overhead limitations when maintaining (via CAS) these head and
93     * tail pointers. This has led to the development of
94     * contention-reducing variants such as elimination arrays (see
95     * Moir et al http://portal.acm.org/citation.cfm?id=1074013) and
96     * optimistic back pointers (see Ladan-Mozes & Shavit
97     * http://people.csail.mit.edu/edya/publications/OptimisticFIFOQueue-journal.pdf).
98     * However, the nature of dual queues enables a simpler tactic for
99     * improving M&S-style implementations when dual-ness is needed.
100     *
101     * In a dual queue, each node must atomically maintain its match
102     * status. While there are other possible variants, we implement
103     * this here as: for a data-mode node, matching entails CASing an
104     * "item" field from a non-null data value to null upon match, and
105     * vice-versa for request nodes, CASing from null to a data
106     * value. (Note that the linearization properties of this style of
107     * queue are easy to verify -- elements are made available by
108     * linking, and unavailable by matching.) Compared to plain M&S
109     * queues, this property of dual queues requires one additional
110     * successful atomic operation per enq/deq pair. But it also
111     * enables lower cost variants of queue maintenance mechanics. (A
112     * variation of this idea applies even for non-dual queues that
113     * support deletion of interior elements, such as
114     * j.u.c.ConcurrentLinkedQueue.)
115     *
116     * Once a node is matched, its match status can never again
117     * change. We may thus arrange that the linked list of them
118     * contain a prefix of zero or more matched nodes, followed by a
119     * suffix of zero or more unmatched nodes. (Note that we allow
120     * both the prefix and suffix to be zero length, which in turn
121     * means that we do not use a dummy header.) If we were not
122     * concerned with either time or space efficiency, we could
123     * correctly perform enqueue and dequeue operations by traversing
124     * from a pointer to the initial node; CASing the item of the
125     * first unmatched node on match and CASing the next field of the
126     * trailing node on appends. (Plus some special-casing when
127     * initially empty). While this would be a terrible idea in
128     * itself, it does have the benefit of not requiring ANY atomic
129     * updates on head/tail fields.
130     *
131     * We introduce here an approach that lies between the extremes of
132     * never versus always updating queue (head and tail) pointers.
133     * This offers a tradeoff between sometimes requiring extra
134     * traversal steps to locate the first and/or last unmatched
135     * nodes, versus the reduced overhead and contention of fewer
136     * updates to queue pointers. For example, a possible snapshot of
137     * a queue is:
138     *
139     * head tail
140     * | |
141     * v v
142     * M -> M -> U -> U -> U -> U
143     *
144     * The best value for this "slack" (the targeted maximum distance
145     * between the value of "head" and the first unmatched node, and
146     * similarly for "tail") is an empirical matter. We have found
147     * that using very small constants in the range of 1-3 work best
148     * over a range of platforms. Larger values introduce increasing
149     * costs of cache misses and risks of long traversal chains, while
150     * smaller values increase CAS contention and overhead.
151     *
152     * Dual queues with slack differ from plain M&S dual queues by
153     * virtue of only sometimes updating head or tail pointers when
154     * matching, appending, or even traversing nodes; in order to
155     * maintain a targeted slack. The idea of "sometimes" may be
156     * operationalized in several ways. The simplest is to use a
157     * per-operation counter incremented on each traversal step, and
158     * to try (via CAS) to update the associated queue pointer
159     * whenever the count exceeds a threshold. Another, that requires
160     * more overhead, is to use random number generators to update
161     * with a given probability per traversal step.
162     *
163     * In any strategy along these lines, because CASes updating
164     * fields may fail, the actual slack may exceed targeted
165     * slack. However, they may be retried at any time to maintain
166     * targets. Even when using very small slack values, this
167     * approach works well for dual queues because it allows all
168     * operations up to the point of matching or appending an item
169     * (hence potentially allowing progress by another thread) to be
170     * read-only, thus not introducing any further contention. As
171     * described below, we implement this by performing slack
172     * maintenance retries only after these points.
173     *
174     * As an accompaniment to such techniques, traversal overhead can
175     * be further reduced without increasing contention of head
176     * pointer updates: Threads may sometimes shortcut the "next" link
177     * path from the current "head" node to be closer to the currently
178     * known first unmatched node, and similarly for tail. Again, this
179     * may be triggered with using thresholds or randomization.
180     *
181     * These ideas must be further extended to avoid unbounded amounts
182     * of costly-to-reclaim garbage caused by the sequential "next"
183     * links of nodes starting at old forgotten head nodes: As first
184     * described in detail by Boehm
185     * (http://portal.acm.org/citation.cfm?doid=503272.503282) if a GC
186     * delays noticing that any arbitrarily old node has become
187     * garbage, all newer dead nodes will also be unreclaimed.
188     * (Similar issues arise in non-GC environments.) To cope with
189     * this in our implementation, upon CASing to advance the head
190     * pointer, we set the "next" link of the previous head to point
191     * only to itself; thus limiting the length of connected dead lists.
192     * (We also take similar care to wipe out possibly garbage
193     * retaining values held in other Node fields.) However, doing so
194     * adds some further complexity to traversal: If any "next"
195     * pointer links to itself, it indicates that the current thread
196     * has lagged behind a head-update, and so the traversal must
197     * continue from the "head". Traversals trying to find the
198     * current tail starting from "tail" may also encounter
199     * self-links, in which case they also continue at "head".
200     *
201     * It is tempting in slack-based scheme to not even use CAS for
202     * updates (similarly to Ladan-Mozes & Shavit). However, this
203     * cannot be done for head updates under the above link-forgetting
204     * mechanics because an update may leave head at a detached node.
205     * And while direct writes are possible for tail updates, they
206     * increase the risk of long retraversals, and hence long garbage
207     * chains, which can be much more costly than is worthwhile
208     * considering that the cost difference of performing a CAS vs
209     * write is smaller when they are not triggered on each operation
210     * (especially considering that writes and CASes equally require
211     * additional GC bookkeeping ("write barriers") that are sometimes
212     * more costly than the writes themselves because of contention).
213     *
214     * *** Overview of implementation ***
215     *
216     * We use a threshold-based approach to updates, with a slack
217     * threshold of two -- that is, we update head/tail when the
218     * current pointer appears to be two or more steps away from the
219     * first/last node. The slack value is hard-wired: a path greater
220     * than one is naturally implemented by checking equality of
221     * traversal pointers except when the list has only one element,
222     * in which case we keep slack threshold at one. Avoiding tracking
223     * explicit counts across method calls slightly simplifies an
224     * already-messy implementation. Using randomization would
225     * probably work better if there were a low-quality dirt-cheap
226     * per-thread one available, but even ThreadLocalRandom is too
227     * heavy for these purposes.
228     *
229     * With such a small slack threshold value, it is not worthwhile
230     * to augment this with path short-circuiting (i.e., unsplicing
231     * interior nodes) except in the case of cancellation/removal (see
232     * below).
233     *
234     * We allow both the head and tail fields to be null before any
235     * nodes are enqueued; initializing upon first append. This
236     * simplifies some other logic, as well as providing more
237     * efficient explicit control paths instead of letting JVMs insert
238     * implicit NullPointerExceptions when they are null. While not
239     * currently fully implemented, we also leave open the possibility
240     * of re-nulling these fields when empty (which is complicated to
241     * arrange, for little benefit.)
242     *
243     * All enqueue/dequeue operations are handled by the single method
244     * "xfer" with parameters indicating whether to act as some form
245     * of offer, put, poll, take, or transfer (each possibly with
246     * timeout). The relative complexity of using one monolithic
247     * method outweighs the code bulk and maintenance problems of
248     * using separate methods for each case.
249     *
250     * Operation consists of up to three phases. The first is
251     * implemented within method xfer, the second in tryAppend, and
252     * the third in method awaitMatch.
253     *
254     * 1. Try to match an existing node
255     *
256     * Starting at head, skip already-matched nodes until finding
257     * an unmatched node of opposite mode, if one exists, in which
258     * case matching it and returning, also if necessary updating
259     * head to one past the matched node (or the node itself if the
260     * list has no other unmatched nodes). If the CAS misses, then
261     * a loop retries advancing head by two steps until either
262     * success or the slack is at most two. By requiring that each
263     * attempt advances head by two (if applicable), we ensure that
264     * the slack does not grow without bound. Traversals also check
265     * if the initial head is now off-list, in which case they
266     * start at the new head.
267     *
268     * If no candidates are found and the call was untimed
269     * poll/offer, (argument "how" is NOW) return.
270     *
271     * 2. Try to append a new node (method tryAppend)
272     *
273     * Starting at current tail pointer, find the actual last node
274     * and try to append a new node (or if head was null, establish
275     * the first node). Nodes can be appended only if their
276     * predecessors are either already matched or are of the same
277     * mode. If we detect otherwise, then a new node with opposite
278     * mode must have been appended during traversal, so we must
279     * restart at phase 1. The traversal and update steps are
280     * otherwise similar to phase 1: Retrying upon CAS misses and
281     * checking for staleness. In particular, if a self-link is
282     * encountered, then we can safely jump to a node on the list
283     * by continuing the traversal at current head.
284     *
285     * On successful append, if the call was ASYNC, return.
286     *
287     * 3. Await match or cancellation (method awaitMatch)
288     *
289     * Wait for another thread to match node; instead cancelling if
290     * the current thread was interrupted or the wait timed out. On
291     * multiprocessors, we use front-of-queue spinning: If a node
292     * appears to be the first unmatched node in the queue, it
293     * spins a bit before blocking. In either case, before blocking
294     * it tries to unsplice any nodes between the current "head"
295     * and the first unmatched node.
296     *
297     * Front-of-queue spinning vastly improves performance of
298     * heavily contended queues. And so long as it is relatively
299     * brief and "quiet", spinning does not much impact performance
300     * of less-contended queues. During spins threads check their
301     * interrupt status and generate a thread-local random number
302     * to decide to occasionally perform a Thread.yield. While
303     * yield has underdefined specs, we assume that it might help,
304     * and will not hurt, in limiting impact of spinning on busy
305     * systems. We also use smaller (1/2) spins for nodes that are
306     * not known to be front but whose predecessors have not
307     * blocked -- these "chained" spins avoid artifacts of
308     * front-of-queue rules which otherwise lead to alternating
309     * nodes spinning vs blocking. Further, front threads that
310     * represent phase changes (from data to request node or vice
311     * versa) compared to their predecessors receive additional
312     * chained spins, reflecting longer paths typically required to
313     * unblock threads during phase changes.
314     *
315     *
316     * ** Unlinking removed interior nodes **
317     *
318     * In addition to minimizing garbage retention via self-linking
319     * described above, we also unlink removed interior nodes. These
320     * may arise due to timed out or interrupted waits, or calls to
321     * remove(x) or Iterator.remove. Normally, given a node that was
322     * at one time known to be the predecessor of some node s that is
323     * to be removed, we can unsplice s by CASing the next field of
324     * its predecessor if it still points to s (otherwise s must
325     * already have been removed or is now offlist). But there are two
326     * situations in which we cannot guarantee to make node s
327     * unreachable in this way: (1) If s is the trailing node of list
328     * (i.e., with null next), then it is pinned as the target node
329     * for appends, so can only be removed later after other nodes are
330     * appended. (2) We cannot necessarily unlink s given a
331     * predecessor node that is matched (including the case of being
332     * cancelled): the predecessor may already be unspliced, in which
333     * case some previous reachable node may still point to s.
334     * (For further explanation see Herlihy & Shavit "The Art of
335     * Multiprocessor Programming" chapter 9). Although, in both
336     * cases, we can rule out the need for further action if either s
337     * or its predecessor are (or can be made to be) at, or fall off
338     * from, the head of list.
339     *
340     * Without taking these into account, it would be possible for an
341     * unbounded number of supposedly removed nodes to remain
342     * reachable. Situations leading to such buildup are uncommon but
343     * can occur in practice; for example when a series of short timed
344     * calls to poll repeatedly time out but never otherwise fall off
345     * the list because of an untimed call to take at the front of the
346     * queue.
347     *
348     * When these cases arise, rather than always retraversing the
349     * entire list to find an actual predecessor to unlink (which
350     * won't help for case (1) anyway), we record a conservative
351     * estimate of possible unsplice failures (in "sweepVotes").
352     * We trigger a full sweep when the estimate exceeds a threshold
353     * ("SWEEP_THRESHOLD") indicating the maximum number of estimated
354     * removal failures to tolerate before sweeping through, unlinking
355     * cancelled nodes that were not unlinked upon initial removal.
356     * We perform sweeps by the thread hitting threshold (rather than
357     * background threads or by spreading work to other threads)
358     * because in the main contexts in which removal occurs, the
359     * caller is already timed-out, cancelled, or performing a
360     * potentially O(n) operation (e.g. remove(x)), none of which are
361     * time-critical enough to warrant the overhead that alternatives
362     * would impose on other threads.
363     *
364     * Because the sweepVotes estimate is conservative, and because
365     * nodes become unlinked "naturally" as they fall off the head of
366     * the queue, and because we allow votes to accumulate even while
367     * sweeps are in progress, there are typically significantly fewer
368     * such nodes than estimated. Choice of a threshold value
369     * balances the likelihood of wasted effort and contention, versus
370     * providing a worst-case bound on retention of interior nodes in
371     * quiescent queues. The value defined below was chosen
372     * empirically to balance these under various timeout scenarios.
373     *
374     * Note that we cannot self-link unlinked interior nodes during
375     * sweeps. However, the associated garbage chains terminate when
376     * some successor ultimately falls off the head of the list and is
377     * self-linked.
378     */
379    
380     /** True if on multiprocessor */
381     private static final boolean MP =
382     Runtime.getRuntime().availableProcessors() > 1;
383    
384     /**
385     * The number of times to spin (with randomly interspersed calls
386     * to Thread.yield) on multiprocessor before blocking when a node
387     * is apparently the first waiter in the queue. See above for
388     * explanation. Must be a power of two. The value is empirically
389     * derived -- it works pretty well across a variety of processors,
390     * numbers of CPUs, and OSes.
391     */
392     private static final int FRONT_SPINS = 1 << 7;
393    
394     /**
395     * The number of times to spin before blocking when a node is
396     * preceded by another node that is apparently spinning. Also
397     * serves as an increment to FRONT_SPINS on phase changes, and as
398     * base average frequency for yielding during spins. Must be a
399     * power of two.
400     */
401     private static final int CHAINED_SPINS = FRONT_SPINS >>> 1;
402    
403     /**
404     * The maximum number of estimated removal failures (sweepVotes)
405     * to tolerate before sweeping through the queue unlinking
406     * cancelled nodes that were not unlinked upon initial
407     * removal. See above for explanation. The value must be at least
408     * two to avoid useless sweeps when removing trailing nodes.
409     */
410     static final int SWEEP_THRESHOLD = 32;
411    
412     /**
413     * Queue nodes. Uses Object, not E, for items to allow forgetting
414     * them after use. Relies heavily on Unsafe mechanics to minimize
415     * unnecessary ordering constraints: Writes that are intrinsically
416     * ordered wrt other accesses or CASes use simple relaxed forms.
417     */
418     static final class Node {
419     final boolean isData; // false if this is a request node
420     volatile Object item; // initially non-null if isData; CASed to match
421     volatile Node next;
422     volatile Thread waiter; // null until waiting
423    
424     // CAS methods for fields
425     final boolean casNext(Node cmp, Node val) {
426     return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
427     }
428    
429     final boolean casItem(Object cmp, Object val) {
430     // assert cmp == null || cmp.getClass() != Node.class;
431     return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
432     }
433    
434     /**
435     * Constructs a new node. Uses relaxed write because item can
436     * only be seen after publication via casNext.
437     */
438     Node(Object item, boolean isData) {
439     UNSAFE.putObject(this, itemOffset, item); // relaxed write
440     this.isData = isData;
441     }
442    
443     /**
444     * Links node to itself to avoid garbage retention. Called
445     * only after CASing head field, so uses relaxed write.
446     */
447     final void forgetNext() {
448     UNSAFE.putObject(this, nextOffset, this);
449     }
450    
451     /**
452     * Sets item to self and waiter to null, to avoid garbage
453     * retention after matching or cancelling. Uses relaxed writes
454     * because order is already constrained in the only calling
455     * contexts: item is forgotten only after volatile/atomic
456     * mechanics that extract items. Similarly, clearing waiter
457     * follows either CAS or return from park (if ever parked;
458     * else we don't care).
459     */
460     final void forgetContents() {
461     UNSAFE.putObject(this, itemOffset, this);
462     UNSAFE.putObject(this, waiterOffset, null);
463     }
464    
465     /**
466     * Returns true if this node has been matched, including the
467     * case of artificial matches due to cancellation.
468     */
469     final boolean isMatched() {
470     Object x = item;
471     return (x == this) || ((x == null) == isData);
472     }
473    
474     /**
475     * Returns true if this is an unmatched request node.
476     */
477     final boolean isUnmatchedRequest() {
478     return !isData && item == null;
479     }
480    
481     /**
482     * Returns true if a node with the given mode cannot be
483     * appended to this node because this node is unmatched and
484     * has opposite data mode.
485     */
486     final boolean cannotPrecede(boolean haveData) {
487     boolean d = isData;
488     Object x;
489     return d != haveData && (x = item) != this && (x != null) == d;
490     }
491    
492     /**
493     * Tries to artificially match a data node -- used by remove.
494     */
495     final boolean tryMatchData() {
496     // assert isData;
497     Object x = item;
498     if (x != null && x != this && casItem(x, null)) {
499     LockSupport.unpark(waiter);
500     return true;
501     }
502     return false;
503     }
504    
505     private static final long serialVersionUID = -3375979862319811754L;
506    
507     // Unsafe mechanics
508     private static final sun.misc.Unsafe UNSAFE;
509     private static final long itemOffset;
510     private static final long nextOffset;
511     private static final long waiterOffset;
512     static {
513     try {
514     UNSAFE = sun.misc.Unsafe.getUnsafe();
515     Class<?> k = Node.class;
516     itemOffset = UNSAFE.objectFieldOffset
517     (k.getDeclaredField("item"));
518     nextOffset = UNSAFE.objectFieldOffset
519     (k.getDeclaredField("next"));
520     waiterOffset = UNSAFE.objectFieldOffset
521     (k.getDeclaredField("waiter"));
522     } catch (Exception e) {
523     throw new Error(e);
524     }
525     }
526     }
527    
528     /** head of the queue; null until first enqueue */
529     transient volatile Node head;
530    
531     /** tail of the queue; null until first append */
532     private transient volatile Node tail;
533    
534     /** The number of apparent failures to unsplice removed nodes */
535     private transient volatile int sweepVotes;
536    
537     // CAS methods for fields
538     private boolean casTail(Node cmp, Node val) {
539     return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
540     }
541    
542     private boolean casHead(Node cmp, Node val) {
543     return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
544     }
545    
546     private boolean casSweepVotes(int cmp, int val) {
547     return UNSAFE.compareAndSwapInt(this, sweepVotesOffset, cmp, val);
548     }
549    
550     /*
551     * Possible values for "how" argument in xfer method.
552     */
553     private static final int NOW = 0; // for untimed poll, tryTransfer
554     private static final int ASYNC = 1; // for offer, put, add
555     private static final int SYNC = 2; // for transfer, take
556     private static final int TIMED = 3; // for timed poll, tryTransfer
557    
558     @SuppressWarnings("unchecked")
559     static <E> E cast(Object item) {
560     // assert item == null || item.getClass() != Node.class;
561     return (E) item;
562     }
563    
564     /**
565     * Implements all queuing methods. See above for explanation.
566     *
567     * @param e the item or null for take
568     * @param haveData true if this is a put, else a take
569     * @param how NOW, ASYNC, SYNC, or TIMED
570     * @param nanos timeout in nanosecs, used only if mode is TIMED
571     * @return an item if matched, else e
572     * @throws NullPointerException if haveData mode but e is null
573     */
574     private E xfer(E e, boolean haveData, int how, long nanos) {
575     if (haveData && (e == null))
576     throw new NullPointerException();
577     Node s = null; // the node to append, if needed
578    
579     retry:
580     for (;;) { // restart on append race
581    
582     for (Node h = head, p = h; p != null;) { // find & match first node
583     boolean isData = p.isData;
584     Object item = p.item;
585     if (item != p && (item != null) == isData) { // unmatched
586     if (isData == haveData) // can't match
587     break;
588     if (p.casItem(item, e)) { // match
589     for (Node q = p; q != h;) {
590     Node n = q.next; // update by 2 unless singleton
591     if (head == h && casHead(h, n == null ? q : n)) {
592     h.forgetNext();
593     break;
594     } // advance and retry
595     if ((h = head) == null ||
596     (q = h.next) == null || !q.isMatched())
597     break; // unless slack < 2
598     }
599     LockSupport.unpark(p.waiter);
600     return LinkedTransferQueue.<E>cast(item);
601     }
602     }
603     Node n = p.next;
604     p = (p != n) ? n : (h = head); // Use head if p offlist
605     }
606    
607     if (how != NOW) { // No matches available
608     if (s == null)
609     s = new Node(e, haveData);
610     Node pred = tryAppend(s, haveData);
611     if (pred == null)
612     continue retry; // lost race vs opposite mode
613     if (how != ASYNC)
614     return awaitMatch(s, pred, e, (how == TIMED), nanos);
615     }
616     return e; // not waiting
617     }
618     }
619    
620     /**
621     * Tries to append node s as tail.
622     *
623     * @param s the node to append
624     * @param haveData true if appending in data mode
625     * @return null on failure due to losing race with append in
626     * different mode, else s's predecessor, or s itself if no
627     * predecessor
628     */
629     private Node tryAppend(Node s, boolean haveData) {
630     for (Node t = tail, p = t;;) { // move p to last node and append
631     Node n, u; // temps for reads of next & tail
632     if (p == null && (p = head) == null) {
633     if (casHead(null, s))
634     return s; // initialize
635     }
636     else if (p.cannotPrecede(haveData))
637     return null; // lost race vs opposite mode
638     else if ((n = p.next) != null) // not last; keep traversing
639     p = p != t && t != (u = tail) ? (t = u) : // stale tail
640     (p != n) ? n : null; // restart if off list
641     else if (!p.casNext(null, s))
642     p = p.next; // re-read on CAS failure
643     else {
644     if (p != t) { // update if slack now >= 2
645     while ((tail != t || !casTail(t, s)) &&
646     (t = tail) != null &&
647     (s = t.next) != null && // advance and retry
648     (s = s.next) != null && s != t);
649     }
650     return p;
651     }
652     }
653     }
654    
655     /**
656     * Spins/yields/blocks until node s is matched or caller gives up.
657     *
658     * @param s the waiting node
659     * @param pred the predecessor of s, or s itself if it has no
660     * predecessor, or null if unknown (the null case does not occur
661     * in any current calls but may in possible future extensions)
662     * @param e the comparison value for checking match
663     * @param timed if true, wait only until timeout elapses
664     * @param nanos timeout in nanosecs, used only if timed is true
665     * @return matched item, or e if unmatched on interrupt or timeout
666     */
667     private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
668     final long deadline = timed ? System.nanoTime() + nanos : 0L;
669     Thread w = Thread.currentThread();
670     int spins = -1; // initialized after first item and cancel checks
671     ThreadLocalRandom randomYields = null; // bound if needed
672    
673     for (;;) {
674     Object item = s.item;
675     if (item != e) { // matched
676     // assert item != s;
677     s.forgetContents(); // avoid garbage
678     return LinkedTransferQueue.<E>cast(item);
679     }
680     if ((w.isInterrupted() || (timed && nanos <= 0)) &&
681     s.casItem(e, s)) { // cancel
682     unsplice(pred, s);
683     return e;
684     }
685    
686     if (spins < 0) { // establish spins at/near front
687     if ((spins = spinsFor(pred, s.isData)) > 0)
688     randomYields = ThreadLocalRandom.current();
689     }
690     else if (spins > 0) { // spin
691     --spins;
692     if (randomYields.nextInt(CHAINED_SPINS) == 0)
693     Thread.yield(); // occasionally yield
694     }
695     else if (s.waiter == null) {
696     s.waiter = w; // request unpark then recheck
697     }
698     else if (timed) {
699     nanos = deadline - System.nanoTime();
700     if (nanos > 0L)
701     LockSupport.parkNanos(this, nanos);
702     }
703     else {
704     LockSupport.park(this);
705     }
706     }
707     }
708    
709     /**
710     * Returns spin/yield value for a node with given predecessor and
711     * data mode. See above for explanation.
712     */
713     private static int spinsFor(Node pred, boolean haveData) {
714     if (MP && pred != null) {
715     if (pred.isData != haveData) // phase change
716     return FRONT_SPINS + CHAINED_SPINS;
717     if (pred.isMatched()) // probably at front
718     return FRONT_SPINS;
719     if (pred.waiter == null) // pred apparently spinning
720     return CHAINED_SPINS;
721     }
722     return 0;
723     }
724    
725     /* -------------- Traversal methods -------------- */
726    
727     /**
728     * Returns the successor of p, or the head node if p.next has been
729     * linked to self, which will only be true if traversing with a
730     * stale pointer that is now off the list.
731     */
732     final Node succ(Node p) {
733     Node next = p.next;
734     return (p == next) ? head : next;
735     }
736    
737     /**
738     * Returns the first unmatched node of the given mode, or null if
739     * none. Used by methods isEmpty, hasWaitingConsumer.
740     */
741     private Node firstOfMode(boolean isData) {
742     for (Node p = head; p != null; p = succ(p)) {
743     if (!p.isMatched())
744     return (p.isData == isData) ? p : null;
745     }
746     return null;
747     }
748    
749     /**
750     * Returns the item in the first unmatched node with isData; or
751     * null if none. Used by peek.
752     */
753     private E firstDataItem() {
754     for (Node p = head; p != null; p = succ(p)) {
755     Object item = p.item;
756     if (p.isData) {
757     if (item != null && item != p)
758     return LinkedTransferQueue.<E>cast(item);
759     }
760     else if (item == null)
761     return null;
762     }
763     return null;
764     }
765    
766     /**
767     * Traverses and counts unmatched nodes of the given mode.
768     * Used by methods size and getWaitingConsumerCount.
769     */
770     private int countOfMode(boolean data) {
771     int count = 0;
772     for (Node p = head; p != null; ) {
773     if (!p.isMatched()) {
774     if (p.isData != data)
775     return 0;
776     if (++count == Integer.MAX_VALUE) // saturated
777     break;
778     }
779     Node n = p.next;
780     if (n != p)
781     p = n;
782     else {
783     count = 0;
784     p = head;
785     }
786     }
787     return count;
788     }
789    
790     final class Itr implements Iterator<E> {
791     private Node nextNode; // next node to return item for
792     private E nextItem; // the corresponding item
793     private Node lastRet; // last returned node, to support remove
794     private Node lastPred; // predecessor to unlink lastRet
795    
796     /**
797     * Moves to next node after prev, or first node if prev null.
798     */
799     private void advance(Node prev) {
800     /*
801     * To track and avoid buildup of deleted nodes in the face
802     * of calls to both Queue.remove and Itr.remove, we must
803     * include variants of unsplice and sweep upon each
804     * advance: Upon Itr.remove, we may need to catch up links
805     * from lastPred, and upon other removes, we might need to
806     * skip ahead from stale nodes and unsplice deleted ones
807     * found while advancing.
808     */
809    
810     Node r, b; // reset lastPred upon possible deletion of lastRet
811     if ((r = lastRet) != null && !r.isMatched())
812     lastPred = r; // next lastPred is old lastRet
813     else if ((b = lastPred) == null || b.isMatched())
814     lastPred = null; // at start of list
815     else {
816     Node s, n; // help with removal of lastPred.next
817     while ((s = b.next) != null &&
818     s != b && s.isMatched() &&
819     (n = s.next) != null && n != s)
820     b.casNext(s, n);
821     }
822    
823     this.lastRet = prev;
824    
825     for (Node p = prev, s, n;;) {
826     s = (p == null) ? head : p.next;
827     if (s == null)
828     break;
829     else if (s == p) {
830     p = null;
831     continue;
832     }
833     Object item = s.item;
834     if (s.isData) {
835     if (item != null && item != s) {
836     nextItem = LinkedTransferQueue.<E>cast(item);
837     nextNode = s;
838     return;
839     }
840     }
841     else if (item == null)
842     break;
843     // assert s.isMatched();
844     if (p == null)
845     p = s;
846     else if ((n = s.next) == null)
847     break;
848     else if (s == n)
849     p = null;
850     else
851     p.casNext(s, n);
852     }
853     nextNode = null;
854     nextItem = null;
855     }
856    
857     Itr() {
858     advance(null);
859     }
860    
861     public final boolean hasNext() {
862     return nextNode != null;
863     }
864    
865     public final E next() {
866     Node p = nextNode;
867     if (p == null) throw new NoSuchElementException();
868     E e = nextItem;
869     advance(p);
870     return e;
871     }
872    
873     public final void remove() {
874     final Node lastRet = this.lastRet;
875     if (lastRet == null)
876     throw new IllegalStateException();
877     this.lastRet = null;
878     if (lastRet.tryMatchData())
879     unsplice(lastPred, lastRet);
880     }
881     }
882    
883     /* -------------- Removal methods -------------- */
884    
885     /**
886     * Unsplices (now or later) the given deleted/cancelled node with
887     * the given predecessor.
888     *
889     * @param pred a node that was at one time known to be the
890     * predecessor of s, or null or s itself if s is/was at head
891     * @param s the node to be unspliced
892     */
893     final void unsplice(Node pred, Node s) {
894     s.forgetContents(); // forget unneeded fields
895     /*
896     * See above for rationale. Briefly: if pred still points to
897     * s, try to unlink s. If s cannot be unlinked, because it is
898     * trailing node or pred might be unlinked, and neither pred
899     * nor s are head or offlist, add to sweepVotes, and if enough
900     * votes have accumulated, sweep.
901     */
902     if (pred != null && pred != s && pred.next == s) {
903     Node n = s.next;
904     if (n == null ||
905     (n != s && pred.casNext(s, n) && pred.isMatched())) {
906     for (;;) { // check if at, or could be, head
907     Node h = head;
908     if (h == pred || h == s || h == null)
909     return; // at head or list empty
910     if (!h.isMatched())
911     break;
912     Node hn = h.next;
913     if (hn == null)
914     return; // now empty
915     if (hn != h && casHead(h, hn))
916     h.forgetNext(); // advance head
917     }
918     if (pred.next != pred && s.next != s) { // recheck if offlist
919     for (;;) { // sweep now if enough votes
920     int v = sweepVotes;
921     if (v < SWEEP_THRESHOLD) {
922     if (casSweepVotes(v, v + 1))
923     break;
924     }
925     else if (casSweepVotes(v, 0)) {
926     sweep();
927     break;
928     }
929     }
930     }
931     }
932     }
933     }
934    
935     /**
936     * Unlinks matched (typically cancelled) nodes encountered in a
937     * traversal from head.
938     */
939     private void sweep() {
940     for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
941     if (!s.isMatched())
942     // Unmatched nodes are never self-linked
943     p = s;
944     else if ((n = s.next) == null) // trailing node is pinned
945     break;
946     else if (s == n) // stale
947     // No need to also check for p == s, since that implies s == n
948     p = head;
949     else
950     p.casNext(s, n);
951     }
952     }
953    
954     /**
955     * Main implementation of remove(Object)
956     */
957     private boolean findAndRemove(Object e) {
958     if (e != null) {
959     for (Node pred = null, p = head; p != null; ) {
960     Object item = p.item;
961     if (p.isData) {
962     if (item != null && item != p && e.equals(item) &&
963     p.tryMatchData()) {
964     unsplice(pred, p);
965     return true;
966     }
967     }
968     else if (item == null)
969     break;
970     pred = p;
971     if ((p = p.next) == pred) { // stale
972     pred = null;
973     p = head;
974     }
975     }
976     }
977     return false;
978     }
979    
980     /**
981     * Creates an initially empty {@code LinkedTransferQueue}.
982     */
983     public LinkedTransferQueue() {
984     }
985    
986     /**
987     * Creates a {@code LinkedTransferQueue}
988     * initially containing the elements of the given collection,
989     * added in traversal order of the collection's iterator.
990     *
991     * @param c the collection of elements to initially contain
992     * @throws NullPointerException if the specified collection or any
993     * of its elements are null
994     */
995     public LinkedTransferQueue(Collection<? extends E> c) {
996     this();
997     addAll(c);
998     }
999    
1000     /**
1001     * Inserts the specified element at the tail of this queue.
1002     * As the queue is unbounded, this method will never block.
1003     *
1004     * @throws NullPointerException if the specified element is null
1005     */
1006     public void put(E e) {
1007     xfer(e, true, ASYNC, 0);
1008     }
1009    
1010     /**
1011     * Inserts the specified element at the tail of this queue.
1012     * As the queue is unbounded, this method will never block or
1013     * return {@code false}.
1014     *
1015     * @return {@code true} (as specified by
1016     * {@link java.util.concurrent.BlockingQueue#offer(Object,long,TimeUnit)
1017     * BlockingQueue.offer})
1018     * @throws NullPointerException if the specified element is null
1019     */
1020     public boolean offer(E e, long timeout, TimeUnit unit) {
1021     xfer(e, true, ASYNC, 0);
1022     return true;
1023     }
1024    
1025     /**
1026     * Inserts the specified element at the tail of this queue.
1027     * As the queue is unbounded, this method will never return {@code false}.
1028     *
1029     * @return {@code true} (as specified by {@link Queue#offer})
1030     * @throws NullPointerException if the specified element is null
1031     */
1032     public boolean offer(E e) {
1033     xfer(e, true, ASYNC, 0);
1034     return true;
1035     }
1036    
1037     /**
1038     * Inserts the specified element at the tail of this queue.
1039     * As the queue is unbounded, this method will never throw
1040     * {@link IllegalStateException} or return {@code false}.
1041     *
1042     * @return {@code true} (as specified by {@link Collection#add})
1043     * @throws NullPointerException if the specified element is null
1044     */
1045     public boolean add(E e) {
1046     xfer(e, true, ASYNC, 0);
1047     return true;
1048     }
1049    
1050     /**
1051     * Transfers the element to a waiting consumer immediately, if possible.
1052     *
1053     * <p>More precisely, transfers the specified element immediately
1054     * if there exists a consumer already waiting to receive it (in
1055     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1056     * otherwise returning {@code false} without enqueuing the element.
1057     *
1058     * @throws NullPointerException if the specified element is null
1059     */
1060     public boolean tryTransfer(E e) {
1061     return xfer(e, true, NOW, 0) == null;
1062     }
1063    
1064     /**
1065     * Transfers the element to a consumer, waiting if necessary to do so.
1066     *
1067     * <p>More precisely, transfers the specified element immediately
1068     * if there exists a consumer already waiting to receive it (in
1069     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1070     * else inserts the specified element at the tail of this queue
1071     * and waits until the element is received by a consumer.
1072     *
1073     * @throws NullPointerException if the specified element is null
1074     */
1075     public void transfer(E e) throws InterruptedException {
1076     if (xfer(e, true, SYNC, 0) != null) {
1077     Thread.interrupted(); // failure possible only due to interrupt
1078     throw new InterruptedException();
1079     }
1080     }
1081    
1082     /**
1083     * Transfers the element to a consumer if it is possible to do so
1084     * before the timeout elapses.
1085     *
1086     * <p>More precisely, transfers the specified element immediately
1087     * if there exists a consumer already waiting to receive it (in
1088     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1089     * else inserts the specified element at the tail of this queue
1090     * and waits until the element is received by a consumer,
1091     * returning {@code false} if the specified wait time elapses
1092     * before the element can be transferred.
1093     *
1094     * @throws NullPointerException if the specified element is null
1095     */
1096     public boolean tryTransfer(E e, long timeout, TimeUnit unit)
1097     throws InterruptedException {
1098     if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
1099     return true;
1100     if (!Thread.interrupted())
1101     return false;
1102     throw new InterruptedException();
1103     }
1104    
1105     public E take() throws InterruptedException {
1106     E e = xfer(null, false, SYNC, 0);
1107     if (e != null)
1108     return e;
1109     Thread.interrupted();
1110     throw new InterruptedException();
1111     }
1112    
1113     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
1114     E e = xfer(null, false, TIMED, unit.toNanos(timeout));
1115     if (e != null || !Thread.interrupted())
1116     return e;
1117     throw new InterruptedException();
1118     }
1119    
1120     public E poll() {
1121     return xfer(null, false, NOW, 0);
1122     }
1123    
1124     /**
1125     * @throws NullPointerException {@inheritDoc}
1126     * @throws IllegalArgumentException {@inheritDoc}
1127     */
1128     public int drainTo(Collection<? super E> c) {
1129     if (c == null)
1130     throw new NullPointerException();
1131     if (c == this)
1132     throw new IllegalArgumentException();
1133     int n = 0;
1134     for (E e; (e = poll()) != null;) {
1135     c.add(e);
1136     ++n;
1137     }
1138     return n;
1139     }
1140    
1141     /**
1142     * @throws NullPointerException {@inheritDoc}
1143     * @throws IllegalArgumentException {@inheritDoc}
1144     */
1145     public int drainTo(Collection<? super E> c, int maxElements) {
1146     if (c == null)
1147     throw new NullPointerException();
1148     if (c == this)
1149     throw new IllegalArgumentException();
1150     int n = 0;
1151     for (E e; n < maxElements && (e = poll()) != null;) {
1152     c.add(e);
1153     ++n;
1154     }
1155     return n;
1156     }
1157    
1158     /**
1159     * Returns an iterator over the elements in this queue in proper sequence.
1160     * The elements will be returned in order from first (head) to last (tail).
1161     *
1162     * <p>The returned iterator is a "weakly consistent" iterator that
1163     * will never throw {@link java.util.ConcurrentModificationException
1164     * ConcurrentModificationException}, and guarantees to traverse
1165     * elements as they existed upon construction of the iterator, and
1166     * may (but is not guaranteed to) reflect any modifications
1167     * subsequent to construction.
1168     *
1169     * @return an iterator over the elements in this queue in proper sequence
1170     */
1171     public Iterator<E> iterator() {
1172     return new Itr();
1173     }
1174    
1175     public E peek() {
1176     return firstDataItem();
1177     }
1178    
1179     /**
1180     * Returns {@code true} if this queue contains no elements.
1181     *
1182     * @return {@code true} if this queue contains no elements
1183     */
1184     public boolean isEmpty() {
1185     for (Node p = head; p != null; p = succ(p)) {
1186     if (!p.isMatched())
1187     return !p.isData;
1188     }
1189     return true;
1190     }
1191    
1192     public boolean hasWaitingConsumer() {
1193     return firstOfMode(false) != null;
1194     }
1195    
1196     /**
1197     * Returns the number of elements in this queue. If this queue
1198     * contains more than {@code Integer.MAX_VALUE} elements, returns
1199     * {@code Integer.MAX_VALUE}.
1200     *
1201     * <p>Beware that, unlike in most collections, this method is
1202     * <em>NOT</em> a constant-time operation. Because of the
1203     * asynchronous nature of these queues, determining the current
1204     * number of elements requires an O(n) traversal.
1205     *
1206     * @return the number of elements in this queue
1207     */
1208     public int size() {
1209     return countOfMode(true);
1210     }
1211    
1212     public int getWaitingConsumerCount() {
1213     return countOfMode(false);
1214     }
1215    
1216     /**
1217     * Removes a single instance of the specified element from this queue,
1218     * if it is present. More formally, removes an element {@code e} such
1219     * that {@code o.equals(e)}, if this queue contains one or more such
1220     * elements.
1221     * Returns {@code true} if this queue contained the specified element
1222     * (or equivalently, if this queue changed as a result of the call).
1223     *
1224     * @param o element to be removed from this queue, if present
1225     * @return {@code true} if this queue changed as a result of the call
1226     */
1227     public boolean remove(Object o) {
1228     return findAndRemove(o);
1229     }
1230    
1231     /**
1232     * Returns {@code true} if this queue contains the specified element.
1233     * More formally, returns {@code true} if and only if this queue contains
1234     * at least one element {@code e} such that {@code o.equals(e)}.
1235     *
1236     * @param o object to be checked for containment in this queue
1237     * @return {@code true} if this queue contains the specified element
1238     */
1239     public boolean contains(Object o) {
1240     if (o == null) return false;
1241     for (Node p = head; p != null; p = succ(p)) {
1242     Object item = p.item;
1243     if (p.isData) {
1244     if (item != null && item != p && o.equals(item))
1245     return true;
1246     }
1247     else if (item == null)
1248     break;
1249     }
1250     return false;
1251     }
1252    
1253     /**
1254     * Always returns {@code Integer.MAX_VALUE} because a
1255     * {@code LinkedTransferQueue} is not capacity constrained.
1256     *
1257     * @return {@code Integer.MAX_VALUE} (as specified by
1258     * {@link java.util.concurrent.BlockingQueue#remainingCapacity()
1259     * BlockingQueue.remainingCapacity})
1260     */
1261     public int remainingCapacity() {
1262     return Integer.MAX_VALUE;
1263     }
1264    
1265     /**
1266     * Saves this queue to a stream (that is, serializes it).
1267     *
1268     * @serialData All of the elements (each an {@code E}) in
1269     * the proper order, followed by a null
1270     */
1271     private void writeObject(java.io.ObjectOutputStream s)
1272     throws java.io.IOException {
1273     s.defaultWriteObject();
1274     for (E e : this)
1275     s.writeObject(e);
1276     // Use trailing null as sentinel
1277     s.writeObject(null);
1278     }
1279    
1280     /**
1281     * Reconstitutes this queue from a stream (that is, deserializes it).
1282     */
1283     private void readObject(java.io.ObjectInputStream s)
1284     throws java.io.IOException, ClassNotFoundException {
1285     s.defaultReadObject();
1286     for (;;) {
1287     @SuppressWarnings("unchecked")
1288     E item = (E) s.readObject();
1289     if (item == null)
1290     break;
1291     else
1292     offer(item);
1293     }
1294     }
1295    
1296     // Unsafe mechanics
1297    
1298     private static final sun.misc.Unsafe UNSAFE;
1299     private static final long headOffset;
1300     private static final long tailOffset;
1301     private static final long sweepVotesOffset;
1302     static {
1303     try {
1304     UNSAFE = sun.misc.Unsafe.getUnsafe();
1305     Class<?> k = LinkedTransferQueue.class;
1306     headOffset = UNSAFE.objectFieldOffset
1307     (k.getDeclaredField("head"));
1308     tailOffset = UNSAFE.objectFieldOffset
1309     (k.getDeclaredField("tail"));
1310     sweepVotesOffset = UNSAFE.objectFieldOffset
1311     (k.getDeclaredField("sweepVotes"));
1312     } catch (Exception e) {
1313     throw new Error(e);
1314     }
1315 jsr166 1.4
1316     // Reduce the risk of rare disastrous classloading in first call to
1317     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1318     Class<?> ensureLoaded = LockSupport.class;
1319 dl 1.1 }
1320     }