ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.127
Committed: Mon Oct 1 00:10:53 2018 UTC (5 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.126: +1 -1 lines
Log Message:
update to using jdk11 by default, except link to jdk10 javadocs;
sync @docRoot references in javadoc with upstream

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