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