ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.141
Committed: Sat Jan 14 21:14:47 2017 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.140: +6 -5 lines
Log Message:
use inline assignment

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