ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.102
Committed: Sat Dec 24 08:44:42 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.101: +5 -2 lines
Log Message:
never unlink an unmatched Node

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