ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.87
Committed: Tue Jun 9 17:18:05 2015 UTC (8 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.86: +1 -1 lines
Log Message:
whitespace

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