ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.112
Committed: Sun Jan 4 09:15:11 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.111: +39 -47 lines
Log Message:
standardize Unsafe mechanics; slightly smaller bytecode

File Contents

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