ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.128
Committed: Thu Jun 4 12:03:50 2020 UTC (4 years ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.127: +167 -201 lines
Log Message:
improve loom-friendliness

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 dl 1.128 *
141     * The above steps improve throughput when many threads produce
142     * and/or consume data. But they don't help much with
143     * single-source / single-sink usages in which one side or the
144     * other is always transiently blocked, and so throughput is
145     * mainly a function of thread scheduling. This is not usually
146     * noticeably improved with bounded short spin-waits. Instead both
147     * forms of transfer try Thread.yield if apparently the sole
148     * waiter. This works well when there are more tasks that cores,
149     * which is expected to be the main usage context of this mode. In
150     * other cases, waiters may help with some bookkeeping, then
151     * park/unpark.
152 dl 1.55 */
153 dl 1.2
154 dl 1.43 /**
155 dl 1.55 * Shared internal API for dual stacks and queues.
156 dl 1.43 */
157 jsr166 1.82 abstract static class Transferer<E> {
158 dl 1.55 /**
159 jsr166 1.59 * Performs a put or take.
160     *
161 dl 1.55 * @param e if non-null, the item to be handed to a consumer;
162 jsr166 1.59 * if null, requests that transfer return an item
163     * offered by producer.
164 dl 1.55 * @param timed if this operation should timeout
165     * @param nanos the timeout, in nanoseconds
166 jsr166 1.59 * @return if non-null, the item provided or received; if null,
167     * the operation failed due to timeout or interrupt --
168     * the caller can distinguish which of these occurred
169     * by checking Thread.interrupted.
170 dl 1.55 */
171 jsr166 1.82 abstract E transfer(E e, boolean timed, long nanos);
172 dl 1.43 }
173    
174     /**
175 dl 1.55 * The number of nanoseconds for which it is faster to spin
176     * rather than to use timed park. A rough estimate suffices.
177 dl 1.43 */
178 dl 1.128 static final long SPIN_FOR_TIMEOUT_THRESHOLD = 1023L;
179 dl 1.55
180 jsr166 1.60 /** Dual stack */
181 jsr166 1.82 static final class TransferStack<E> extends Transferer<E> {
182 dl 1.55 /*
183     * This extends Scherer-Scott dual stack algorithm, differing,
184     * among other ways, by using "covering" nodes rather than
185     * bit-marked pointers: Fulfilling operations push on marker
186     * nodes (with FULFILLING bit set in mode) to reserve a spot
187     * to match a waiting node.
188     */
189 dl 1.43
190 dl 1.55 /* Modes for SNodes, ORed together in node fields */
191     /** Node represents an unfulfilled consumer */
192     static final int REQUEST = 0;
193     /** Node represents an unfulfilled producer */
194     static final int DATA = 1;
195     /** Node is fulfilling another unfulfilled DATA or REQUEST */
196     static final int FULFILLING = 2;
197    
198 jsr166 1.87 /** Returns true if m has fulfilling bit set. */
199 dl 1.55 static boolean isFulfilling(int m) { return (m & FULFILLING) != 0; }
200    
201     /** Node class for TransferStacks. */
202 dl 1.128 static final class SNode implements ForkJoinPool.ManagedBlocker {
203 dl 1.55 volatile SNode next; // next node in stack
204     volatile SNode match; // the node matched to this
205     volatile Thread waiter; // to control park/unpark
206     Object item; // data; or null for REQUESTs
207     int mode;
208     // Note: item and mode fields don't need to be volatile
209     // since they are always written before, and read after,
210     // other volatile/atomic operations.
211    
212     SNode(Object item) {
213     this.item = item;
214     }
215    
216     boolean casNext(SNode cmp, SNode val) {
217 dl 1.69 return cmp == next &&
218 dl 1.120 SNEXT.compareAndSet(this, cmp, val);
219 dl 1.55 }
220    
221     /**
222 jsr166 1.63 * Tries to match node s to this node, if so, waking up thread.
223     * Fulfillers call tryMatch to identify their waiters.
224     * Waiters block until they have been matched.
225     *
226 dl 1.55 * @param s the node to match
227     * @return true if successfully matched to s
228     */
229     boolean tryMatch(SNode s) {
230 dl 1.128 SNode m; Thread w;
231     if ((m = match) == null) {
232     if (SMATCH.compareAndSet(this, null, s)) {
233     if ((w = waiter) != null)
234     LockSupport.unpark(w);
235     return true;
236 dl 1.55 }
237 dl 1.128 else
238     m = match;
239 dl 1.47 }
240 dl 1.128 return m == s;
241 dl 1.55 }
242    
243     /**
244 jsr166 1.59 * Tries to cancel a wait by matching node to itself.
245 dl 1.55 */
246 dl 1.128 boolean tryCancel() {
247     return SMATCH.compareAndSet(this, null, this);
248 dl 1.55 }
249    
250     boolean isCancelled() {
251     return match == this;
252 dl 1.47 }
253 dl 1.69
254 dl 1.128 public final boolean isReleasable() {
255     return match != null || Thread.currentThread().isInterrupted();
256     }
257    
258     public final boolean block() {
259     while (!isReleasable()) LockSupport.park();
260     return true;
261     }
262    
263     void forgetWaiter() {
264     SWAITER.setOpaque(this, null);
265     }
266    
267 dl 1.120 // VarHandle mechanics
268     private static final VarHandle SMATCH;
269     private static final VarHandle SNEXT;
270 dl 1.128 private static final VarHandle SWAITER;
271 dl 1.73 static {
272     try {
273 dl 1.120 MethodHandles.Lookup l = MethodHandles.lookup();
274     SMATCH = l.findVarHandle(SNode.class, "match", SNode.class);
275     SNEXT = l.findVarHandle(SNode.class, "next", SNode.class);
276 dl 1.128 SWAITER = l.findVarHandle(SNode.class, "waiter", Thread.class);
277 jsr166 1.111 } catch (ReflectiveOperationException e) {
278 jsr166 1.126 throw new ExceptionInInitializerError(e);
279 dl 1.73 }
280     }
281 dl 1.47 }
282 dl 1.43
283 dl 1.55 /** The head (top) of the stack */
284     volatile SNode head;
285 jsr166 1.70
286 dl 1.55 boolean casHead(SNode h, SNode nh) {
287 jsr166 1.70 return h == head &&
288 dl 1.120 SHEAD.compareAndSet(this, h, nh);
289 dl 1.55 }
290 dl 1.2
291 dl 1.55 /**
292 jsr166 1.57 * Creates or resets fields of a node. Called only from transfer
293 dl 1.55 * where the node to push on stack is lazily created and
294     * reused when possible to help reduce intervals between reads
295     * and CASes of head and to avoid surges of garbage when CASes
296     * to push nodes fail due to contention.
297     */
298     static SNode snode(SNode s, Object e, SNode next, int mode) {
299     if (s == null) s = new SNode(e);
300     s.mode = mode;
301     s.next = next;
302     return s;
303 dl 1.43 }
304    
305 dl 1.55 /**
306 jsr166 1.57 * Puts or takes an item.
307 dl 1.55 */
308 jsr166 1.83 @SuppressWarnings("unchecked")
309 jsr166 1.82 E transfer(E e, boolean timed, long nanos) {
310 dl 1.55 /*
311     * Basic algorithm is to loop trying one of three actions:
312     *
313     * 1. If apparently empty or already containing nodes of same
314     * mode, try to push node on stack and wait for a match,
315     * returning it, or null if cancelled.
316     *
317     * 2. If apparently containing node of complementary mode,
318     * try to push a fulfilling node on to stack, match
319     * with corresponding waiting node, pop both from
320     * stack, and return matched item. The matching or
321     * unlinking might not actually be necessary because of
322 dl 1.62 * other threads performing action 3:
323 dl 1.55 *
324     * 3. If top of stack already holds another fulfilling node,
325     * help it out by doing its match and/or pop
326     * operations, and then continue. The code for helping
327     * is essentially the same as for fulfilling, except
328     * that it doesn't return the item.
329     */
330    
331     SNode s = null; // constructed/reused as needed
332 jsr166 1.72 int mode = (e == null) ? REQUEST : DATA;
333 dl 1.55
334     for (;;) {
335     SNode h = head;
336     if (h == null || h.mode == mode) { // empty or same-mode
337 jsr166 1.118 if (timed && nanos <= 0L) { // can't wait
338 jsr166 1.58 if (h != null && h.isCancelled())
339 dl 1.55 casHead(h, h.next); // pop cancelled node
340     else
341 jsr166 1.58 return null;
342 dl 1.55 } else if (casHead(h, s = snode(s, e, h, mode))) {
343 dl 1.128 long deadline = timed ? System.nanoTime() + nanos : 0L;
344     Thread w = Thread.currentThread();
345     int stat = -1; // -1: may yield, +1: park, else 0
346     SNode m; // await fulfill or cancel
347     while ((m = s.match) == null) {
348     if ((timed &&
349     (nanos = deadline - System.nanoTime()) <= 0) ||
350     w.isInterrupted()) {
351     if (s.tryCancel()) {
352     clean(s); // wait cancelled
353     return null;
354     }
355     } else if ((m = s.match) != null) {
356     break; // recheck
357     } else if (stat <= 0) {
358     if (stat < 0 && h == null && head == s) {
359     stat = 0; // yield once if was empty
360     Thread.yield();
361     } else {
362     stat = 1;
363     s.waiter = w; // enable signal
364     }
365     } else if (!timed) {
366     LockSupport.setCurrentBlocker(this);
367     try {
368     ForkJoinPool.managedBlock(s);
369     } catch (InterruptedException cannotHappen) { }
370     LockSupport.setCurrentBlocker(null);
371     } else if (nanos > SPIN_FOR_TIMEOUT_THRESHOLD)
372     LockSupport.parkNanos(this, nanos);
373 dl 1.55 }
374 dl 1.128 if (stat == 1)
375     s.forgetWaiter();
376     Object result = (mode == REQUEST) ? m.item : s.item;
377     if (h != null && h.next == s)
378     casHead(h, s.next); // help fulfiller
379     return (E) result;
380 dl 1.55 }
381     } else if (!isFulfilling(h.mode)) { // try to fulfill
382     if (h.isCancelled()) // already cancelled
383     casHead(h, h.next); // pop and retry
384     else if (casHead(h, s=snode(s, e, h, FULFILLING|mode))) {
385     for (;;) { // loop until matched or waiters disappear
386     SNode m = s.next; // m is s's match
387     if (m == null) { // all waiters are gone
388     casHead(s, null); // pop fulfill node
389     s = null; // use new node next time
390     break; // restart main loop
391     }
392     SNode mn = m.next;
393     if (m.tryMatch(s)) {
394     casHead(s, mn); // pop both s and m
395 jsr166 1.83 return (E) ((mode == REQUEST) ? m.item : s.item);
396 dl 1.55 } else // lost match
397     s.casNext(m, mn); // help unlink
398     }
399     }
400     } else { // help a fulfiller
401     SNode m = h.next; // m is h's match
402     if (m == null) // waiter is gone
403     casHead(h, null); // pop fulfilling node
404     else {
405     SNode mn = m.next;
406     if (m.tryMatch(h)) // help match
407     casHead(h, mn); // pop both h and m
408     else // lost match
409     h.casNext(m, mn); // help unlink
410     }
411 dl 1.47 }
412     }
413     }
414    
415 dl 1.55 /**
416 jsr166 1.57 * Unlinks s from the stack.
417 dl 1.55 */
418     void clean(SNode s) {
419 jsr166 1.58 s.item = null; // forget item
420 dl 1.128 s.forgetWaiter();
421 dl 1.55
422     /*
423     * At worst we may need to traverse entire stack to unlink
424     * s. If there are multiple concurrent calls to clean, we
425     * might not see s if another thread has already removed
426     * it. But we can stop when we see any node known to
427     * follow s. We use s.next unless it too is cancelled, in
428     * which case we try the node one past. We don't check any
429 jsr166 1.59 * further because we don't want to doubly traverse just to
430 dl 1.55 * find sentinel.
431     */
432    
433     SNode past = s.next;
434     if (past != null && past.isCancelled())
435     past = past.next;
436    
437     // Absorb cancelled nodes at head
438     SNode p;
439     while ((p = head) != null && p != past && p.isCancelled())
440     casHead(p, p.next);
441    
442     // Unsplice embedded nodes
443     while (p != null && p != past) {
444     SNode n = p.next;
445     if (n != null && n.isCancelled())
446     p.casNext(n, n.next);
447     else
448     p = n;
449 dl 1.47 }
450     }
451 dl 1.69
452 dl 1.120 // VarHandle mechanics
453     private static final VarHandle SHEAD;
454 dl 1.73 static {
455     try {
456 dl 1.120 MethodHandles.Lookup l = MethodHandles.lookup();
457     SHEAD = l.findVarHandle(TransferStack.class, "head", SNode.class);
458 jsr166 1.111 } catch (ReflectiveOperationException e) {
459 jsr166 1.126 throw new ExceptionInInitializerError(e);
460 dl 1.73 }
461     }
462 dl 1.47 }
463 jsr166 1.48
464 jsr166 1.61 /** Dual Queue */
465 jsr166 1.82 static final class TransferQueue<E> extends Transferer<E> {
466 dl 1.55 /*
467     * This extends Scherer-Scott dual queue algorithm, differing,
468     * among other ways, by using modes within nodes rather than
469     * marked pointers. The algorithm is a little simpler than
470     * that for stacks because fulfillers do not need explicit
471     * nodes, and matching is done by CAS'ing QNode.item field
472 jsr166 1.59 * from non-null to null (for put) or vice versa (for take).
473 dl 1.55 */
474 dl 1.53
475 dl 1.55 /** Node class for TransferQueue. */
476 dl 1.128 static final class QNode implements ForkJoinPool.ManagedBlocker {
477 dl 1.55 volatile QNode next; // next node in queue
478     volatile Object item; // CAS'ed to or from null
479     volatile Thread waiter; // to control park/unpark
480 jsr166 1.58 final boolean isData;
481 dl 1.35
482 dl 1.55 QNode(Object item, boolean isData) {
483     this.item = item;
484     this.isData = isData;
485     }
486 dl 1.35
487 dl 1.55 boolean casNext(QNode cmp, QNode val) {
488 dl 1.69 return next == cmp &&
489 dl 1.120 QNEXT.compareAndSet(this, cmp, val);
490 dl 1.55 }
491    
492     boolean casItem(Object cmp, Object val) {
493 dl 1.69 return item == cmp &&
494 dl 1.120 QITEM.compareAndSet(this, cmp, val);
495 dl 1.55 }
496    
497     /**
498 jsr166 1.59 * Tries to cancel by CAS'ing ref to this as item.
499 dl 1.55 */
500 dl 1.128 boolean tryCancel(Object cmp) {
501     return QITEM.compareAndSet(this, cmp, this);
502 dl 1.55 }
503 jsr166 1.70
504 dl 1.55 boolean isCancelled() {
505     return item == this;
506     }
507 dl 1.56
508 jsr166 1.58 /**
509 jsr166 1.57 * Returns true if this node is known to be off the queue
510 dl 1.56 * because its next pointer has been forgotten due to
511     * an advanceHead operation.
512     */
513     boolean isOffList() {
514     return next == this;
515     }
516 dl 1.74
517 dl 1.128 void forgetWaiter() {
518     QWAITER.setOpaque(this, null);
519     }
520    
521     boolean isFulfilled() {
522     Object x;
523     return isData == ((x = item) == null) || x == this;
524     }
525    
526     public final boolean isReleasable() {
527     Object x;
528     return isData == ((x = item) == null) || x == this ||
529     Thread.currentThread().isInterrupted();
530     }
531    
532     public final boolean block() {
533     while (!isReleasable()) LockSupport.park();
534     return true;
535     }
536    
537 dl 1.120 // VarHandle mechanics
538     private static final VarHandle QITEM;
539     private static final VarHandle QNEXT;
540 dl 1.128 private static final VarHandle QWAITER;
541 dl 1.73 static {
542     try {
543 dl 1.120 MethodHandles.Lookup l = MethodHandles.lookup();
544     QITEM = l.findVarHandle(QNode.class, "item", Object.class);
545     QNEXT = l.findVarHandle(QNode.class, "next", QNode.class);
546 dl 1.128 QWAITER = l.findVarHandle(QNode.class, "waiter", Thread.class);
547 jsr166 1.112 } catch (ReflectiveOperationException e) {
548 jsr166 1.126 throw new ExceptionInInitializerError(e);
549 dl 1.73 }
550     }
551 dl 1.31 }
552    
553 dl 1.55 /** Head of queue */
554     transient volatile QNode head;
555     /** Tail of queue */
556     transient volatile QNode tail;
557 dl 1.31 /**
558 dl 1.55 * Reference to a cancelled node that might not yet have been
559     * unlinked from queue because it was the last inserted node
560 jsr166 1.91 * when it was cancelled.
561 dl 1.31 */
562 dl 1.55 transient volatile QNode cleanMe;
563    
564     TransferQueue() {
565     QNode h = new QNode(null, false); // initialize to dummy node.
566     head = h;
567     tail = h;
568 dl 1.31 }
569    
570     /**
571 jsr166 1.59 * Tries to cas nh as new head; if successful, unlink
572 dl 1.55 * old head's next node to avoid garbage retention.
573 dl 1.31 */
574 dl 1.55 void advanceHead(QNode h, QNode nh) {
575 jsr166 1.70 if (h == head &&
576 dl 1.120 QHEAD.compareAndSet(this, h, nh))
577 dl 1.55 h.next = h; // forget old next
578 dl 1.31 }
579    
580     /**
581 jsr166 1.57 * Tries to cas nt as new tail.
582 dl 1.31 */
583 dl 1.55 void advanceTail(QNode t, QNode nt) {
584     if (tail == t)
585 dl 1.120 QTAIL.compareAndSet(this, t, nt);
586 dl 1.31 }
587 dl 1.2
588     /**
589 jsr166 1.57 * Tries to CAS cleanMe slot.
590 dl 1.2 */
591 dl 1.55 boolean casCleanMe(QNode cmp, QNode val) {
592 dl 1.69 return cleanMe == cmp &&
593 dl 1.120 QCLEANME.compareAndSet(this, cmp, val);
594 dl 1.35 }
595    
596     /**
597 jsr166 1.57 * Puts or takes an item.
598 dl 1.35 */
599 jsr166 1.83 @SuppressWarnings("unchecked")
600 jsr166 1.82 E transfer(E e, boolean timed, long nanos) {
601 jsr166 1.58 /* Basic algorithm is to loop trying to take either of
602 dl 1.55 * two actions:
603     *
604 jsr166 1.58 * 1. If queue apparently empty or holding same-mode nodes,
605 dl 1.55 * try to add node to queue of waiters, wait to be
606     * fulfilled (or cancelled) and return matching item.
607     *
608     * 2. If queue apparently contains waiting items, and this
609     * call is of complementary mode, try to fulfill by CAS'ing
610     * item field of waiting node and dequeuing it, and then
611     * returning matching item.
612     *
613     * In each case, along the way, check for and try to help
614     * advance head and tail on behalf of other stalled/slow
615     * threads.
616     *
617     * The loop starts off with a null check guarding against
618     * seeing uninitialized head or tail values. This never
619     * happens in current SynchronousQueue, but could if
620     * callers held non-volatile/final ref to the
621     * transferer. The check is here anyway because it places
622     * null checks at top of loop, which is usually faster
623     * than having them implicitly interspersed.
624     */
625    
626 dl 1.128 QNode s = null; // constructed/reused as needed
627 dl 1.55 boolean isData = (e != null);
628     for (;;) {
629 dl 1.128 QNode t = tail, h = head, m, tn; // m is node to fulfill
630     if (t == null || h == null)
631     ; // inconsistent
632     else if (h == t || t.isData == isData) { // empty or same-mode
633     if (t != tail) // inconsistent
634     ;
635     else if ((tn = t.next) != null) // lagging tail
636 dl 1.55 advanceTail(t, tn);
637 dl 1.128 else if (timed && nanos <= 0L) // can't wait
638 dl 1.55 return null;
639 dl 1.128 else if (t.casNext(null, (s != null) ? s :
640     (s = new QNode(e, isData)))) {
641     advanceTail(t, s);
642     long deadline = timed ? System.nanoTime() + nanos : 0L;
643     Thread w = Thread.currentThread();
644     int stat = -1; // same idea as TransferStack
645     Object item;
646     while ((item = s.item) == e) {
647     if ((timed &&
648     (nanos = deadline - System.nanoTime()) <= 0) ||
649     w.isInterrupted()) {
650     if (s.tryCancel(e)) {
651     clean(t, s);
652     return null;
653     }
654     } else if ((item = s.item) != e) {
655     break; // recheck
656     } else if (stat <= 0) {
657     if (t.next == s) {
658     if (stat < 0 && t.isFulfilled()) {
659     stat = 0; // yield once if first
660     Thread.yield();
661     }
662     else {
663     stat = 1;
664     s.waiter = w;
665     }
666     }
667     } else if (!timed) {
668     LockSupport.setCurrentBlocker(this);
669     try {
670     ForkJoinPool.managedBlock(s);
671     } catch (InterruptedException cannotHappen) { }
672     LockSupport.setCurrentBlocker(null);
673     }
674     else if (nanos > SPIN_FOR_TIMEOUT_THRESHOLD)
675     LockSupport.parkNanos(this, nanos);
676     }
677     if (stat == 1)
678     s.forgetWaiter();
679     if (!s.isOffList()) { // not already unlinked
680     advanceHead(t, s); // unlink if head
681     if (item != null) // and forget fields
682     s.item = s;
683     }
684     return (item != null) ? (E)item : e;
685 dl 1.55 }
686    
687 dl 1.128 } else if ((m = h.next) != null && t == tail && h == head) {
688     Thread waiter;
689 dl 1.55 Object x = m.item;
690 dl 1.128 boolean fulfilled = ((isData == (x == null)) &&
691     x != m && m.casItem(x, e));
692     advanceHead(h, m); // (help) dequeue
693     if (fulfilled) {
694     if ((waiter = m.waiter) != null)
695     LockSupport.unpark(waiter);
696     return (x != null) ? (E)x : e;
697 dl 1.55 }
698 dl 1.120 }
699 dl 1.35 }
700 dl 1.31 }
701    
702     /**
703 jsr166 1.57 * Gets rid of cancelled node s with original predecessor pred.
704 dl 1.31 */
705 dl 1.55 void clean(QNode pred, QNode s) {
706 dl 1.128 s.forgetWaiter();
707 dl 1.55 /*
708     * At any given time, exactly one node on list cannot be
709     * deleted -- the last inserted node. To accommodate this,
710     * if we cannot delete s, we save its predecessor as
711     * "cleanMe", deleting the previously saved version
712     * first. At least one of node s or the node previously
713     * saved can always be deleted, so this always terminates.
714     */
715     while (pred.next == s) { // Return early if already unlinked
716     QNode h = head;
717     QNode hn = h.next; // Absorb cancelled first node as head
718     if (hn != null && hn.isCancelled()) {
719     advanceHead(h, hn);
720     continue;
721     }
722 jsr166 1.68 QNode t = tail; // Ensure consistent read for tail
723 dl 1.55 if (t == h)
724     return;
725 jsr166 1.68 QNode tn = t.next;
726     if (t != tail)
727 dl 1.55 continue;
728     if (tn != null) {
729     advanceTail(t, tn);
730     continue;
731     }
732     if (s != t) { // If not tail, try to unsplice
733     QNode sn = s.next;
734     if (sn == s || pred.casNext(s, sn))
735     return;
736     }
737     QNode dp = cleanMe;
738     if (dp != null) { // Try unlinking previous cancelled node
739     QNode d = dp.next;
740     QNode dn;
741     if (d == null || // d is gone or
742     d == dp || // d is off list or
743     !d.isCancelled() || // d not cancelled or
744     (d != t && // d not tail and
745     (dn = d.next) != null && // has successor
746     dn != d && // that is on list
747     dp.casNext(d, dn))) // d unspliced
748 jsr166 1.58 casCleanMe(dp, null);
749     if (dp == pred)
750 dl 1.55 return; // s is already saved node
751 jsr166 1.58 } else if (casCleanMe(null, pred))
752 dl 1.55 return; // Postpone cleaning s
753 dl 1.2 }
754     }
755 dl 1.69
756 dl 1.120 // VarHandle mechanics
757     private static final VarHandle QHEAD;
758     private static final VarHandle QTAIL;
759     private static final VarHandle QCLEANME;
760 dl 1.73 static {
761     try {
762 dl 1.120 MethodHandles.Lookup l = MethodHandles.lookup();
763     QHEAD = l.findVarHandle(TransferQueue.class, "head",
764     QNode.class);
765     QTAIL = l.findVarHandle(TransferQueue.class, "tail",
766     QNode.class);
767     QCLEANME = l.findVarHandle(TransferQueue.class, "cleanMe",
768     QNode.class);
769 jsr166 1.111 } catch (ReflectiveOperationException e) {
770 jsr166 1.126 throw new ExceptionInInitializerError(e);
771 dl 1.73 }
772     }
773 dl 1.55 }
774    
775     /**
776     * The transferer. Set only in constructor, but cannot be declared
777     * as final without further complicating serialization. Since
778 dl 1.56 * this is accessed only at most once per public method, there
779     * isn't a noticeable performance penalty for using volatile
780     * instead of final here.
781 dl 1.55 */
782 jsr166 1.82 private transient volatile Transferer<E> transferer;
783 dl 1.55
784     /**
785 jsr166 1.90 * Creates a {@code SynchronousQueue} with nonfair access policy.
786 dl 1.55 */
787     public SynchronousQueue() {
788     this(false);
789     }
790 dl 1.2
791 dl 1.55 /**
792 jsr166 1.90 * Creates a {@code SynchronousQueue} with the specified fairness policy.
793 jsr166 1.63 *
794     * @param fair if true, waiting threads contend in FIFO order for
795     * access; otherwise the order is unspecified.
796 dl 1.55 */
797     public SynchronousQueue(boolean fair) {
798 jsr166 1.82 transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
799 dl 1.2 }
800    
801     /**
802 dl 1.35 * Adds the specified element to this queue, waiting if necessary for
803     * another thread to receive it.
804 jsr166 1.50 *
805     * @throws InterruptedException {@inheritDoc}
806     * @throws NullPointerException {@inheritDoc}
807 tim 1.10 */
808 jsr166 1.82 public void put(E e) throws InterruptedException {
809     if (e == null) throw new NullPointerException();
810     if (transferer.transfer(e, false, 0) == null) {
811 jsr166 1.68 Thread.interrupted();
812 dl 1.55 throw new InterruptedException();
813 jsr166 1.68 }
814 tim 1.1 }
815    
816 dholmes 1.11 /**
817 dl 1.20 * Inserts the specified element into this queue, waiting if necessary
818 dl 1.18 * up to the specified wait time for another thread to receive it.
819 jsr166 1.50 *
820 jsr166 1.90 * @return {@code true} if successful, or {@code false} if the
821 jsr166 1.92 * specified waiting time elapses before a consumer appears
822 jsr166 1.50 * @throws InterruptedException {@inheritDoc}
823     * @throws NullPointerException {@inheritDoc}
824 dholmes 1.11 */
825 jsr166 1.82 public boolean offer(E e, long timeout, TimeUnit unit)
826 dl 1.55 throws InterruptedException {
827 jsr166 1.82 if (e == null) throw new NullPointerException();
828     if (transferer.transfer(e, true, unit.toNanos(timeout)) != null)
829 dl 1.55 return true;
830     if (!Thread.interrupted())
831     return false;
832     throw new InterruptedException();
833     }
834    
835     /**
836     * Inserts the specified element into this queue, if another thread is
837     * waiting to receive it.
838     *
839     * @param e the element to add
840 jsr166 1.90 * @return {@code true} if the element was added to this queue, else
841     * {@code false}
842 dl 1.55 * @throws NullPointerException if the specified element is null
843     */
844     public boolean offer(E e) {
845 jsr166 1.49 if (e == null) throw new NullPointerException();
846 dl 1.55 return transferer.transfer(e, true, 0) != null;
847 tim 1.1 }
848    
849 dholmes 1.11 /**
850     * Retrieves and removes the head of this queue, waiting if necessary
851     * for another thread to insert it.
852 jsr166 1.50 *
853 dholmes 1.11 * @return the head of this queue
854 jsr166 1.50 * @throws InterruptedException {@inheritDoc}
855 dholmes 1.11 */
856 dl 1.2 public E take() throws InterruptedException {
857 jsr166 1.82 E e = transferer.transfer(null, false, 0);
858 dl 1.55 if (e != null)
859 jsr166 1.82 return e;
860 jsr166 1.68 Thread.interrupted();
861 dl 1.55 throw new InterruptedException();
862 tim 1.1 }
863 dl 1.2
864 dholmes 1.11 /**
865     * Retrieves and removes the head of this queue, waiting
866     * if necessary up to the specified wait time, for another thread
867     * to insert it.
868 jsr166 1.50 *
869 jsr166 1.90 * @return the head of this queue, or {@code null} if the
870 jsr166 1.92 * specified waiting time elapses before an element is present
871 jsr166 1.50 * @throws InterruptedException {@inheritDoc}
872 dholmes 1.11 */
873 dl 1.2 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
874 jsr166 1.82 E e = transferer.transfer(null, true, unit.toNanos(timeout));
875 dl 1.55 if (e != null || !Thread.interrupted())
876 jsr166 1.82 return e;
877 dl 1.55 throw new InterruptedException();
878 tim 1.1 }
879 dl 1.2
880 dl 1.18 /**
881     * Retrieves and removes the head of this queue, if another thread
882     * is currently making an element available.
883     *
884 jsr166 1.90 * @return the head of this queue, or {@code null} if no
885 jsr166 1.92 * element is available
886 dl 1.18 */
887 dl 1.2 public E poll() {
888 jsr166 1.82 return transferer.transfer(null, true, 0);
889 tim 1.1 }
890 dl 1.2
891 dl 1.5 /**
892 jsr166 1.90 * Always returns {@code true}.
893     * A {@code SynchronousQueue} has no internal capacity.
894 jsr166 1.63 *
895 jsr166 1.90 * @return {@code true}
896 dl 1.5 */
897     public boolean isEmpty() {
898     return true;
899     }
900    
901     /**
902 dholmes 1.11 * Always returns zero.
903 jsr166 1.90 * A {@code SynchronousQueue} has no internal capacity.
904 jsr166 1.63 *
905 jsr166 1.89 * @return zero
906 dl 1.5 */
907     public int size() {
908     return 0;
909 tim 1.1 }
910 dl 1.2
911 dl 1.5 /**
912 dholmes 1.11 * Always returns zero.
913 jsr166 1.90 * A {@code SynchronousQueue} has no internal capacity.
914 jsr166 1.63 *
915 jsr166 1.89 * @return zero
916 dl 1.5 */
917     public int remainingCapacity() {
918     return 0;
919     }
920    
921     /**
922 dholmes 1.11 * Does nothing.
923 jsr166 1.90 * A {@code SynchronousQueue} has no internal capacity.
924 dholmes 1.11 */
925 dl 1.55 public void clear() {
926     }
927 dholmes 1.11
928     /**
929 jsr166 1.90 * Always returns {@code false}.
930     * A {@code SynchronousQueue} has no internal capacity.
931 jsr166 1.63 *
932 dl 1.55 * @param o the element
933 jsr166 1.90 * @return {@code false}
934 dholmes 1.11 */
935     public boolean contains(Object o) {
936     return false;
937     }
938    
939     /**
940 jsr166 1.90 * Always returns {@code false}.
941     * A {@code SynchronousQueue} has no internal capacity.
942 dl 1.18 *
943     * @param o the element to remove
944 jsr166 1.90 * @return {@code false}
945 dl 1.18 */
946     public boolean remove(Object o) {
947     return false;
948     }
949    
950     /**
951 jsr166 1.90 * Returns {@code false} unless the given collection is empty.
952     * A {@code SynchronousQueue} has no internal capacity.
953 jsr166 1.63 *
954 dl 1.18 * @param c the collection
955 jsr166 1.90 * @return {@code false} unless given collection is empty
956 dholmes 1.11 */
957 dl 1.12 public boolean containsAll(Collection<?> c) {
958 dl 1.16 return c.isEmpty();
959 dholmes 1.11 }
960    
961     /**
962 jsr166 1.90 * Always returns {@code false}.
963     * A {@code SynchronousQueue} has no internal capacity.
964 jsr166 1.63 *
965 dl 1.18 * @param c the collection
966 jsr166 1.90 * @return {@code false}
967 dholmes 1.11 */
968 dl 1.12 public boolean removeAll(Collection<?> c) {
969 dholmes 1.11 return false;
970     }
971    
972     /**
973 jsr166 1.90 * Always returns {@code false}.
974     * A {@code SynchronousQueue} has no internal capacity.
975 jsr166 1.63 *
976 dl 1.18 * @param c the collection
977 jsr166 1.90 * @return {@code false}
978 dholmes 1.11 */
979 dl 1.12 public boolean retainAll(Collection<?> c) {
980 dholmes 1.11 return false;
981     }
982    
983     /**
984 jsr166 1.90 * Always returns {@code null}.
985     * A {@code SynchronousQueue} does not return elements
986 dl 1.5 * unless actively waited on.
987 jsr166 1.63 *
988 jsr166 1.90 * @return {@code null}
989 dl 1.5 */
990     public E peek() {
991     return null;
992     }
993    
994     /**
995 jsr166 1.90 * Returns an empty iterator in which {@code hasNext} always returns
996     * {@code false}.
997 tim 1.13 *
998 dholmes 1.11 * @return an empty iterator
999 dl 1.5 */
1000 dl 1.2 public Iterator<E> iterator() {
1001 jsr166 1.102 return Collections.emptyIterator();
1002 tim 1.1 }
1003    
1004 jsr166 1.101 /**
1005     * Returns an empty spliterator in which calls to
1006 jsr166 1.124 * {@link Spliterator#trySplit() trySplit} always return {@code null}.
1007 jsr166 1.101 *
1008     * @return an empty spliterator
1009     * @since 1.8
1010     */
1011 dl 1.96 public Spliterator<E> spliterator() {
1012 dl 1.95 return Spliterators.emptySpliterator();
1013 dl 1.93 }
1014 jsr166 1.94
1015 dl 1.5 /**
1016 dholmes 1.11 * Returns a zero-length array.
1017     * @return a zero-length array
1018 dl 1.5 */
1019 dl 1.3 public Object[] toArray() {
1020 dl 1.25 return new Object[0];
1021 tim 1.1 }
1022    
1023 dholmes 1.11 /**
1024 jsr166 1.103 * Sets the zeroth element of the specified array to {@code null}
1025 dholmes 1.11 * (if the array has non-zero length) and returns it.
1026 jsr166 1.50 *
1027 dl 1.40 * @param a the array
1028 dholmes 1.11 * @return the specified array
1029 jsr166 1.50 * @throws NullPointerException if the specified array is null
1030 dholmes 1.11 */
1031 dl 1.2 public <T> T[] toArray(T[] a) {
1032     if (a.length > 0)
1033     a[0] = null;
1034     return a;
1035     }
1036 dl 1.21
1037 jsr166 1.50 /**
1038 jsr166 1.113 * Always returns {@code "[]"}.
1039     * @return {@code "[]"}
1040     */
1041     public String toString() {
1042     return "[]";
1043     }
1044    
1045     /**
1046 jsr166 1.50 * @throws UnsupportedOperationException {@inheritDoc}
1047     * @throws ClassCastException {@inheritDoc}
1048     * @throws NullPointerException {@inheritDoc}
1049     * @throws IllegalArgumentException {@inheritDoc}
1050     */
1051 dl 1.21 public int drainTo(Collection<? super E> c) {
1052 jsr166 1.121 Objects.requireNonNull(c);
1053 dl 1.21 if (c == this)
1054     throw new IllegalArgumentException();
1055     int n = 0;
1056 jsr166 1.122 for (E e; (e = poll()) != null; n++)
1057 dl 1.21 c.add(e);
1058     return n;
1059     }
1060    
1061 jsr166 1.50 /**
1062     * @throws UnsupportedOperationException {@inheritDoc}
1063     * @throws ClassCastException {@inheritDoc}
1064     * @throws NullPointerException {@inheritDoc}
1065     * @throws IllegalArgumentException {@inheritDoc}
1066     */
1067 dl 1.21 public int drainTo(Collection<? super E> c, int maxElements) {
1068 jsr166 1.121 Objects.requireNonNull(c);
1069 dl 1.21 if (c == this)
1070     throw new IllegalArgumentException();
1071     int n = 0;
1072 jsr166 1.122 for (E e; n < maxElements && (e = poll()) != null; n++)
1073 dl 1.21 c.add(e);
1074     return n;
1075     }
1076 dl 1.55
1077     /*
1078     * To cope with serialization strategy in the 1.5 version of
1079     * SynchronousQueue, we declare some unused classes and fields
1080     * that exist solely to enable serializability across versions.
1081     * These fields are never used, so are initialized only if this
1082     * object is ever serialized or deserialized.
1083     */
1084    
1085 jsr166 1.82 @SuppressWarnings("serial")
1086 dl 1.55 static class WaitQueue implements java.io.Serializable { }
1087     static class LifoWaitQueue extends WaitQueue {
1088     private static final long serialVersionUID = -3633113410248163686L;
1089     }
1090     static class FifoWaitQueue extends WaitQueue {
1091     private static final long serialVersionUID = -3623113410248163686L;
1092     }
1093     private ReentrantLock qlock;
1094     private WaitQueue waitingProducers;
1095     private WaitQueue waitingConsumers;
1096    
1097     /**
1098 jsr166 1.84 * Saves this queue to a stream (that is, serializes it).
1099 jsr166 1.99 * @param s the stream
1100 jsr166 1.100 * @throws java.io.IOException if an I/O error occurs
1101 dl 1.55 */
1102     private void writeObject(java.io.ObjectOutputStream s)
1103     throws java.io.IOException {
1104     boolean fair = transferer instanceof TransferQueue;
1105     if (fair) {
1106     qlock = new ReentrantLock(true);
1107     waitingProducers = new FifoWaitQueue();
1108     waitingConsumers = new FifoWaitQueue();
1109     }
1110     else {
1111     qlock = new ReentrantLock();
1112     waitingProducers = new LifoWaitQueue();
1113     waitingConsumers = new LifoWaitQueue();
1114     }
1115     s.defaultWriteObject();
1116     }
1117    
1118 jsr166 1.84 /**
1119     * Reconstitutes this queue from a stream (that is, deserializes it).
1120 jsr166 1.99 * @param s the stream
1121 jsr166 1.100 * @throws ClassNotFoundException if the class of a serialized object
1122     * could not be found
1123     * @throws java.io.IOException if an I/O error occurs
1124 jsr166 1.84 */
1125 jsr166 1.98 private void readObject(java.io.ObjectInputStream s)
1126 dl 1.55 throws java.io.IOException, ClassNotFoundException {
1127     s.defaultReadObject();
1128     if (waitingProducers instanceof FifoWaitQueue)
1129 jsr166 1.82 transferer = new TransferQueue<E>();
1130 dl 1.55 else
1131 jsr166 1.82 transferer = new TransferStack<E>();
1132 dl 1.55 }
1133    
1134 jsr166 1.114 static {
1135     // Reduce the risk of rare disastrous classloading in first call to
1136     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1137     Class<?> ensureLoaded = LockSupport.class;
1138     }
1139 tim 1.1 }