ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.61
Committed: Wed Mar 27 19:46:34 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.60: +1 -1 lines
Log Message:
conform to updated lambda Spliterator

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