ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.122
Committed: Sat Dec 24 20:30:51 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.121: +2 -6 lines
Log Message:
loop code golf

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