ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.80
Committed: Sat Nov 13 15:47:01 2010 UTC (13 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.79: +84 -23 lines
Log Message:
Iterator consistency and unsplicing

File Contents

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