ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.76
Committed: Wed Dec 31 07:54:14 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.75: +2 -3 lines
Log Message:
standardize import statement order

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