ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.145
Committed: Mon Jan 16 00:57:48 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.144: +2 -4 lines
Log Message:
tryAppend: go directly to head on self-link

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