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