ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.78
Committed: Wed Jun 8 00:50:35 2011 UTC (13 years ago) by jsr166
Branch: MAIN
Changes since 1.77: +0 -1 lines
Log Message:
clean up imports

File Contents

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