ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.81
Committed: Wed Feb 18 06:39:40 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.80: +1 -3 lines
Log Message:
use "standard" if (p == (p = p.next)) idiom

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