ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.119
Committed: Wed Dec 28 02:22:26 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.118: +2 -4 lines
Log Message:
standardize on restartFromHead label

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