ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.129
Committed: Thu Dec 29 07:30:28 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.128: +1 -3 lines
Log Message:
xfer: remove conditional initialization for s

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