ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.39
Committed: Tue Mar 15 19:47:03 2011 UTC (13 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.38: +1 -1 lines
Log Message:
Update Creative Commons license URL in legal notices

File Contents

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