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 (3 years, 11 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.127: +167 -201 lines
Log Message:
improve loom-friendliness

File Contents

# Content
1 /*
2 * 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 * http://creativecommons.org/publicdomain/zero/1.0/
6 */
7
8 package java.util.concurrent;
9
10 import java.lang.invoke.MethodHandles;
11 import java.lang.invoke.VarHandle;
12 import java.util.AbstractQueue;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Iterator;
16 import java.util.Objects;
17 import java.util.Spliterator;
18 import java.util.Spliterators;
19 import java.util.concurrent.locks.LockSupport;
20 import java.util.concurrent.locks.ReentrantLock;
21
22 /**
23 * 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 * {@code peek} at a synchronous queue because an element is only
28 * 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 * {@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 *
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 * object running in one thread must sync up with an object running
42 * in another thread in order to hand it some information, event, or
43 * task.
44 *
45 * <p>This class supports an optional fairness policy for ordering
46 * waiting producer and consumer threads. By default, this ordering
47 * is not guaranteed. However, a queue constructed with fairness set
48 * to {@code true} grants threads access in FIFO order.
49 *
50 * <p>This class and its iterator implement all of the <em>optional</em>
51 * methods of the {@link Collection} and {@link Iterator} interfaces.
52 *
53 * <p>This class is a member of the
54 * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
55 * Java Collections Framework</a>.
56 *
57 * @since 1.5
58 * @author Doug Lea and Bill Scherer and Michael Scott
59 * @param <E> the type of elements held in this queue
60 */
61 public class SynchronousQueue<E> extends AbstractQueue<E>
62 implements BlockingQueue<E>, java.io.Serializable {
63 private static final long serialVersionUID = -3223113410248163686L;
64
65 /*
66 * 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 * 1. The original algorithms used bit-marked pointers, but
105 * 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 * 3. Support for cancellation via timeout and interrupts,
110 * including cleaning out cancelled nodes/threads
111 * from lists to avoid garbage retention and memory depletion.
112 *
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 * is taken to "forget" references to data, other nodes, and
132 * 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 * aggressively forgotten to avoid reachability of everything any
139 * node has ever referred to since arrival.
140 *
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 */
153
154 /**
155 * Shared internal API for dual stacks and queues.
156 */
157 abstract static class Transferer<E> {
158 /**
159 * Performs a put or take.
160 *
161 * @param e if non-null, the item to be handed to a consumer;
162 * if null, requests that transfer return an item
163 * offered by producer.
164 * @param timed if this operation should timeout
165 * @param nanos the timeout, in nanoseconds
166 * @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 */
171 abstract E transfer(E e, boolean timed, long nanos);
172 }
173
174 /**
175 * The number of nanoseconds for which it is faster to spin
176 * rather than to use timed park. A rough estimate suffices.
177 */
178 static final long SPIN_FOR_TIMEOUT_THRESHOLD = 1023L;
179
180 /** Dual stack */
181 static final class TransferStack<E> extends Transferer<E> {
182 /*
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
190 /* 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 /** Returns true if m has fulfilling bit set. */
199 static boolean isFulfilling(int m) { return (m & FULFILLING) != 0; }
200
201 /** Node class for TransferStacks. */
202 static final class SNode implements ForkJoinPool.ManagedBlocker {
203 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 return cmp == next &&
218 SNEXT.compareAndSet(this, cmp, val);
219 }
220
221 /**
222 * 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 * @param s the node to match
227 * @return true if successfully matched to s
228 */
229 boolean tryMatch(SNode s) {
230 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 }
237 else
238 m = match;
239 }
240 return m == s;
241 }
242
243 /**
244 * Tries to cancel a wait by matching node to itself.
245 */
246 boolean tryCancel() {
247 return SMATCH.compareAndSet(this, null, this);
248 }
249
250 boolean isCancelled() {
251 return match == this;
252 }
253
254 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 // VarHandle mechanics
268 private static final VarHandle SMATCH;
269 private static final VarHandle SNEXT;
270 private static final VarHandle SWAITER;
271 static {
272 try {
273 MethodHandles.Lookup l = MethodHandles.lookup();
274 SMATCH = l.findVarHandle(SNode.class, "match", SNode.class);
275 SNEXT = l.findVarHandle(SNode.class, "next", SNode.class);
276 SWAITER = l.findVarHandle(SNode.class, "waiter", Thread.class);
277 } catch (ReflectiveOperationException e) {
278 throw new ExceptionInInitializerError(e);
279 }
280 }
281 }
282
283 /** The head (top) of the stack */
284 volatile SNode head;
285
286 boolean casHead(SNode h, SNode nh) {
287 return h == head &&
288 SHEAD.compareAndSet(this, h, nh);
289 }
290
291 /**
292 * Creates or resets fields of a node. Called only from transfer
293 * 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 }
304
305 /**
306 * Puts or takes an item.
307 */
308 @SuppressWarnings("unchecked")
309 E transfer(E e, boolean timed, long nanos) {
310 /*
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 * other threads performing action 3:
323 *
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 int mode = (e == null) ? REQUEST : DATA;
333
334 for (;;) {
335 SNode h = head;
336 if (h == null || h.mode == mode) { // empty or same-mode
337 if (timed && nanos <= 0L) { // can't wait
338 if (h != null && h.isCancelled())
339 casHead(h, h.next); // pop cancelled node
340 else
341 return null;
342 } else if (casHead(h, s = snode(s, e, h, mode))) {
343 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 }
374 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 }
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 return (E) ((mode == REQUEST) ? m.item : s.item);
396 } 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 }
412 }
413 }
414
415 /**
416 * Unlinks s from the stack.
417 */
418 void clean(SNode s) {
419 s.item = null; // forget item
420 s.forgetWaiter();
421
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 * further because we don't want to doubly traverse just to
430 * 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 }
450 }
451
452 // VarHandle mechanics
453 private static final VarHandle SHEAD;
454 static {
455 try {
456 MethodHandles.Lookup l = MethodHandles.lookup();
457 SHEAD = l.findVarHandle(TransferStack.class, "head", SNode.class);
458 } catch (ReflectiveOperationException e) {
459 throw new ExceptionInInitializerError(e);
460 }
461 }
462 }
463
464 /** Dual Queue */
465 static final class TransferQueue<E> extends Transferer<E> {
466 /*
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 * from non-null to null (for put) or vice versa (for take).
473 */
474
475 /** Node class for TransferQueue. */
476 static final class QNode implements ForkJoinPool.ManagedBlocker {
477 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 final boolean isData;
481
482 QNode(Object item, boolean isData) {
483 this.item = item;
484 this.isData = isData;
485 }
486
487 boolean casNext(QNode cmp, QNode val) {
488 return next == cmp &&
489 QNEXT.compareAndSet(this, cmp, val);
490 }
491
492 boolean casItem(Object cmp, Object val) {
493 return item == cmp &&
494 QITEM.compareAndSet(this, cmp, val);
495 }
496
497 /**
498 * Tries to cancel by CAS'ing ref to this as item.
499 */
500 boolean tryCancel(Object cmp) {
501 return QITEM.compareAndSet(this, cmp, this);
502 }
503
504 boolean isCancelled() {
505 return item == this;
506 }
507
508 /**
509 * Returns true if this node is known to be off the queue
510 * because its next pointer has been forgotten due to
511 * an advanceHead operation.
512 */
513 boolean isOffList() {
514 return next == this;
515 }
516
517 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 // VarHandle mechanics
538 private static final VarHandle QITEM;
539 private static final VarHandle QNEXT;
540 private static final VarHandle QWAITER;
541 static {
542 try {
543 MethodHandles.Lookup l = MethodHandles.lookup();
544 QITEM = l.findVarHandle(QNode.class, "item", Object.class);
545 QNEXT = l.findVarHandle(QNode.class, "next", QNode.class);
546 QWAITER = l.findVarHandle(QNode.class, "waiter", Thread.class);
547 } catch (ReflectiveOperationException e) {
548 throw new ExceptionInInitializerError(e);
549 }
550 }
551 }
552
553 /** Head of queue */
554 transient volatile QNode head;
555 /** Tail of queue */
556 transient volatile QNode tail;
557 /**
558 * Reference to a cancelled node that might not yet have been
559 * unlinked from queue because it was the last inserted node
560 * when it was cancelled.
561 */
562 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 }
569
570 /**
571 * Tries to cas nh as new head; if successful, unlink
572 * old head's next node to avoid garbage retention.
573 */
574 void advanceHead(QNode h, QNode nh) {
575 if (h == head &&
576 QHEAD.compareAndSet(this, h, nh))
577 h.next = h; // forget old next
578 }
579
580 /**
581 * Tries to cas nt as new tail.
582 */
583 void advanceTail(QNode t, QNode nt) {
584 if (tail == t)
585 QTAIL.compareAndSet(this, t, nt);
586 }
587
588 /**
589 * Tries to CAS cleanMe slot.
590 */
591 boolean casCleanMe(QNode cmp, QNode val) {
592 return cleanMe == cmp &&
593 QCLEANME.compareAndSet(this, cmp, val);
594 }
595
596 /**
597 * Puts or takes an item.
598 */
599 @SuppressWarnings("unchecked")
600 E transfer(E e, boolean timed, long nanos) {
601 /* Basic algorithm is to loop trying to take either of
602 * two actions:
603 *
604 * 1. If queue apparently empty or holding same-mode nodes,
605 * 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 QNode s = null; // constructed/reused as needed
627 boolean isData = (e != null);
628 for (;;) {
629 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 advanceTail(t, tn);
637 else if (timed && nanos <= 0L) // can't wait
638 return null;
639 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 }
686
687 } else if ((m = h.next) != null && t == tail && h == head) {
688 Thread waiter;
689 Object x = m.item;
690 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 }
698 }
699 }
700 }
701
702 /**
703 * Gets rid of cancelled node s with original predecessor pred.
704 */
705 void clean(QNode pred, QNode s) {
706 s.forgetWaiter();
707 /*
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 QNode t = tail; // Ensure consistent read for tail
723 if (t == h)
724 return;
725 QNode tn = t.next;
726 if (t != tail)
727 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 casCleanMe(dp, null);
749 if (dp == pred)
750 return; // s is already saved node
751 } else if (casCleanMe(null, pred))
752 return; // Postpone cleaning s
753 }
754 }
755
756 // VarHandle mechanics
757 private static final VarHandle QHEAD;
758 private static final VarHandle QTAIL;
759 private static final VarHandle QCLEANME;
760 static {
761 try {
762 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 } catch (ReflectiveOperationException e) {
770 throw new ExceptionInInitializerError(e);
771 }
772 }
773 }
774
775 /**
776 * The transferer. Set only in constructor, but cannot be declared
777 * as final without further complicating serialization. Since
778 * 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 */
782 private transient volatile Transferer<E> transferer;
783
784 /**
785 * Creates a {@code SynchronousQueue} with nonfair access policy.
786 */
787 public SynchronousQueue() {
788 this(false);
789 }
790
791 /**
792 * Creates a {@code SynchronousQueue} with the specified fairness policy.
793 *
794 * @param fair if true, waiting threads contend in FIFO order for
795 * access; otherwise the order is unspecified.
796 */
797 public SynchronousQueue(boolean fair) {
798 transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
799 }
800
801 /**
802 * Adds the specified element to this queue, waiting if necessary for
803 * another thread to receive it.
804 *
805 * @throws InterruptedException {@inheritDoc}
806 * @throws NullPointerException {@inheritDoc}
807 */
808 public void put(E e) throws InterruptedException {
809 if (e == null) throw new NullPointerException();
810 if (transferer.transfer(e, false, 0) == null) {
811 Thread.interrupted();
812 throw new InterruptedException();
813 }
814 }
815
816 /**
817 * Inserts the specified element into this queue, waiting if necessary
818 * up to the specified wait time for another thread to receive it.
819 *
820 * @return {@code true} if successful, or {@code false} if the
821 * specified waiting time elapses before a consumer appears
822 * @throws InterruptedException {@inheritDoc}
823 * @throws NullPointerException {@inheritDoc}
824 */
825 public boolean offer(E e, long timeout, TimeUnit unit)
826 throws InterruptedException {
827 if (e == null) throw new NullPointerException();
828 if (transferer.transfer(e, true, unit.toNanos(timeout)) != null)
829 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 * @return {@code true} if the element was added to this queue, else
841 * {@code false}
842 * @throws NullPointerException if the specified element is null
843 */
844 public boolean offer(E e) {
845 if (e == null) throw new NullPointerException();
846 return transferer.transfer(e, true, 0) != null;
847 }
848
849 /**
850 * Retrieves and removes the head of this queue, waiting if necessary
851 * for another thread to insert it.
852 *
853 * @return the head of this queue
854 * @throws InterruptedException {@inheritDoc}
855 */
856 public E take() throws InterruptedException {
857 E e = transferer.transfer(null, false, 0);
858 if (e != null)
859 return e;
860 Thread.interrupted();
861 throw new InterruptedException();
862 }
863
864 /**
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 *
869 * @return the head of this queue, or {@code null} if the
870 * specified waiting time elapses before an element is present
871 * @throws InterruptedException {@inheritDoc}
872 */
873 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
874 E e = transferer.transfer(null, true, unit.toNanos(timeout));
875 if (e != null || !Thread.interrupted())
876 return e;
877 throw new InterruptedException();
878 }
879
880 /**
881 * Retrieves and removes the head of this queue, if another thread
882 * is currently making an element available.
883 *
884 * @return the head of this queue, or {@code null} if no
885 * element is available
886 */
887 public E poll() {
888 return transferer.transfer(null, true, 0);
889 }
890
891 /**
892 * Always returns {@code true}.
893 * A {@code SynchronousQueue} has no internal capacity.
894 *
895 * @return {@code true}
896 */
897 public boolean isEmpty() {
898 return true;
899 }
900
901 /**
902 * Always returns zero.
903 * A {@code SynchronousQueue} has no internal capacity.
904 *
905 * @return zero
906 */
907 public int size() {
908 return 0;
909 }
910
911 /**
912 * Always returns zero.
913 * A {@code SynchronousQueue} has no internal capacity.
914 *
915 * @return zero
916 */
917 public int remainingCapacity() {
918 return 0;
919 }
920
921 /**
922 * Does nothing.
923 * A {@code SynchronousQueue} has no internal capacity.
924 */
925 public void clear() {
926 }
927
928 /**
929 * Always returns {@code false}.
930 * A {@code SynchronousQueue} has no internal capacity.
931 *
932 * @param o the element
933 * @return {@code false}
934 */
935 public boolean contains(Object o) {
936 return false;
937 }
938
939 /**
940 * Always returns {@code false}.
941 * A {@code SynchronousQueue} has no internal capacity.
942 *
943 * @param o the element to remove
944 * @return {@code false}
945 */
946 public boolean remove(Object o) {
947 return false;
948 }
949
950 /**
951 * Returns {@code false} unless the given collection is empty.
952 * A {@code SynchronousQueue} has no internal capacity.
953 *
954 * @param c the collection
955 * @return {@code false} unless given collection is empty
956 */
957 public boolean containsAll(Collection<?> c) {
958 return c.isEmpty();
959 }
960
961 /**
962 * Always returns {@code false}.
963 * A {@code SynchronousQueue} has no internal capacity.
964 *
965 * @param c the collection
966 * @return {@code false}
967 */
968 public boolean removeAll(Collection<?> c) {
969 return false;
970 }
971
972 /**
973 * Always returns {@code false}.
974 * A {@code SynchronousQueue} has no internal capacity.
975 *
976 * @param c the collection
977 * @return {@code false}
978 */
979 public boolean retainAll(Collection<?> c) {
980 return false;
981 }
982
983 /**
984 * Always returns {@code null}.
985 * A {@code SynchronousQueue} does not return elements
986 * unless actively waited on.
987 *
988 * @return {@code null}
989 */
990 public E peek() {
991 return null;
992 }
993
994 /**
995 * Returns an empty iterator in which {@code hasNext} always returns
996 * {@code false}.
997 *
998 * @return an empty iterator
999 */
1000 public Iterator<E> iterator() {
1001 return Collections.emptyIterator();
1002 }
1003
1004 /**
1005 * Returns an empty spliterator in which calls to
1006 * {@link Spliterator#trySplit() trySplit} always return {@code null}.
1007 *
1008 * @return an empty spliterator
1009 * @since 1.8
1010 */
1011 public Spliterator<E> spliterator() {
1012 return Spliterators.emptySpliterator();
1013 }
1014
1015 /**
1016 * Returns a zero-length array.
1017 * @return a zero-length array
1018 */
1019 public Object[] toArray() {
1020 return new Object[0];
1021 }
1022
1023 /**
1024 * Sets the zeroth element of the specified array to {@code null}
1025 * (if the array has non-zero length) and returns it.
1026 *
1027 * @param a the array
1028 * @return the specified array
1029 * @throws NullPointerException if the specified array is null
1030 */
1031 public <T> T[] toArray(T[] a) {
1032 if (a.length > 0)
1033 a[0] = null;
1034 return a;
1035 }
1036
1037 /**
1038 * Always returns {@code "[]"}.
1039 * @return {@code "[]"}
1040 */
1041 public String toString() {
1042 return "[]";
1043 }
1044
1045 /**
1046 * @throws UnsupportedOperationException {@inheritDoc}
1047 * @throws ClassCastException {@inheritDoc}
1048 * @throws NullPointerException {@inheritDoc}
1049 * @throws IllegalArgumentException {@inheritDoc}
1050 */
1051 public int drainTo(Collection<? super E> c) {
1052 Objects.requireNonNull(c);
1053 if (c == this)
1054 throw new IllegalArgumentException();
1055 int n = 0;
1056 for (E e; (e = poll()) != null; n++)
1057 c.add(e);
1058 return n;
1059 }
1060
1061 /**
1062 * @throws UnsupportedOperationException {@inheritDoc}
1063 * @throws ClassCastException {@inheritDoc}
1064 * @throws NullPointerException {@inheritDoc}
1065 * @throws IllegalArgumentException {@inheritDoc}
1066 */
1067 public int drainTo(Collection<? super E> c, int maxElements) {
1068 Objects.requireNonNull(c);
1069 if (c == this)
1070 throw new IllegalArgumentException();
1071 int n = 0;
1072 for (E e; n < maxElements && (e = poll()) != null; n++)
1073 c.add(e);
1074 return n;
1075 }
1076
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 @SuppressWarnings("serial")
1086 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 * Saves this queue to a stream (that is, serializes it).
1099 * @param s the stream
1100 * @throws java.io.IOException if an I/O error occurs
1101 */
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 /**
1119 * Reconstitutes this queue from a stream (that is, deserializes it).
1120 * @param s the stream
1121 * @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 */
1125 private void readObject(java.io.ObjectInputStream s)
1126 throws java.io.IOException, ClassNotFoundException {
1127 s.defaultReadObject();
1128 if (waitingProducers instanceof FifoWaitQueue)
1129 transferer = new TransferQueue<E>();
1130 else
1131 transferer = new TransferStack<E>();
1132 }
1133
1134 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 }