ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.138
Committed: Sun Jan 8 03:48:36 2017 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.137: +8 -7 lines
Log Message:
save a few volatile reads

File Contents

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