ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.113
Committed: Sat Dec 24 20:51:00 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.112: +5 -5 lines
Log Message:
Most uses of firstDataNode are clearer and more efficient if we just hop to head

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