jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea, Bill Scherer, and Michael Scott with jaroslav@1890: * assistance from members of JCP JSR-166 Expert Group and released to jaroslav@1890: * the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent; jaroslav@1890: import java.util.concurrent.locks.*; jaroslav@1890: import java.util.*; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * A {@linkplain BlockingQueue blocking queue} in which each insert jaroslav@1890: * operation must wait for a corresponding remove operation by another jaroslav@1890: * thread, and vice versa. A synchronous queue does not have any jaroslav@1890: * internal capacity, not even a capacity of one. You cannot jaroslav@1890: * peek at a synchronous queue because an element is only jaroslav@1890: * present when you try to remove it; you cannot insert an element jaroslav@1890: * (using any method) unless another thread is trying to remove it; jaroslav@1890: * you cannot iterate as there is nothing to iterate. The jaroslav@1890: * head of the queue is the element that the first queued jaroslav@1890: * inserting thread is trying to add to the queue; if there is no such jaroslav@1890: * queued thread then no element is available for removal and jaroslav@1890: * poll() will return null. For purposes of other jaroslav@1890: * Collection methods (for example contains), a jaroslav@1890: * SynchronousQueue acts as an empty collection. This queue jaroslav@1890: * does not permit null elements. jaroslav@1890: * jaroslav@1890: *

Synchronous queues are similar to rendezvous channels used in jaroslav@1890: * CSP and Ada. They are well suited for handoff designs, in which an jaroslav@1890: * object running in one thread must sync up with an object running jaroslav@1890: * in another thread in order to hand it some information, event, or jaroslav@1890: * task. jaroslav@1890: * jaroslav@1890: *

This class supports an optional fairness policy for ordering jaroslav@1890: * waiting producer and consumer threads. By default, this ordering jaroslav@1890: * is not guaranteed. However, a queue constructed with fairness set jaroslav@1890: * to true grants threads access in FIFO order. jaroslav@1890: * jaroslav@1890: *

This class and its iterator implement all of the jaroslav@1890: * optional methods of the {@link Collection} and {@link jaroslav@1890: * Iterator} interfaces. jaroslav@1890: * jaroslav@1890: *

This class is a member of the jaroslav@1890: * jaroslav@1890: * Java Collections Framework. jaroslav@1890: * jaroslav@1890: * @since 1.5 jaroslav@1890: * @author Doug Lea and Bill Scherer and Michael Scott jaroslav@1890: * @param the type of elements held in this collection jaroslav@1890: */ jaroslav@1890: public class SynchronousQueue extends AbstractQueue jaroslav@1890: implements BlockingQueue, java.io.Serializable { jaroslav@1890: private static final long serialVersionUID = -3223113410248163686L; jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This class implements extensions of the dual stack and dual jaroslav@1890: * queue algorithms described in "Nonblocking Concurrent Objects jaroslav@1890: * with Condition Synchronization", by W. N. Scherer III and jaroslav@1890: * M. L. Scott. 18th Annual Conf. on Distributed Computing, jaroslav@1890: * Oct. 2004 (see also jaroslav@1890: * http://www.cs.rochester.edu/u/scott/synchronization/pseudocode/duals.html). jaroslav@1890: * The (Lifo) stack is used for non-fair mode, and the (Fifo) jaroslav@1890: * queue for fair mode. The performance of the two is generally jaroslav@1890: * similar. Fifo usually supports higher throughput under jaroslav@1890: * contention but Lifo maintains higher thread locality in common jaroslav@1890: * applications. jaroslav@1890: * jaroslav@1890: * A dual queue (and similarly stack) is one that at any given jaroslav@1890: * time either holds "data" -- items provided by put operations, jaroslav@1890: * or "requests" -- slots representing take operations, or is jaroslav@1890: * empty. A call to "fulfill" (i.e., a call requesting an item jaroslav@1890: * from a queue holding data or vice versa) dequeues a jaroslav@1890: * complementary node. The most interesting feature of these jaroslav@1890: * queues is that any operation can figure out which mode the jaroslav@1890: * queue is in, and act accordingly without needing locks. jaroslav@1890: * jaroslav@1890: * Both the queue and stack extend abstract class Transferer jaroslav@1890: * defining the single method transfer that does a put or a jaroslav@1890: * take. These are unified into a single method because in dual jaroslav@1890: * data structures, the put and take operations are symmetrical, jaroslav@1890: * so nearly all code can be combined. The resulting transfer jaroslav@1890: * methods are on the long side, but are easier to follow than jaroslav@1890: * they would be if broken up into nearly-duplicated parts. jaroslav@1890: * jaroslav@1890: * The queue and stack data structures share many conceptual jaroslav@1890: * similarities but very few concrete details. For simplicity, jaroslav@1890: * they are kept distinct so that they can later evolve jaroslav@1890: * separately. jaroslav@1890: * jaroslav@1890: * The algorithms here differ from the versions in the above paper jaroslav@1890: * in extending them for use in synchronous queues, as well as jaroslav@1890: * dealing with cancellation. The main differences include: jaroslav@1890: * jaroslav@1890: * 1. The original algorithms used bit-marked pointers, but jaroslav@1890: * the ones here use mode bits in nodes, leading to a number jaroslav@1890: * of further adaptations. jaroslav@1890: * 2. SynchronousQueues must block threads waiting to become jaroslav@1890: * fulfilled. jaroslav@1890: * 3. Support for cancellation via timeout and interrupts, jaroslav@1890: * including cleaning out cancelled nodes/threads jaroslav@1890: * from lists to avoid garbage retention and memory depletion. jaroslav@1890: * jaroslav@1890: * Blocking is mainly accomplished using LockSupport park/unpark, jaroslav@1890: * except that nodes that appear to be the next ones to become jaroslav@1890: * fulfilled first spin a bit (on multiprocessors only). On very jaroslav@1890: * busy synchronous queues, spinning can dramatically improve jaroslav@1890: * throughput. And on less busy ones, the amount of spinning is jaroslav@1890: * small enough not to be noticeable. jaroslav@1890: * jaroslav@1890: * Cleaning is done in different ways in queues vs stacks. For jaroslav@1890: * queues, we can almost always remove a node immediately in O(1) jaroslav@1890: * time (modulo retries for consistency checks) when it is jaroslav@1890: * cancelled. But if it may be pinned as the current tail, it must jaroslav@1890: * wait until some subsequent cancellation. For stacks, we need a jaroslav@1890: * potentially O(n) traversal to be sure that we can remove the jaroslav@1890: * node, but this can run concurrently with other threads jaroslav@1890: * accessing the stack. jaroslav@1890: * jaroslav@1890: * While garbage collection takes care of most node reclamation jaroslav@1890: * issues that otherwise complicate nonblocking algorithms, care jaroslav@1890: * is taken to "forget" references to data, other nodes, and jaroslav@1890: * threads that might be held on to long-term by blocked jaroslav@1890: * threads. In cases where setting to null would otherwise jaroslav@1890: * conflict with main algorithms, this is done by changing a jaroslav@1890: * node's link to now point to the node itself. This doesn't arise jaroslav@1890: * much for Stack nodes (because blocked threads do not hang on to jaroslav@1890: * old head pointers), but references in Queue nodes must be jaroslav@1890: * aggressively forgotten to avoid reachability of everything any jaroslav@1890: * node has ever referred to since arrival. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Shared internal API for dual stacks and queues. jaroslav@1890: */ jaroslav@1890: abstract static class Transferer { jaroslav@1890: /** jaroslav@1890: * Performs a put or take. jaroslav@1890: * jaroslav@1890: * @param e if non-null, the item to be handed to a consumer; jaroslav@1890: * if null, requests that transfer return an item jaroslav@1890: * offered by producer. jaroslav@1890: * @param timed if this operation should timeout jaroslav@1890: * @param nanos the timeout, in nanoseconds jaroslav@1890: * @return if non-null, the item provided or received; if null, jaroslav@1890: * the operation failed due to timeout or interrupt -- jaroslav@1890: * the caller can distinguish which of these occurred jaroslav@1890: * by checking Thread.interrupted. jaroslav@1890: */ jaroslav@1890: abstract Object transfer(Object e, boolean timed, long nanos); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** The number of CPUs, for spin control */ jaroslav@1895: static final int NCPUS = 1; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of times to spin before blocking in timed waits. jaroslav@1890: * The value is empirically derived -- it works well across a jaroslav@1890: * variety of processors and OSes. Empirically, the best value jaroslav@1890: * seems not to vary with number of CPUs (beyond 2) so is just jaroslav@1890: * a constant. jaroslav@1890: */ jaroslav@1890: static final int maxTimedSpins = (NCPUS < 2) ? 0 : 32; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of times to spin before blocking in untimed waits. jaroslav@1890: * This is greater than timed value because untimed waits spin jaroslav@1890: * faster since they don't need to check times on each spin. jaroslav@1890: */ jaroslav@1890: static final int maxUntimedSpins = maxTimedSpins * 16; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The number of nanoseconds for which it is faster to spin jaroslav@1890: * rather than to use timed park. A rough estimate suffices. jaroslav@1890: */ jaroslav@1890: static final long spinForTimeoutThreshold = 1000L; jaroslav@1890: jaroslav@1890: /** Dual stack */ jaroslav@1890: static final class TransferStack extends Transferer { jaroslav@1890: /* jaroslav@1890: * This extends Scherer-Scott dual stack algorithm, differing, jaroslav@1890: * among other ways, by using "covering" nodes rather than jaroslav@1890: * bit-marked pointers: Fulfilling operations push on marker jaroslav@1890: * nodes (with FULFILLING bit set in mode) to reserve a spot jaroslav@1890: * to match a waiting node. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* Modes for SNodes, ORed together in node fields */ jaroslav@1890: /** Node represents an unfulfilled consumer */ jaroslav@1890: static final int REQUEST = 0; jaroslav@1890: /** Node represents an unfulfilled producer */ jaroslav@1890: static final int DATA = 1; jaroslav@1890: /** Node is fulfilling another unfulfilled DATA or REQUEST */ jaroslav@1890: static final int FULFILLING = 2; jaroslav@1890: jaroslav@1890: /** Return true if m has fulfilling bit set */ jaroslav@1890: static boolean isFulfilling(int m) { return (m & FULFILLING) != 0; } jaroslav@1890: jaroslav@1890: /** Node class for TransferStacks. */ jaroslav@1890: static final class SNode { jaroslav@1890: volatile SNode next; // next node in stack jaroslav@1890: volatile SNode match; // the node matched to this jaroslav@1890: volatile Thread waiter; // to control park/unpark jaroslav@1890: Object item; // data; or null for REQUESTs jaroslav@1890: int mode; jaroslav@1890: // Note: item and mode fields don't need to be volatile jaroslav@1890: // since they are always written before, and read after, jaroslav@1890: // other volatile/atomic operations. jaroslav@1890: jaroslav@1890: SNode(Object item) { jaroslav@1890: this.item = item; jaroslav@1890: } jaroslav@1890: jaroslav@1890: boolean casNext(SNode cmp, SNode val) { jaroslav@1895: if (next == cmp) { jaroslav@1895: next = val; jaroslav@1895: return true; jaroslav@1895: } jaroslav@1895: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to match node s to this node, if so, waking up thread. jaroslav@1890: * Fulfillers call tryMatch to identify their waiters. jaroslav@1890: * Waiters block until they have been matched. jaroslav@1890: * jaroslav@1890: * @param s the node to match jaroslav@1890: * @return true if successfully matched to s jaroslav@1890: */ jaroslav@1890: boolean tryMatch(SNode s) { jaroslav@1895: if (match == null) { jaroslav@1895: match = s; jaroslav@1890: Thread w = waiter; jaroslav@1890: if (w != null) { // waiters need at most one unpark jaroslav@1890: waiter = null; jaroslav@1890: LockSupport.unpark(w); jaroslav@1890: } jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: return match == s; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to cancel a wait by matching node to itself. jaroslav@1890: */ jaroslav@1890: void tryCancel() { jaroslav@1895: if (match == null) { jaroslav@1895: match = this; jaroslav@1895: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: boolean isCancelled() { jaroslav@1890: return match == this; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** The head (top) of the stack */ jaroslav@1890: volatile SNode head; jaroslav@1890: jaroslav@1890: boolean casHead(SNode h, SNode nh) { jaroslav@1895: if (head == h) { jaroslav@1895: head = nh; jaroslav@1895: return true; jaroslav@1895: } jaroslav@1895: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates or resets fields of a node. Called only from transfer jaroslav@1890: * where the node to push on stack is lazily created and jaroslav@1890: * reused when possible to help reduce intervals between reads jaroslav@1890: * and CASes of head and to avoid surges of garbage when CASes jaroslav@1890: * to push nodes fail due to contention. jaroslav@1890: */ jaroslav@1890: static SNode snode(SNode s, Object e, SNode next, int mode) { jaroslav@1890: if (s == null) s = new SNode(e); jaroslav@1890: s.mode = mode; jaroslav@1890: s.next = next; jaroslav@1890: return s; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Puts or takes an item. jaroslav@1890: */ jaroslav@1890: Object transfer(Object e, boolean timed, long nanos) { jaroslav@1890: /* jaroslav@1890: * Basic algorithm is to loop trying one of three actions: jaroslav@1890: * jaroslav@1890: * 1. If apparently empty or already containing nodes of same jaroslav@1890: * mode, try to push node on stack and wait for a match, jaroslav@1890: * returning it, or null if cancelled. jaroslav@1890: * jaroslav@1890: * 2. If apparently containing node of complementary mode, jaroslav@1890: * try to push a fulfilling node on to stack, match jaroslav@1890: * with corresponding waiting node, pop both from jaroslav@1890: * stack, and return matched item. The matching or jaroslav@1890: * unlinking might not actually be necessary because of jaroslav@1890: * other threads performing action 3: jaroslav@1890: * jaroslav@1890: * 3. If top of stack already holds another fulfilling node, jaroslav@1890: * help it out by doing its match and/or pop jaroslav@1890: * operations, and then continue. The code for helping jaroslav@1890: * is essentially the same as for fulfilling, except jaroslav@1890: * that it doesn't return the item. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: SNode s = null; // constructed/reused as needed jaroslav@1890: int mode = (e == null) ? REQUEST : DATA; jaroslav@1890: jaroslav@1890: for (;;) { jaroslav@1890: SNode h = head; jaroslav@1890: if (h == null || h.mode == mode) { // empty or same-mode jaroslav@1890: if (timed && nanos <= 0) { // can't wait jaroslav@1890: if (h != null && h.isCancelled()) jaroslav@1890: casHead(h, h.next); // pop cancelled node jaroslav@1890: else jaroslav@1890: return null; jaroslav@1890: } else if (casHead(h, s = snode(s, e, h, mode))) { jaroslav@1890: SNode m = awaitFulfill(s, timed, nanos); jaroslav@1890: if (m == s) { // wait was cancelled jaroslav@1890: clean(s); jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: if ((h = head) != null && h.next == s) jaroslav@1890: casHead(h, s.next); // help s's fulfiller jaroslav@1890: return (mode == REQUEST) ? m.item : s.item; jaroslav@1890: } jaroslav@1890: } else if (!isFulfilling(h.mode)) { // try to fulfill jaroslav@1890: if (h.isCancelled()) // already cancelled jaroslav@1890: casHead(h, h.next); // pop and retry jaroslav@1890: else if (casHead(h, s=snode(s, e, h, FULFILLING|mode))) { jaroslav@1890: for (;;) { // loop until matched or waiters disappear jaroslav@1890: SNode m = s.next; // m is s's match jaroslav@1890: if (m == null) { // all waiters are gone jaroslav@1890: casHead(s, null); // pop fulfill node jaroslav@1890: s = null; // use new node next time jaroslav@1890: break; // restart main loop jaroslav@1890: } jaroslav@1890: SNode mn = m.next; jaroslav@1890: if (m.tryMatch(s)) { jaroslav@1890: casHead(s, mn); // pop both s and m jaroslav@1890: return (mode == REQUEST) ? m.item : s.item; jaroslav@1890: } else // lost match jaroslav@1890: s.casNext(m, mn); // help unlink jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } else { // help a fulfiller jaroslav@1890: SNode m = h.next; // m is h's match jaroslav@1890: if (m == null) // waiter is gone jaroslav@1890: casHead(h, null); // pop fulfilling node jaroslav@1890: else { jaroslav@1890: SNode mn = m.next; jaroslav@1890: if (m.tryMatch(h)) // help match jaroslav@1890: casHead(h, mn); // pop both h and m jaroslav@1890: else // lost match jaroslav@1890: h.casNext(m, mn); // help unlink jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Spins/blocks until node s is matched by a fulfill operation. jaroslav@1890: * jaroslav@1890: * @param s the waiting node jaroslav@1890: * @param timed true if timed wait jaroslav@1890: * @param nanos timeout value jaroslav@1890: * @return matched node, or s if cancelled jaroslav@1890: */ jaroslav@1890: SNode awaitFulfill(SNode s, boolean timed, long nanos) { jaroslav@1890: /* jaroslav@1890: * When a node/thread is about to block, it sets its waiter jaroslav@1890: * field and then rechecks state at least one more time jaroslav@1890: * before actually parking, thus covering race vs jaroslav@1890: * fulfiller noticing that waiter is non-null so should be jaroslav@1890: * woken. jaroslav@1890: * jaroslav@1890: * When invoked by nodes that appear at the point of call jaroslav@1890: * to be at the head of the stack, calls to park are jaroslav@1890: * preceded by spins to avoid blocking when producers and jaroslav@1890: * consumers are arriving very close in time. This can jaroslav@1890: * happen enough to bother only on multiprocessors. jaroslav@1890: * jaroslav@1890: * The order of checks for returning out of main loop jaroslav@1890: * reflects fact that interrupts have precedence over jaroslav@1890: * normal returns, which have precedence over jaroslav@1890: * timeouts. (So, on timeout, one last check for match is jaroslav@1890: * done before giving up.) Except that calls from untimed jaroslav@1890: * SynchronousQueue.{poll/offer} don't check interrupts jaroslav@1890: * and don't wait at all, so are trapped in transfer jaroslav@1890: * method rather than calling awaitFulfill. jaroslav@1890: */ jaroslav@1890: long lastTime = timed ? System.nanoTime() : 0; jaroslav@1890: Thread w = Thread.currentThread(); jaroslav@1890: SNode h = head; jaroslav@1890: int spins = (shouldSpin(s) ? jaroslav@1890: (timed ? maxTimedSpins : maxUntimedSpins) : 0); jaroslav@1890: for (;;) { jaroslav@1890: if (w.isInterrupted()) jaroslav@1890: s.tryCancel(); jaroslav@1890: SNode m = s.match; jaroslav@1890: if (m != null) jaroslav@1890: return m; jaroslav@1890: if (timed) { jaroslav@1890: long now = System.nanoTime(); jaroslav@1890: nanos -= now - lastTime; jaroslav@1890: lastTime = now; jaroslav@1890: if (nanos <= 0) { jaroslav@1890: s.tryCancel(); jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: if (spins > 0) jaroslav@1890: spins = shouldSpin(s) ? (spins-1) : 0; jaroslav@1890: else if (s.waiter == null) jaroslav@1890: s.waiter = w; // establish waiter so can park next iter jaroslav@1890: else if (!timed) jaroslav@1890: LockSupport.park(this); jaroslav@1890: else if (nanos > spinForTimeoutThreshold) jaroslav@1890: LockSupport.parkNanos(this, nanos); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if node s is at head or there is an active jaroslav@1890: * fulfiller. jaroslav@1890: */ jaroslav@1890: boolean shouldSpin(SNode s) { jaroslav@1890: SNode h = head; jaroslav@1890: return (h == s || h == null || isFulfilling(h.mode)); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Unlinks s from the stack. jaroslav@1890: */ jaroslav@1890: void clean(SNode s) { jaroslav@1890: s.item = null; // forget item jaroslav@1890: s.waiter = null; // forget thread jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * At worst we may need to traverse entire stack to unlink jaroslav@1890: * s. If there are multiple concurrent calls to clean, we jaroslav@1890: * might not see s if another thread has already removed jaroslav@1890: * it. But we can stop when we see any node known to jaroslav@1890: * follow s. We use s.next unless it too is cancelled, in jaroslav@1890: * which case we try the node one past. We don't check any jaroslav@1890: * further because we don't want to doubly traverse just to jaroslav@1890: * find sentinel. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: SNode past = s.next; jaroslav@1890: if (past != null && past.isCancelled()) jaroslav@1890: past = past.next; jaroslav@1890: jaroslav@1890: // Absorb cancelled nodes at head jaroslav@1890: SNode p; jaroslav@1890: while ((p = head) != null && p != past && p.isCancelled()) jaroslav@1890: casHead(p, p.next); jaroslav@1890: jaroslav@1890: // Unsplice embedded nodes jaroslav@1890: while (p != null && p != past) { jaroslav@1890: SNode n = p.next; jaroslav@1890: if (n != null && n.isCancelled()) jaroslav@1890: p.casNext(n, n.next); jaroslav@1890: else jaroslav@1890: p = n; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** Dual Queue */ jaroslav@1890: static final class TransferQueue extends Transferer { jaroslav@1890: /* jaroslav@1890: * This extends Scherer-Scott dual queue algorithm, differing, jaroslav@1890: * among other ways, by using modes within nodes rather than jaroslav@1890: * marked pointers. The algorithm is a little simpler than jaroslav@1890: * that for stacks because fulfillers do not need explicit jaroslav@1890: * nodes, and matching is done by CAS'ing QNode.item field jaroslav@1890: * from non-null to null (for put) or vice versa (for take). jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /** Node class for TransferQueue. */ jaroslav@1890: static final class QNode { jaroslav@1890: volatile QNode next; // next node in queue jaroslav@1890: volatile Object item; // CAS'ed to or from null jaroslav@1890: volatile Thread waiter; // to control park/unpark jaroslav@1890: final boolean isData; jaroslav@1890: jaroslav@1890: QNode(Object item, boolean isData) { jaroslav@1890: this.item = item; jaroslav@1890: this.isData = isData; jaroslav@1890: } jaroslav@1890: jaroslav@1890: boolean casNext(QNode cmp, QNode val) { jaroslav@1895: if (next == cmp) { jaroslav@1895: next = val; jaroslav@1895: return true; jaroslav@1895: } jaroslav@1895: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: boolean casItem(Object cmp, Object val) { jaroslav@1895: if (item == cmp) { jaroslav@1895: item = val; jaroslav@1895: return true; jaroslav@1895: } jaroslav@1895: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to cancel by CAS'ing ref to this as item. jaroslav@1890: */ jaroslav@1890: void tryCancel(Object cmp) { jaroslav@1895: if (item == cmp) { jaroslav@1895: item = this; jaroslav@1895: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: boolean isCancelled() { jaroslav@1890: return item == this; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if this node is known to be off the queue jaroslav@1890: * because its next pointer has been forgotten due to jaroslav@1890: * an advanceHead operation. jaroslav@1890: */ jaroslav@1890: boolean isOffList() { jaroslav@1890: return next == this; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** Head of queue */ jaroslav@1890: transient volatile QNode head; jaroslav@1890: /** Tail of queue */ jaroslav@1890: transient volatile QNode tail; jaroslav@1890: /** jaroslav@1890: * Reference to a cancelled node that might not yet have been jaroslav@1890: * unlinked from queue because it was the last inserted node jaroslav@1890: * when it cancelled. jaroslav@1890: */ jaroslav@1890: transient volatile QNode cleanMe; jaroslav@1890: jaroslav@1890: TransferQueue() { jaroslav@1890: QNode h = new QNode(null, false); // initialize to dummy node. jaroslav@1890: head = h; jaroslav@1890: tail = h; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to cas nh as new head; if successful, unlink jaroslav@1890: * old head's next node to avoid garbage retention. jaroslav@1890: */ jaroslav@1890: void advanceHead(QNode h, QNode nh) { jaroslav@1895: if (head == h) { jaroslav@1895: head = nh; jaroslav@1890: h.next = h; // forget old next jaroslav@1895: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to cas nt as new tail. jaroslav@1890: */ jaroslav@1890: void advanceTail(QNode t, QNode nt) { jaroslav@1895: if (tail == t) { jaroslav@1895: tail = nt; jaroslav@1895: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Tries to CAS cleanMe slot. jaroslav@1890: */ jaroslav@1890: boolean casCleanMe(QNode cmp, QNode val) { jaroslav@1895: if (cleanMe == cmp) { jaroslav@1895: cleanMe = val; jaroslav@1895: return true; jaroslav@1895: } jaroslav@1895: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Puts or takes an item. jaroslav@1890: */ jaroslav@1890: Object transfer(Object e, boolean timed, long nanos) { jaroslav@1890: /* Basic algorithm is to loop trying to take either of jaroslav@1890: * two actions: jaroslav@1890: * jaroslav@1890: * 1. If queue apparently empty or holding same-mode nodes, jaroslav@1890: * try to add node to queue of waiters, wait to be jaroslav@1890: * fulfilled (or cancelled) and return matching item. jaroslav@1890: * jaroslav@1890: * 2. If queue apparently contains waiting items, and this jaroslav@1890: * call is of complementary mode, try to fulfill by CAS'ing jaroslav@1890: * item field of waiting node and dequeuing it, and then jaroslav@1890: * returning matching item. jaroslav@1890: * jaroslav@1890: * In each case, along the way, check for and try to help jaroslav@1890: * advance head and tail on behalf of other stalled/slow jaroslav@1890: * threads. jaroslav@1890: * jaroslav@1890: * The loop starts off with a null check guarding against jaroslav@1890: * seeing uninitialized head or tail values. This never jaroslav@1890: * happens in current SynchronousQueue, but could if jaroslav@1890: * callers held non-volatile/final ref to the jaroslav@1890: * transferer. The check is here anyway because it places jaroslav@1890: * null checks at top of loop, which is usually faster jaroslav@1890: * than having them implicitly interspersed. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: QNode s = null; // constructed/reused as needed jaroslav@1890: boolean isData = (e != null); jaroslav@1890: jaroslav@1890: for (;;) { jaroslav@1890: QNode t = tail; jaroslav@1890: QNode h = head; jaroslav@1890: if (t == null || h == null) // saw uninitialized value jaroslav@1890: continue; // spin jaroslav@1890: jaroslav@1890: if (h == t || t.isData == isData) { // empty or same-mode jaroslav@1890: QNode tn = t.next; jaroslav@1890: if (t != tail) // inconsistent read jaroslav@1890: continue; jaroslav@1890: if (tn != null) { // lagging tail jaroslav@1890: advanceTail(t, tn); jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: if (timed && nanos <= 0) // can't wait jaroslav@1890: return null; jaroslav@1890: if (s == null) jaroslav@1890: s = new QNode(e, isData); jaroslav@1890: if (!t.casNext(null, s)) // failed to link in jaroslav@1890: continue; jaroslav@1890: jaroslav@1890: advanceTail(t, s); // swing tail and wait jaroslav@1890: Object x = awaitFulfill(s, e, timed, nanos); jaroslav@1890: if (x == s) { // wait was cancelled jaroslav@1890: clean(t, s); jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: if (!s.isOffList()) { // not already unlinked jaroslav@1890: advanceHead(t, s); // unlink if head jaroslav@1890: if (x != null) // and forget fields jaroslav@1890: s.item = s; jaroslav@1890: s.waiter = null; jaroslav@1890: } jaroslav@1890: return (x != null) ? x : e; jaroslav@1890: jaroslav@1890: } else { // complementary-mode jaroslav@1890: QNode m = h.next; // node to fulfill jaroslav@1890: if (t != tail || m == null || h != head) jaroslav@1890: continue; // inconsistent read jaroslav@1890: jaroslav@1890: Object x = m.item; jaroslav@1890: if (isData == (x != null) || // m already fulfilled jaroslav@1890: x == m || // m cancelled jaroslav@1890: !m.casItem(x, e)) { // lost CAS jaroslav@1890: advanceHead(h, m); // dequeue and retry jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: jaroslav@1890: advanceHead(h, m); // successfully fulfilled jaroslav@1890: LockSupport.unpark(m.waiter); jaroslav@1890: return (x != null) ? x : e; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Spins/blocks until node s is fulfilled. jaroslav@1890: * jaroslav@1890: * @param s the waiting node jaroslav@1890: * @param e the comparison value for checking match jaroslav@1890: * @param timed true if timed wait jaroslav@1890: * @param nanos timeout value jaroslav@1890: * @return matched item, or s if cancelled jaroslav@1890: */ jaroslav@1890: Object awaitFulfill(QNode s, Object e, boolean timed, long nanos) { jaroslav@1890: /* Same idea as TransferStack.awaitFulfill */ jaroslav@1890: long lastTime = timed ? System.nanoTime() : 0; jaroslav@1890: Thread w = Thread.currentThread(); jaroslav@1890: int spins = ((head.next == s) ? jaroslav@1890: (timed ? maxTimedSpins : maxUntimedSpins) : 0); jaroslav@1890: for (;;) { jaroslav@1890: if (w.isInterrupted()) jaroslav@1890: s.tryCancel(e); jaroslav@1890: Object x = s.item; jaroslav@1890: if (x != e) jaroslav@1890: return x; jaroslav@1890: if (timed) { jaroslav@1890: long now = System.nanoTime(); jaroslav@1890: nanos -= now - lastTime; jaroslav@1890: lastTime = now; jaroslav@1890: if (nanos <= 0) { jaroslav@1890: s.tryCancel(e); jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: if (spins > 0) jaroslav@1890: --spins; jaroslav@1890: else if (s.waiter == null) jaroslav@1890: s.waiter = w; jaroslav@1890: else if (!timed) jaroslav@1890: LockSupport.park(this); jaroslav@1890: else if (nanos > spinForTimeoutThreshold) jaroslav@1890: LockSupport.parkNanos(this, nanos); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Gets rid of cancelled node s with original predecessor pred. jaroslav@1890: */ jaroslav@1890: void clean(QNode pred, QNode s) { jaroslav@1890: s.waiter = null; // forget thread jaroslav@1890: /* jaroslav@1890: * At any given time, exactly one node on list cannot be jaroslav@1890: * deleted -- the last inserted node. To accommodate this, jaroslav@1890: * if we cannot delete s, we save its predecessor as jaroslav@1890: * "cleanMe", deleting the previously saved version jaroslav@1890: * first. At least one of node s or the node previously jaroslav@1890: * saved can always be deleted, so this always terminates. jaroslav@1890: */ jaroslav@1890: while (pred.next == s) { // Return early if already unlinked jaroslav@1890: QNode h = head; jaroslav@1890: QNode hn = h.next; // Absorb cancelled first node as head jaroslav@1890: if (hn != null && hn.isCancelled()) { jaroslav@1890: advanceHead(h, hn); jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: QNode t = tail; // Ensure consistent read for tail jaroslav@1890: if (t == h) jaroslav@1890: return; jaroslav@1890: QNode tn = t.next; jaroslav@1890: if (t != tail) jaroslav@1890: continue; jaroslav@1890: if (tn != null) { jaroslav@1890: advanceTail(t, tn); jaroslav@1890: continue; jaroslav@1890: } jaroslav@1890: if (s != t) { // If not tail, try to unsplice jaroslav@1890: QNode sn = s.next; jaroslav@1890: if (sn == s || pred.casNext(s, sn)) jaroslav@1890: return; jaroslav@1890: } jaroslav@1890: QNode dp = cleanMe; jaroslav@1890: if (dp != null) { // Try unlinking previous cancelled node jaroslav@1890: QNode d = dp.next; jaroslav@1890: QNode dn; jaroslav@1890: if (d == null || // d is gone or jaroslav@1890: d == dp || // d is off list or jaroslav@1890: !d.isCancelled() || // d not cancelled or jaroslav@1890: (d != t && // d not tail and jaroslav@1890: (dn = d.next) != null && // has successor jaroslav@1890: dn != d && // that is on list jaroslav@1890: dp.casNext(d, dn))) // d unspliced jaroslav@1890: casCleanMe(dp, null); jaroslav@1890: if (dp == pred) jaroslav@1890: return; // s is already saved node jaroslav@1890: } else if (casCleanMe(null, pred)) jaroslav@1890: return; // Postpone cleaning s jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * The transferer. Set only in constructor, but cannot be declared jaroslav@1890: * as final without further complicating serialization. Since jaroslav@1890: * this is accessed only at most once per public method, there jaroslav@1890: * isn't a noticeable performance penalty for using volatile jaroslav@1890: * instead of final here. jaroslav@1890: */ jaroslav@1890: private transient volatile Transferer transferer; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a SynchronousQueue with nonfair access policy. jaroslav@1890: */ jaroslav@1890: public SynchronousQueue() { jaroslav@1890: this(false); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a SynchronousQueue with the specified fairness policy. jaroslav@1890: * jaroslav@1890: * @param fair if true, waiting threads contend in FIFO order for jaroslav@1890: * access; otherwise the order is unspecified. jaroslav@1890: */ jaroslav@1890: public SynchronousQueue(boolean fair) { jaroslav@1890: transferer = fair ? new TransferQueue() : new TransferStack(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Adds the specified element to this queue, waiting if necessary for jaroslav@1890: * another thread to receive it. jaroslav@1890: * jaroslav@1890: * @throws InterruptedException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public void put(E o) throws InterruptedException { jaroslav@1890: if (o == null) throw new NullPointerException(); jaroslav@1890: if (transferer.transfer(o, false, 0) == null) { jaroslav@1890: Thread.interrupted(); jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this queue, waiting if necessary jaroslav@1890: * up to the specified wait time for another thread to receive it. jaroslav@1890: * jaroslav@1890: * @return true if successful, or false if the jaroslav@1890: * specified waiting time elapses before a consumer appears. jaroslav@1890: * @throws InterruptedException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public boolean offer(E o, long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: if (o == null) throw new NullPointerException(); jaroslav@1890: if (transferer.transfer(o, true, unit.toNanos(timeout)) != null) jaroslav@1890: return true; jaroslav@1890: if (!Thread.interrupted()) jaroslav@1890: return false; jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Inserts the specified element into this queue, if another thread is jaroslav@1890: * waiting to receive it. jaroslav@1890: * jaroslav@1890: * @param e the element to add jaroslav@1890: * @return true if the element was added to this queue, else jaroslav@1890: * false jaroslav@1890: * @throws NullPointerException if the specified element is null jaroslav@1890: */ jaroslav@1890: public boolean offer(E e) { jaroslav@1890: if (e == null) throw new NullPointerException(); jaroslav@1890: return transferer.transfer(e, true, 0) != null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Retrieves and removes the head of this queue, waiting if necessary jaroslav@1890: * for another thread to insert it. jaroslav@1890: * jaroslav@1890: * @return the head of this queue jaroslav@1890: * @throws InterruptedException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public E take() throws InterruptedException { jaroslav@1890: Object e = transferer.transfer(null, false, 0); jaroslav@1890: if (e != null) jaroslav@1890: return (E)e; jaroslav@1890: Thread.interrupted(); jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Retrieves and removes the head of this queue, waiting jaroslav@1890: * if necessary up to the specified wait time, for another thread jaroslav@1890: * to insert it. jaroslav@1890: * jaroslav@1890: * @return the head of this queue, or null if the jaroslav@1890: * specified waiting time elapses before an element is present. jaroslav@1890: * @throws InterruptedException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public E poll(long timeout, TimeUnit unit) throws InterruptedException { jaroslav@1890: Object e = transferer.transfer(null, true, unit.toNanos(timeout)); jaroslav@1890: if (e != null || !Thread.interrupted()) jaroslav@1890: return (E)e; jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Retrieves and removes the head of this queue, if another thread jaroslav@1890: * is currently making an element available. jaroslav@1890: * jaroslav@1890: * @return the head of this queue, or null if no jaroslav@1890: * element is available. jaroslav@1890: */ jaroslav@1890: public E poll() { jaroslav@1890: return (E)transferer.transfer(null, true, 0); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns true. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @return true jaroslav@1890: */ jaroslav@1890: public boolean isEmpty() { jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns zero. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @return zero. jaroslav@1890: */ jaroslav@1890: public int size() { jaroslav@1890: return 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns zero. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @return zero. jaroslav@1890: */ jaroslav@1890: public int remainingCapacity() { jaroslav@1890: return 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Does nothing. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: */ jaroslav@1890: public void clear() { jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns false. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @param o the element jaroslav@1890: * @return false jaroslav@1890: */ jaroslav@1890: public boolean contains(Object o) { jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns false. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @param o the element to remove jaroslav@1890: * @return false jaroslav@1890: */ jaroslav@1890: public boolean remove(Object o) { jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns false unless the given collection is empty. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @param c the collection jaroslav@1890: * @return false unless given collection is empty jaroslav@1890: */ jaroslav@1890: public boolean containsAll(Collection c) { jaroslav@1890: return c.isEmpty(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns false. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @param c the collection jaroslav@1890: * @return false jaroslav@1890: */ jaroslav@1890: public boolean removeAll(Collection c) { jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns false. jaroslav@1890: * A SynchronousQueue has no internal capacity. jaroslav@1890: * jaroslav@1890: * @param c the collection jaroslav@1890: * @return false jaroslav@1890: */ jaroslav@1890: public boolean retainAll(Collection c) { jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Always returns null. jaroslav@1890: * A SynchronousQueue does not return elements jaroslav@1890: * unless actively waited on. jaroslav@1890: * jaroslav@1890: * @return null jaroslav@1890: */ jaroslav@1890: public E peek() { jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an empty iterator in which hasNext always returns jaroslav@1890: * false. jaroslav@1890: * jaroslav@1890: * @return an empty iterator jaroslav@1890: */ jaroslav@1890: public Iterator iterator() { jaroslav@1890: return Collections.emptyIterator(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a zero-length array. jaroslav@1890: * @return a zero-length array jaroslav@1890: */ jaroslav@1890: public Object[] toArray() { jaroslav@1890: return new Object[0]; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Sets the zeroeth element of the specified array to null jaroslav@1890: * (if the array has non-zero length) and returns it. jaroslav@1890: * jaroslav@1890: * @param a the array jaroslav@1890: * @return the specified array jaroslav@1890: * @throws NullPointerException if the specified array is null jaroslav@1890: */ jaroslav@1890: public T[] toArray(T[] a) { jaroslav@1890: if (a.length > 0) jaroslav@1890: a[0] = null; jaroslav@1890: return a; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws UnsupportedOperationException {@inheritDoc} jaroslav@1890: * @throws ClassCastException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while ( (e = poll()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws UnsupportedOperationException {@inheritDoc} jaroslav@1890: * @throws ClassCastException {@inheritDoc} jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws IllegalArgumentException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public int drainTo(Collection c, int maxElements) { jaroslav@1890: if (c == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (c == this) jaroslav@1890: throw new IllegalArgumentException(); jaroslav@1890: int n = 0; jaroslav@1890: E e; jaroslav@1890: while (n < maxElements && (e = poll()) != null) { jaroslav@1890: c.add(e); jaroslav@1890: ++n; jaroslav@1890: } jaroslav@1890: return n; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * To cope with serialization strategy in the 1.5 version of jaroslav@1890: * SynchronousQueue, we declare some unused classes and fields jaroslav@1890: * that exist solely to enable serializability across versions. jaroslav@1890: * These fields are never used, so are initialized only if this jaroslav@1890: * object is ever serialized or deserialized. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: static class WaitQueue implements java.io.Serializable { } jaroslav@1890: static class LifoWaitQueue extends WaitQueue { jaroslav@1890: private static final long serialVersionUID = -3633113410248163686L; jaroslav@1890: } jaroslav@1890: static class FifoWaitQueue extends WaitQueue { jaroslav@1890: private static final long serialVersionUID = -3623113410248163686L; jaroslav@1890: } jaroslav@1890: private ReentrantLock qlock; jaroslav@1890: private WaitQueue waitingProducers; jaroslav@1890: private WaitQueue waitingConsumers; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Save the state to a stream (that is, serialize it). jaroslav@1890: * jaroslav@1890: * @param s the stream jaroslav@1890: */ jaroslav@1890: private void writeObject(java.io.ObjectOutputStream s) jaroslav@1890: throws java.io.IOException { jaroslav@1890: boolean fair = transferer instanceof TransferQueue; jaroslav@1890: if (fair) { jaroslav@1890: qlock = new ReentrantLock(true); jaroslav@1890: waitingProducers = new FifoWaitQueue(); jaroslav@1890: waitingConsumers = new FifoWaitQueue(); jaroslav@1890: } jaroslav@1890: else { jaroslav@1890: qlock = new ReentrantLock(); jaroslav@1890: waitingProducers = new LifoWaitQueue(); jaroslav@1890: waitingConsumers = new LifoWaitQueue(); jaroslav@1890: } jaroslav@1890: s.defaultWriteObject(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: private void readObject(final java.io.ObjectInputStream s) jaroslav@1890: throws java.io.IOException, ClassNotFoundException { jaroslav@1890: s.defaultReadObject(); jaroslav@1890: if (waitingProducers instanceof FifoWaitQueue) jaroslav@1890: transferer = new TransferQueue(); jaroslav@1890: else jaroslav@1890: transferer = new TransferStack(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: }