ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.153
Committed: Wed Jan 18 23:40:58 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.152: +59 -104 lines
Log Message:
xfer: rewrite to avoid theoretical race where fast-forward to tail skips matchable nodes

File Contents

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