ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.132
Committed: Sun Jan 1 23:17:58 2017 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.131: +4 -4 lines
Log Message:
remove redundant parens

File Contents

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