ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/SynchronousQueue.java
Revision: 1.116
Committed: Sat Sep 19 21:07:11 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.115: +4 -4 lines
Log Message:
ALL_CAPS for static finals

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