ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.158
Committed: Sun Jan 7 03:58:45 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.157: +1 -2 lines
Log Message:
remove redundant cast

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