1 /* 2 * Written by Doug Lea, Bill Scherer, and Michael Scott with 3 * assistance from members of JCP JSR-166 Expert Group and released to 4 * the public domain, as explained at 5 * http://creativecommons.org/licenses/publicdomain 6 */ 7 8 package java.util.concurrent; 9 10 import java.util.AbstractQueue; 11 import java.util.Collection; 12 import java.util.Collections; 13 import java.util.Iterator; 14 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; 15 import java.util.concurrent.locks.LockSupport; 16 import java.util.concurrent.locks.ReentrantLock; 17 18 // BEGIN android-note 19 // removed link to collections framework docs 20 // END android-note 21 22 /** 23 * A {@linkplain BlockingQueue blocking queue} in which each insert 24 * operation must wait for a corresponding remove operation by another 25 * thread, and vice versa. A synchronous queue does not have any 26 * internal capacity, not even a capacity of one. You cannot 27 * <tt>peek</tt> at a synchronous queue because an element is only 28 * present when you try to remove it; you cannot insert an element 29 * (using any method) unless another thread is trying to remove it; 30 * you cannot iterate as there is nothing to iterate. The 31 * <em>head</em> of the queue is the element that the first queued 32 * inserting thread is trying to add to the queue; if there is no such 33 * queued thread then no element is available for removal and 34 * <tt>poll()</tt> will return <tt>null</tt>. For purposes of other 35 * <tt>Collection</tt> methods (for example <tt>contains</tt>), a 36 * <tt>SynchronousQueue</tt> acts as an empty collection. This queue 37 * does not permit <tt>null</tt> elements. 38 * 39 * <p>Synchronous queues are similar to rendezvous channels used in 40 * CSP and Ada. They are well suited for handoff designs, in which an 41 * object running in one thread must sync up with an object running 42 * in another thread in order to hand it some information, event, or 43 * task. 44 * 45 * <p> This class supports an optional fairness policy for ordering 46 * waiting producer and consumer threads. By default, this ordering 47 * is not guaranteed. However, a queue constructed with fairness set 48 * to <tt>true</tt> grants threads access in FIFO order. 49 * 50 * <p>This class and its iterator implement all of the 51 * <em>optional</em> methods of the {@link Collection} and {@link 52 * Iterator} interfaces. 53 * 54 * @since 1.5 55 * @author Doug Lea and Bill Scherer and Michael Scott 56 * @param <E> the type of elements held in this collection 57 */ 58 public class SynchronousQueue<E> extends AbstractQueue<E> 59 implements BlockingQueue<E>, java.io.Serializable { 60 private static final long serialVersionUID = -3223113410248163686L; 61 62 /* 63 * This class implements extensions of the dual stack and dual 64 * queue algorithms described in "Nonblocking Concurrent Objects 65 * with Condition Synchronization", by W. N. Scherer III and 66 * M. L. Scott. 18th Annual Conf. on Distributed Computing, 67 * Oct. 2004 (see also 68 * http://www.cs.rochester.edu/u/scott/synchronization/pseudocode/duals.html). 69 * The (Lifo) stack is used for non-fair mode, and the (Fifo) 70 * queue for fair mode. The performance of the two is generally 71 * similar. Fifo usually supports higher throughput under 72 * contention but Lifo maintains higher thread locality in common 73 * applications. 74 * 75 * A dual queue (and similarly stack) is one that at any given 76 * time either holds "data" -- items provided by put operations, 77 * or "requests" -- slots representing take operations, or is 78 * empty. A call to "fulfill" (i.e., a call requesting an item 79 * from a queue holding data or vice versa) dequeues a 80 * complementary node. The most interesting feature of these 81 * queues is that any operation can figure out which mode the 82 * queue is in, and act accordingly without needing locks. 83 * 84 * Both the queue and stack extend abstract class Transferer 85 * defining the single method transfer that does a put or a 86 * take. These are unified into a single method because in dual 87 * data structures, the put and take operations are symmetrical, 88 * so nearly all code can be combined. The resulting transfer 89 * methods are on the long side, but are easier to follow than 90 * they would be if broken up into nearly-duplicated parts. 91 * 92 * The queue and stack data structures share many conceptual 93 * similarities but very few concrete details. For simplicity, 94 * they are kept distinct so that they can later evolve 95 * separately. 96 * 97 * The algorithms here differ from the versions in the above paper 98 * in extending them for use in synchronous queues, as well as 99 * dealing with cancellation. The main differences include: 100 * 101 * 1. The original algorithms used bit-marked pointers, but 102 * the ones here use mode bits in nodes, leading to a number 103 * of further adaptations. 104 * 2. SynchronousQueues must block threads waiting to become 105 * fulfilled. 106 * 3. Support for cancellation via timeout and interrupts, 107 * including cleaning out cancelled nodes/threads 108 * from lists to avoid garbage retention and memory depletion. 109 * 110 * Blocking is mainly accomplished using LockSupport park/unpark, 111 * except that nodes that appear to be the next ones to become 112 * fulfilled first spin a bit (on multiprocessors only). On very 113 * busy synchronous queues, spinning can dramatically improve 114 * throughput. And on less busy ones, the amount of spinning is 115 * small enough not to be noticeable. 116 * 117 * Cleaning is done in different ways in queues vs stacks. For 118 * queues, we can almost always remove a node immediately in O(1) 119 * time (modulo retries for consistency checks) when it is 120 * cancelled. But if it may be pinned as the current tail, it must 121 * wait until some subsequent cancellation. For stacks, we need a 122 * potentially O(n) traversal to be sure that we can remove the 123 * node, but this can run concurrently with other threads 124 * accessing the stack. 125 * 126 * While garbage collection takes care of most node reclamation 127 * issues that otherwise complicate nonblocking algorithms, care 128 * is taken to "forget" references to data, other nodes, and 129 * threads that might be held on to long-term by blocked 130 * threads. In cases where setting to null would otherwise 131 * conflict with main algorithms, this is done by changing a 132 * node's link to now point to the node itself. This doesn't arise 133 * much for Stack nodes (because blocked threads do not hang on to 134 * old head pointers), but references in Queue nodes must be 135 * aggressively forgotten to avoid reachability of everything any 136 * node has ever referred to since arrival. 137 */ 138 139 /** 140 * Shared internal API for dual stacks and queues. 141 */ 142 static abstract class Transferer { 143 /** 144 * Performs a put or take. 145 * 146 * @param e if non-null, the item to be handed to a consumer; 147 * if null, requests that transfer return an item 148 * offered by producer. 149 * @param timed if this operation should timeout 150 * @param nanos the timeout, in nanoseconds 151 * @return if non-null, the item provided or received; if null, 152 * the operation failed due to timeout or interrupt -- 153 * the caller can distinguish which of these occurred 154 * by checking Thread.interrupted. 155 */ 156 abstract Object transfer(Object e, boolean timed, long nanos); 157 } 158 159 /** The number of CPUs, for spin control */ 160 static final int NCPUS = Runtime.getRuntime().availableProcessors(); 161 162 /** 163 * The number of times to spin before blocking in timed waits. 164 * The value is empirically derived -- it works well across a 165 * variety of processors and OSes. Empirically, the best value 166 * seems not to vary with number of CPUs (beyond 2) so is just 167 * a constant. 168 */ 169 static final int maxTimedSpins = (NCPUS < 2)? 0 : 32; 170 171 /** 172 * The number of times to spin before blocking in untimed waits. 173 * This is greater than timed value because untimed waits spin 174 * faster since they don't need to check times on each spin. 175 */ 176 static final int maxUntimedSpins = maxTimedSpins * 16; 177 178 /** 179 * The number of nanoseconds for which it is faster to spin 180 * rather than to use timed park. A rough estimate suffices. 181 */ 182 static final long spinForTimeoutThreshold = 1000L; 183 184 /** Dual stack */ 185 static final class TransferStack extends Transferer { 186 /* 187 * This extends Scherer-Scott dual stack algorithm, differing, 188 * among other ways, by using "covering" nodes rather than 189 * bit-marked pointers: Fulfilling operations push on marker 190 * nodes (with FULFILLING bit set in mode) to reserve a spot 191 * to match a waiting node. 192 */ 193 194 /* Modes for SNodes, ORed together in node fields */ 195 /** Node represents an unfulfilled consumer */ 196 static final int REQUEST = 0; 197 /** Node represents an unfulfilled producer */ 198 static final int DATA = 1; 199 /** Node is fulfilling another unfulfilled DATA or REQUEST */ 200 static final int FULFILLING = 2; 201 202 /** Return true if m has fulfilling bit set */ 203 static boolean isFulfilling(int m) { return (m & FULFILLING) != 0; } 204 205 /** Node class for TransferStacks. */ 206 static final class SNode { 207 volatile SNode next; // next node in stack 208 volatile SNode match; // the node matched to this 209 volatile Thread waiter; // to control park/unpark 210 Object item; // data; or null for REQUESTs 211 int mode; 212 // Note: item and mode fields don't need to be volatile 213 // since they are always written before, and read after, 214 // other volatile/atomic operations. 215 216 SNode(Object item) { 217 this.item = item; 218 } 219 220 static final AtomicReferenceFieldUpdater<SNode, SNode> 221 nextUpdater = AtomicReferenceFieldUpdater.newUpdater 222 (SNode.class, SNode.class, "next"); 223 224 boolean casNext(SNode cmp, SNode val) { 225 return (cmp == next && 226 nextUpdater.compareAndSet(this, cmp, val)); 227 } 228 229 static final AtomicReferenceFieldUpdater<SNode, SNode> 230 matchUpdater = AtomicReferenceFieldUpdater.newUpdater 231 (SNode.class, SNode.class, "match"); 232 233 /** 234 * Tries to match node s to this node, if so, waking up thread. 235 * Fulfillers call tryMatch to identify their waiters. 236 * Waiters block until they have been matched. 237 * 238 * @param s the node to match 239 * @return true if successfully matched to s 240 */ 241 boolean tryMatch(SNode s) { 242 if (match == null && 243 matchUpdater.compareAndSet(this, null, s)) { 244 Thread w = waiter; 245 if (w != null) { // waiters need at most one unpark 246 waiter = null; 247 LockSupport.unpark(w); 248 } 249 return true; 250 } 251 return match == s; 252 } 253 254 /** 255 * Tries to cancel a wait by matching node to itself. 256 */ 257 void tryCancel() { 258 matchUpdater.compareAndSet(this, null, this); 259 } 260 261 boolean isCancelled() { 262 return match == this; 263 } 264 } 265 266 /** The head (top) of the stack */ 267 volatile SNode head; 268 269 static final AtomicReferenceFieldUpdater<TransferStack, SNode> 270 headUpdater = AtomicReferenceFieldUpdater.newUpdater 271 (TransferStack.class, SNode.class, "head"); 272 273 boolean casHead(SNode h, SNode nh) { 274 return h == head && headUpdater.compareAndSet(this, h, nh); 275 } 276 277 /** 278 * Creates or resets fields of a node. Called only from transfer 279 * where the node to push on stack is lazily created and 280 * reused when possible to help reduce intervals between reads 281 * and CASes of head and to avoid surges of garbage when CASes 282 * to push nodes fail due to contention. 283 */ 284 static SNode snode(SNode s, Object e, SNode next, int mode) { 285 if (s == null) s = new SNode(e); 286 s.mode = mode; 287 s.next = next; 288 return s; 289 } 290 291 /** 292 * Puts or takes an item. 293 */ 294 Object transfer(Object e, boolean timed, long nanos) { 295 /* 296 * Basic algorithm is to loop trying one of three actions: 297 * 298 * 1. If apparently empty or already containing nodes of same 299 * mode, try to push node on stack and wait for a match, 300 * returning it, or null if cancelled. 301 * 302 * 2. If apparently containing node of complementary mode, 303 * try to push a fulfilling node on to stack, match 304 * with corresponding waiting node, pop both from 305 * stack, and return matched item. The matching or 306 * unlinking might not actually be necessary because of 307 * other threads performing action 3: 308 * 309 * 3. If top of stack already holds another fulfilling node, 310 * help it out by doing its match and/or pop 311 * operations, and then continue. The code for helping 312 * is essentially the same as for fulfilling, except 313 * that it doesn't return the item. 314 */ 315 316 SNode s = null; // constructed/reused as needed 317 int mode = (e == null)? REQUEST : DATA; 318 319 for (;;) { 320 SNode h = head; 321 if (h == null || h.mode == mode) { // empty or same-mode 322 if (timed && nanos <= 0) { // can't wait 323 if (h != null && h.isCancelled()) 324 casHead(h, h.next); // pop cancelled node 325 else 326 return null; 327 } else if (casHead(h, s = snode(s, e, h, mode))) { 328 SNode m = awaitFulfill(s, timed, nanos); 329 if (m == s) { // wait was cancelled 330 clean(s); 331 return null; 332 } 333 if ((h = head) != null && h.next == s) 334 casHead(h, s.next); // help s's fulfiller 335 return mode == REQUEST? m.item : s.item; 336 } 337 } else if (!isFulfilling(h.mode)) { // try to fulfill 338 if (h.isCancelled()) // already cancelled 339 casHead(h, h.next); // pop and retry 340 else if (casHead(h, s=snode(s, e, h, FULFILLING|mode))) { 341 for (;;) { // loop until matched or waiters disappear 342 SNode m = s.next; // m is s's match 343 if (m == null) { // all waiters are gone 344 casHead(s, null); // pop fulfill node 345 s = null; // use new node next time 346 break; // restart main loop 347 } 348 SNode mn = m.next; 349 if (m.tryMatch(s)) { 350 casHead(s, mn); // pop both s and m 351 return (mode == REQUEST)? m.item : s.item; 352 } else // lost match 353 s.casNext(m, mn); // help unlink 354 } 355 } 356 } else { // help a fulfiller 357 SNode m = h.next; // m is h's match 358 if (m == null) // waiter is gone 359 casHead(h, null); // pop fulfilling node 360 else { 361 SNode mn = m.next; 362 if (m.tryMatch(h)) // help match 363 casHead(h, mn); // pop both h and m 364 else // lost match 365 h.casNext(m, mn); // help unlink 366 } 367 } 368 } 369 } 370 371 /** 372 * Spins/blocks until node s is matched by a fulfill operation. 373 * 374 * @param s the waiting node 375 * @param timed true if timed wait 376 * @param nanos timeout value 377 * @return matched node, or s if cancelled 378 */ 379 SNode awaitFulfill(SNode s, boolean timed, long nanos) { 380 /* 381 * When a node/thread is about to block, it sets its waiter 382 * field and then rechecks state at least one more time 383 * before actually parking, thus covering race vs 384 * fulfiller noticing that waiter is non-null so should be 385 * woken. 386 * 387 * When invoked by nodes that appear at the point of call 388 * to be at the head of the stack, calls to park are 389 * preceded by spins to avoid blocking when producers and 390 * consumers are arriving very close in time. This can 391 * happen enough to bother only on multiprocessors. 392 * 393 * The order of checks for returning out of main loop 394 * reflects fact that interrupts have precedence over 395 * normal returns, which have precedence over 396 * timeouts. (So, on timeout, one last check for match is 397 * done before giving up.) Except that calls from untimed 398 * SynchronousQueue.{poll/offer} don't check interrupts 399 * and don't wait at all, so are trapped in transfer 400 * method rather than calling awaitFulfill. 401 */ 402 long lastTime = (timed)? System.nanoTime() : 0; 403 Thread w = Thread.currentThread(); 404 SNode h = head; 405 int spins = (shouldSpin(s)? 406 (timed? maxTimedSpins : maxUntimedSpins) : 0); 407 for (;;) { 408 if (w.isInterrupted()) 409 s.tryCancel(); 410 SNode m = s.match; 411 if (m != null) 412 return m; 413 if (timed) { 414 long now = System.nanoTime(); 415 nanos -= now - lastTime; 416 lastTime = now; 417 if (nanos <= 0) { 418 s.tryCancel(); 419 continue; 420 } 421 } 422 if (spins > 0) 423 spins = shouldSpin(s)? (spins-1) : 0; 424 else if (s.waiter == null) 425 s.waiter = w; // establish waiter so can park next iter 426 else if (!timed) 427 LockSupport.park(this); 428 else if (nanos > spinForTimeoutThreshold) 429 LockSupport.parkNanos(this, nanos); 430 } 431 } 432 433 /** 434 * Returns true if node s is at head or there is an active 435 * fulfiller. 436 */ 437 boolean shouldSpin(SNode s) { 438 SNode h = head; 439 return (h == s || h == null || isFulfilling(h.mode)); 440 } 441 442 /** 443 * Unlinks s from the stack. 444 */ 445 void clean(SNode s) { 446 s.item = null; // forget item 447 s.waiter = null; // forget thread 448 449 /* 450 * At worst we may need to traverse entire stack to unlink 451 * s. If there are multiple concurrent calls to clean, we 452 * might not see s if another thread has already removed 453 * it. But we can stop when we see any node known to 454 * follow s. We use s.next unless it too is cancelled, in 455 * which case we try the node one past. We don't check any 456 * further because we don't want to doubly traverse just to 457 * find sentinel. 458 */ 459 460 SNode past = s.next; 461 if (past != null && past.isCancelled()) 462 past = past.next; 463 464 // Absorb cancelled nodes at head 465 SNode p; 466 while ((p = head) != null && p != past && p.isCancelled()) 467 casHead(p, p.next); 468 469 // Unsplice embedded nodes 470 while (p != null && p != past) { 471 SNode n = p.next; 472 if (n != null && n.isCancelled()) 473 p.casNext(n, n.next); 474 else 475 p = n; 476 } 477 } 478 } 479 480 /** Dual Queue */ 481 static final class TransferQueue extends Transferer { 482 /* 483 * This extends Scherer-Scott dual queue algorithm, differing, 484 * among other ways, by using modes within nodes rather than 485 * marked pointers. The algorithm is a little simpler than 486 * that for stacks because fulfillers do not need explicit 487 * nodes, and matching is done by CAS'ing QNode.item field 488 * from non-null to null (for put) or vice versa (for take). 489 */ 490 491 /** Node class for TransferQueue. */ 492 static final class QNode { 493 volatile QNode next; // next node in queue 494 volatile Object item; // CAS'ed to or from null 495 volatile Thread waiter; // to control park/unpark 496 final boolean isData; 497 498 QNode(Object item, boolean isData) { 499 this.item = item; 500 this.isData = isData; 501 } 502 503 static final AtomicReferenceFieldUpdater<QNode, QNode> 504 nextUpdater = AtomicReferenceFieldUpdater.newUpdater 505 (QNode.class, QNode.class, "next"); 506 507 boolean casNext(QNode cmp, QNode val) { 508 return (next == cmp && 509 nextUpdater.compareAndSet(this, cmp, val)); 510 } 511 512 static final AtomicReferenceFieldUpdater<QNode, Object> 513 itemUpdater = AtomicReferenceFieldUpdater.newUpdater 514 (QNode.class, Object.class, "item"); 515 516 boolean casItem(Object cmp, Object val) { 517 return (item == cmp && 518 itemUpdater.compareAndSet(this, cmp, val)); 519 } 520 521 /** 522 * Tries to cancel by CAS'ing ref to this as item. 523 */ 524 void tryCancel(Object cmp) { 525 itemUpdater.compareAndSet(this, cmp, this); 526 } 527 528 boolean isCancelled() { 529 return item == this; 530 } 531 532 /** 533 * Returns true if this node is known to be off the queue 534 * because its next pointer has been forgotten due to 535 * an advanceHead operation. 536 */ 537 boolean isOffList() { 538 return next == this; 539 } 540 } 541 542 /** Head of queue */ 543 transient volatile QNode head; 544 /** Tail of queue */ 545 transient volatile QNode tail; 546 /** 547 * Reference to a cancelled node that might not yet have been 548 * unlinked from queue because it was the last inserted node 549 * when it cancelled. 550 */ 551 transient volatile QNode cleanMe; 552 553 TransferQueue() { 554 QNode h = new QNode(null, false); // initialize to dummy node. 555 head = h; 556 tail = h; 557 } 558 559 static final AtomicReferenceFieldUpdater<TransferQueue, QNode> 560 headUpdater = AtomicReferenceFieldUpdater.newUpdater 561 (TransferQueue.class, QNode.class, "head"); 562 563 /** 564 * Tries to cas nh as new head; if successful, unlink 565 * old head's next node to avoid garbage retention. 566 */ 567 void advanceHead(QNode h, QNode nh) { 568 if (h == head && headUpdater.compareAndSet(this, h, nh)) 569 h.next = h; // forget old next 570 } 571 572 static final AtomicReferenceFieldUpdater<TransferQueue, QNode> 573 tailUpdater = AtomicReferenceFieldUpdater.newUpdater 574 (TransferQueue.class, QNode.class, "tail"); 575 576 /** 577 * Tries to cas nt as new tail. 578 */ 579 void advanceTail(QNode t, QNode nt) { 580 if (tail == t) 581 tailUpdater.compareAndSet(this, t, nt); 582 } 583 584 static final AtomicReferenceFieldUpdater<TransferQueue, QNode> 585 cleanMeUpdater = AtomicReferenceFieldUpdater.newUpdater 586 (TransferQueue.class, QNode.class, "cleanMe"); 587 588 /** 589 * Tries to CAS cleanMe slot. 590 */ 591 boolean casCleanMe(QNode cmp, QNode val) { 592 return (cleanMe == cmp && 593 cleanMeUpdater.compareAndSet(this, cmp, val)); 594 } 595 596 /** 597 * Puts or takes an item. 598 */ 599 Object transfer(Object e, boolean timed, long nanos) { 600 /* Basic algorithm is to loop trying to take either of 601 * two actions: 602 * 603 * 1. If queue apparently empty or holding same-mode nodes, 604 * try to add node to queue of waiters, wait to be 605 * fulfilled (or cancelled) and return matching item. 606 * 607 * 2. If queue apparently contains waiting items, and this 608 * call is of complementary mode, try to fulfill by CAS'ing 609 * item field of waiting node and dequeuing it, and then 610 * returning matching item. 611 * 612 * In each case, along the way, check for and try to help 613 * advance head and tail on behalf of other stalled/slow 614 * threads. 615 * 616 * The loop starts off with a null check guarding against 617 * seeing uninitialized head or tail values. This never 618 * happens in current SynchronousQueue, but could if 619 * callers held non-volatile/final ref to the 620 * transferer. The check is here anyway because it places 621 * null checks at top of loop, which is usually faster 622 * than having them implicitly interspersed. 623 */ 624 625 QNode s = null; // constructed/reused as needed 626 boolean isData = (e != null); 627 628 for (;;) { 629 QNode t = tail; 630 QNode h = head; 631 if (t == null || h == null) // saw uninitialized value 632 continue; // spin 633 634 if (h == t || t.isData == isData) { // empty or same-mode 635 QNode tn = t.next; 636 if (t != tail) // inconsistent read 637 continue; 638 if (tn != null) { // lagging tail 639 advanceTail(t, tn); 640 continue; 641 } 642 if (timed && nanos <= 0) // can't wait 643 return null; 644 if (s == null) 645 s = new QNode(e, isData); 646 if (!t.casNext(null, s)) // failed to link in 647 continue; 648 649 advanceTail(t, s); // swing tail and wait 650 Object x = awaitFulfill(s, e, timed, nanos); 651 if (x == s) { // wait was cancelled 652 clean(t, s); 653 return null; 654 } 655 656 if (!s.isOffList()) { // not already unlinked 657 advanceHead(t, s); // unlink if head 658 if (x != null) // and forget fields 659 s.item = s; 660 s.waiter = null; 661 } 662 return (x != null)? x : e; 663 664 } else { // complementary-mode 665 QNode m = h.next; // node to fulfill 666 if (t != tail || m == null || h != head) 667 continue; // inconsistent read 668 669 Object x = m.item; 670 if (isData == (x != null) || // m already fulfilled 671 x == m || // m cancelled 672 !m.casItem(x, e)) { // lost CAS 673 advanceHead(h, m); // dequeue and retry 674 continue; 675 } 676 677 advanceHead(h, m); // successfully fulfilled 678 LockSupport.unpark(m.waiter); 679 return (x != null)? x : e; 680 } 681 } 682 } 683 684 /** 685 * Spins/blocks until node s is fulfilled. 686 * 687 * @param s the waiting node 688 * @param e the comparison value for checking match 689 * @param timed true if timed wait 690 * @param nanos timeout value 691 * @return matched item, or s if cancelled 692 */ 693 Object awaitFulfill(QNode s, Object e, boolean timed, long nanos) { 694 /* Same idea as TransferStack.awaitFulfill */ 695 long lastTime = (timed)? System.nanoTime() : 0; 696 Thread w = Thread.currentThread(); 697 int spins = ((head.next == s) ? 698 (timed? maxTimedSpins : maxUntimedSpins) : 0); 699 for (;;) { 700 if (w.isInterrupted()) 701 s.tryCancel(e); 702 Object x = s.item; 703 if (x != e) 704 return x; 705 if (timed) { 706 long now = System.nanoTime(); 707 nanos -= now - lastTime; 708 lastTime = now; 709 if (nanos <= 0) { 710 s.tryCancel(e); 711 continue; 712 } 713 } 714 if (spins > 0) 715 --spins; 716 else if (s.waiter == null) 717 s.waiter = w; 718 else if (!timed) 719 LockSupport.park(this); 720 else if (nanos > spinForTimeoutThreshold) 721 LockSupport.parkNanos(this, nanos); 722 } 723 } 724 725 /** 726 * Gets rid of cancelled node s with original predecessor pred. 727 */ 728 void clean(QNode pred, QNode s) { 729 s.waiter = null; // forget thread 730 /* 731 * At any given time, exactly one node on list cannot be 732 * deleted -- the last inserted node. To accommodate this, 733 * if we cannot delete s, we save its predecessor as 734 * "cleanMe", deleting the previously saved version 735 * first. At least one of node s or the node previously 736 * saved can always be deleted, so this always terminates. 737 */ 738 while (pred.next == s) { // Return early if already unlinked 739 QNode h = head; 740 QNode hn = h.next; // Absorb cancelled first node as head 741 if (hn != null && hn.isCancelled()) { 742 advanceHead(h, hn); 743 continue; 744 } 745 QNode t = tail; // Ensure consistent read for tail 746 if (t == h) 747 return; 748 QNode tn = t.next; 749 if (t != tail) 750 continue; 751 if (tn != null) { 752 advanceTail(t, tn); 753 continue; 754 } 755 if (s != t) { // If not tail, try to unsplice 756 QNode sn = s.next; 757 if (sn == s || pred.casNext(s, sn)) 758 return; 759 } 760 QNode dp = cleanMe; 761 if (dp != null) { // Try unlinking previous cancelled node 762 QNode d = dp.next; 763 QNode dn; 764 if (d == null || // d is gone or 765 d == dp || // d is off list or 766 !d.isCancelled() || // d not cancelled or 767 (d != t && // d not tail and 768 (dn = d.next) != null && // has successor 769 dn != d && // that is on list 770 dp.casNext(d, dn))) // d unspliced 771 casCleanMe(dp, null); 772 if (dp == pred) 773 return; // s is already saved node 774 } else if (casCleanMe(null, pred)) 775 return; // Postpone cleaning s 776 } 777 } 778 } 779 780 /** 781 * The transferer. Set only in constructor, but cannot be declared 782 * as final without further complicating serialization. Since 783 * this is accessed only at most once per public method, there 784 * isn't a noticeable performance penalty for using volatile 785 * instead of final here. 786 */ 787 private transient volatile Transferer transferer; 788 789 /** 790 * Creates a <tt>SynchronousQueue</tt> with nonfair access policy. 791 */ 792 public SynchronousQueue() { 793 this(false); 794 } 795 796 /** 797 * Creates a <tt>SynchronousQueue</tt> with the specified fairness policy. 798 * 799 * @param fair if true, waiting threads contend in FIFO order for 800 * access; otherwise the order is unspecified. 801 */ 802 public SynchronousQueue(boolean fair) { 803 transferer = (fair)? new TransferQueue() : new TransferStack(); 804 } 805 806 /** 807 * Adds the specified element to this queue, waiting if necessary for 808 * another thread to receive it. 809 * 810 * @throws InterruptedException {@inheritDoc} 811 * @throws NullPointerException {@inheritDoc} 812 */ 813 public void put(E o) throws InterruptedException { 814 if (o == null) throw new NullPointerException(); 815 if (transferer.transfer(o, false, 0) == null) { 816 Thread.interrupted(); 817 throw new InterruptedException(); 818 } 819 } 820 821 /** 822 * Inserts the specified element into this queue, waiting if necessary 823 * up to the specified wait time for another thread to receive it. 824 * 825 * @return <tt>true</tt> if successful, or <tt>false</tt> if the 826 * specified waiting time elapses before a consumer appears. 827 * @throws InterruptedException {@inheritDoc} 828 * @throws NullPointerException {@inheritDoc} 829 */ 830 public boolean offer(E o, long timeout, TimeUnit unit) 831 throws InterruptedException { 832 if (o == null) throw new NullPointerException(); 833 if (transferer.transfer(o, true, unit.toNanos(timeout)) != null) 834 return true; 835 if (!Thread.interrupted()) 836 return false; 837 throw new InterruptedException(); 838 } 839 840 /** 841 * Inserts the specified element into this queue, if another thread is 842 * waiting to receive it. 843 * 844 * @param e the element to add 845 * @return <tt>true</tt> if the element was added to this queue, else 846 * <tt>false</tt> 847 * @throws NullPointerException if the specified element is null 848 */ 849 public boolean offer(E e) { 850 if (e == null) throw new NullPointerException(); 851 return transferer.transfer(e, true, 0) != null; 852 } 853 854 /** 855 * Retrieves and removes the head of this queue, waiting if necessary 856 * for another thread to insert it. 857 * 858 * @return the head of this queue 859 * @throws InterruptedException {@inheritDoc} 860 */ 861 public E take() throws InterruptedException { 862 Object e = transferer.transfer(null, false, 0); 863 if (e != null) 864 return (E)e; 865 Thread.interrupted(); 866 throw new InterruptedException(); 867 } 868 869 /** 870 * Retrieves and removes the head of this queue, waiting 871 * if necessary up to the specified wait time, for another thread 872 * to insert it. 873 * 874 * @return the head of this queue, or <tt>null</tt> if the 875 * specified waiting time elapses before an element is present. 876 * @throws InterruptedException {@inheritDoc} 877 */ 878 public E poll(long timeout, TimeUnit unit) throws InterruptedException { 879 Object e = transferer.transfer(null, true, unit.toNanos(timeout)); 880 if (e != null || !Thread.interrupted()) 881 return (E)e; 882 throw new InterruptedException(); 883 } 884 885 /** 886 * Retrieves and removes the head of this queue, if another thread 887 * is currently making an element available. 888 * 889 * @return the head of this queue, or <tt>null</tt> if no 890 * element is available. 891 */ 892 public E poll() { 893 return (E)transferer.transfer(null, true, 0); 894 } 895 896 /** 897 * Always returns <tt>true</tt>. 898 * A <tt>SynchronousQueue</tt> has no internal capacity. 899 * 900 * @return <tt>true</tt> 901 */ 902 public boolean isEmpty() { 903 return true; 904 } 905 906 /** 907 * Always returns zero. 908 * A <tt>SynchronousQueue</tt> has no internal capacity. 909 * 910 * @return zero. 911 */ 912 public int size() { 913 return 0; 914 } 915 916 /** 917 * Always returns zero. 918 * A <tt>SynchronousQueue</tt> has no internal capacity. 919 * 920 * @return zero. 921 */ 922 public int remainingCapacity() { 923 return 0; 924 } 925 926 /** 927 * Does nothing. 928 * A <tt>SynchronousQueue</tt> has no internal capacity. 929 */ 930 public void clear() { 931 } 932 933 /** 934 * Always returns <tt>false</tt>. 935 * A <tt>SynchronousQueue</tt> has no internal capacity. 936 * 937 * @param o the element 938 * @return <tt>false</tt> 939 */ 940 public boolean contains(Object o) { 941 return false; 942 } 943 944 /** 945 * Always returns <tt>false</tt>. 946 * A <tt>SynchronousQueue</tt> has no internal capacity. 947 * 948 * @param o the element to remove 949 * @return <tt>false</tt> 950 */ 951 public boolean remove(Object o) { 952 return false; 953 } 954 955 /** 956 * Returns <tt>false</tt> unless the given collection is empty. 957 * A <tt>SynchronousQueue</tt> has no internal capacity. 958 * 959 * @param c the collection 960 * @return <tt>false</tt> unless given collection is empty 961 */ 962 public boolean containsAll(Collection<?> c) { 963 return c.isEmpty(); 964 } 965 966 /** 967 * Always returns <tt>false</tt>. 968 * A <tt>SynchronousQueue</tt> has no internal capacity. 969 * 970 * @param c the collection 971 * @return <tt>false</tt> 972 */ 973 public boolean removeAll(Collection<?> c) { 974 return false; 975 } 976 977 /** 978 * Always returns <tt>false</tt>. 979 * A <tt>SynchronousQueue</tt> has no internal capacity. 980 * 981 * @param c the collection 982 * @return <tt>false</tt> 983 */ 984 public boolean retainAll(Collection<?> c) { 985 return false; 986 } 987 988 /** 989 * Always returns <tt>null</tt>. 990 * A <tt>SynchronousQueue</tt> does not return elements 991 * unless actively waited on. 992 * 993 * @return <tt>null</tt> 994 */ 995 public E peek() { 996 return null; 997 } 998 999 /** 1000 * Returns an empty iterator in which <tt>hasNext</tt> always returns 1001 * <tt>false</tt>. 1002 * 1003 * @return an empty iterator 1004 */ 1005 public Iterator<E> iterator() { 1006 return Collections.<E>emptySet().iterator(); // android-changed 1007 } 1008 1009 /** 1010 * Returns a zero-length array. 1011 * @return a zero-length array 1012 */ 1013 public Object[] toArray() { 1014 return new Object[0]; 1015 } 1016 1017 /** 1018 * Sets the zeroeth element of the specified array to <tt>null</tt> 1019 * (if the array has non-zero length) and returns it. 1020 * 1021 * @param a the array 1022 * @return the specified array 1023 * @throws NullPointerException if the specified array is null 1024 */ 1025 public <T> T[] toArray(T[] a) { 1026 if (a.length > 0) 1027 a[0] = null; 1028 return a; 1029 } 1030 1031 /** 1032 * @throws UnsupportedOperationException {@inheritDoc} 1033 * @throws ClassCastException {@inheritDoc} 1034 * @throws NullPointerException {@inheritDoc} 1035 * @throws IllegalArgumentException {@inheritDoc} 1036 */ 1037 public int drainTo(Collection<? super E> c) { 1038 if (c == null) 1039 throw new NullPointerException(); 1040 if (c == this) 1041 throw new IllegalArgumentException(); 1042 int n = 0; 1043 E e; 1044 while ( (e = poll()) != null) { 1045 c.add(e); 1046 ++n; 1047 } 1048 return n; 1049 } 1050 1051 /** 1052 * @throws UnsupportedOperationException {@inheritDoc} 1053 * @throws ClassCastException {@inheritDoc} 1054 * @throws NullPointerException {@inheritDoc} 1055 * @throws IllegalArgumentException {@inheritDoc} 1056 */ 1057 public int drainTo(Collection<? super E> c, int maxElements) { 1058 if (c == null) 1059 throw new NullPointerException(); 1060 if (c == this) 1061 throw new IllegalArgumentException(); 1062 int n = 0; 1063 E e; 1064 while (n < maxElements && (e = poll()) != null) { 1065 c.add(e); 1066 ++n; 1067 } 1068 return n; 1069 } 1070 1071 /* 1072 * To cope with serialization strategy in the 1.5 version of 1073 * SynchronousQueue, we declare some unused classes and fields 1074 * that exist solely to enable serializability across versions. 1075 * These fields are never used, so are initialized only if this 1076 * object is ever serialized or deserialized. 1077 */ 1078 1079 static class WaitQueue implements java.io.Serializable { } 1080 static class LifoWaitQueue extends WaitQueue { 1081 private static final long serialVersionUID = -3633113410248163686L; 1082 } 1083 static class FifoWaitQueue extends WaitQueue { 1084 private static final long serialVersionUID = -3623113410248163686L; 1085 } 1086 private ReentrantLock qlock; 1087 private WaitQueue waitingProducers; 1088 private WaitQueue waitingConsumers; 1089 1090 /** 1091 * Save the state to a stream (that is, serialize it). 1092 * 1093 * @param s the stream 1094 */ 1095 private void writeObject(java.io.ObjectOutputStream s) 1096 throws java.io.IOException { 1097 boolean fair = transferer instanceof TransferQueue; 1098 if (fair) { 1099 qlock = new ReentrantLock(true); 1100 waitingProducers = new FifoWaitQueue(); 1101 waitingConsumers = new FifoWaitQueue(); 1102 } 1103 else { 1104 qlock = new ReentrantLock(); 1105 waitingProducers = new LifoWaitQueue(); 1106 waitingConsumers = new LifoWaitQueue(); 1107 } 1108 s.defaultWriteObject(); 1109 } 1110 1111 private void readObject(final java.io.ObjectInputStream s) 1112 throws java.io.IOException, ClassNotFoundException { 1113 s.defaultReadObject(); 1114 if (waitingProducers instanceof FifoWaitQueue) 1115 transferer = new TransferQueue(); 1116 else 1117 transferer = new TransferStack(); 1118 } 1119 1120 } 1121