ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.73
Committed: Tue Feb 22 23:53:32 2011 UTC (13 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.72: +63 -25 lines
Log Message:
Reduce dependencies in static initialization

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