ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.110
Committed: Sat Dec 24 18:37:26 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.109: +3 -11 lines
Log Message:
remove succ(Node) abstraction

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