0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea, Bill Scherer, and Michael Scott with
0N/A * assistance from members of JCP JSR-166 Expert Group and released to
0N/A * the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/Apackage java.util.concurrent;
0N/Aimport java.util.concurrent.atomic.*;
0N/Aimport java.util.concurrent.locks.LockSupport;
0N/A
0N/A/**
0N/A * A synchronization point at which threads can pair and swap elements
0N/A * within pairs. Each thread presents some object on entry to the
0N/A * {@link #exchange exchange} method, matches with a partner thread,
0N/A * and receives its partner's object on return. An Exchanger may be
0N/A * viewed as a bidirectional form of a {@link SynchronousQueue}.
0N/A * Exchangers may be useful in applications such as genetic algorithms
0N/A * and pipeline designs.
0N/A *
0N/A * <p><b>Sample Usage:</b>
0N/A * Here are the highlights of a class that uses an {@code Exchanger}
0N/A * to swap buffers between threads so that the thread filling the
0N/A * buffer gets a freshly emptied one when it needs it, handing off the
0N/A * filled one to the thread emptying the buffer.
0N/A * <pre>{@code
0N/A * class FillAndEmpty {
0N/A * Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
0N/A * DataBuffer initialEmptyBuffer = ... a made-up type
0N/A * DataBuffer initialFullBuffer = ...
0N/A *
0N/A * class FillingLoop implements Runnable {
0N/A * public void run() {
0N/A * DataBuffer currentBuffer = initialEmptyBuffer;
0N/A * try {
0N/A * while (currentBuffer != null) {
0N/A * addToBuffer(currentBuffer);
0N/A * if (currentBuffer.isFull())
0N/A * currentBuffer = exchanger.exchange(currentBuffer);
0N/A * }
0N/A * } catch (InterruptedException ex) { ... handle ... }
0N/A * }
0N/A * }
0N/A *
0N/A * class EmptyingLoop implements Runnable {
0N/A * public void run() {
0N/A * DataBuffer currentBuffer = initialFullBuffer;
0N/A * try {
0N/A * while (currentBuffer != null) {
0N/A * takeFromBuffer(currentBuffer);
0N/A * if (currentBuffer.isEmpty())
0N/A * currentBuffer = exchanger.exchange(currentBuffer);
0N/A * }
0N/A * } catch (InterruptedException ex) { ... handle ...}
0N/A * }
0N/A * }
0N/A *
0N/A * void start() {
0N/A * new Thread(new FillingLoop()).start();
0N/A * new Thread(new EmptyingLoop()).start();
0N/A * }
0N/A * }
0N/A * }</pre>
0N/A *
0N/A * <p>Memory consistency effects: For each pair of threads that
0N/A * successfully exchange objects via an {@code Exchanger}, actions
0N/A * prior to the {@code exchange()} in each thread
0N/A * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
0N/A * those subsequent to a return from the corresponding {@code exchange()}
0N/A * in the other thread.
0N/A *
0N/A * @since 1.5
0N/A * @author Doug Lea and Bill Scherer and Michael Scott
0N/A * @param <V> The type of objects that may be exchanged
0N/A */
0N/Apublic class Exchanger<V> {
0N/A /*
0N/A * Algorithm Description:
0N/A *
0N/A * The basic idea is to maintain a "slot", which is a reference to
0N/A * a Node containing both an Item to offer and a "hole" waiting to
0N/A * get filled in. If an incoming "occupying" thread sees that the
0N/A * slot is null, it CAS'es (compareAndSets) a Node there and waits
0N/A * for another to invoke exchange. That second "fulfilling" thread
0N/A * sees that the slot is non-null, and so CASes it back to null,
0N/A * also exchanging items by CASing the hole, plus waking up the
0N/A * occupying thread if it is blocked. In each case CAS'es may
0N/A * fail because a slot at first appears non-null but is null upon
0N/A * CAS, or vice-versa. So threads may need to retry these
0N/A * actions.
0N/A *
0N/A * This simple approach works great when there are only a few
0N/A * threads using an Exchanger, but performance rapidly
0N/A * deteriorates due to CAS contention on the single slot when
0N/A * there are lots of threads using an exchanger. So instead we use
0N/A * an "arena"; basically a kind of hash table with a dynamically
0N/A * varying number of slots, any one of which can be used by
0N/A * threads performing an exchange. Incoming threads pick slots
0N/A * based on a hash of their Thread ids. If an incoming thread
0N/A * fails to CAS in its chosen slot, it picks an alternative slot
0N/A * instead. And similarly from there. If a thread successfully
0N/A * CASes into a slot but no other thread arrives, it tries
0N/A * another, heading toward the zero slot, which always exists even
0N/A * if the table shrinks. The particular mechanics controlling this
0N/A * are as follows:
0N/A *
0N/A * Waiting: Slot zero is special in that it is the only slot that
0N/A * exists when there is no contention. A thread occupying slot
0N/A * zero will block if no thread fulfills it after a short spin.
0N/A * In other cases, occupying threads eventually give up and try
0N/A * another slot. Waiting threads spin for a while (a period that
0N/A * should be a little less than a typical context-switch time)
0N/A * before either blocking (if slot zero) or giving up (if other
0N/A * slots) and restarting. There is no reason for threads to block
0N/A * unless there are unlikely to be any other threads present.
0N/A * Occupants are mainly avoiding memory contention so sit there
0N/A * quietly polling for a shorter period than it would take to
0N/A * block and then unblock them. Non-slot-zero waits that elapse
0N/A * because of lack of other threads waste around one extra
0N/A * context-switch time per try, which is still on average much
0N/A * faster than alternative approaches.
0N/A *
0N/A * Sizing: Usually, using only a few slots suffices to reduce
0N/A * contention. Especially with small numbers of threads, using
0N/A * too many slots can lead to just as poor performance as using
0N/A * too few of them, and there's not much room for error. The
0N/A * variable "max" maintains the number of slots actually in
0N/A * use. It is increased when a thread sees too many CAS
0N/A * failures. (This is analogous to resizing a regular hash table
0N/A * based on a target load factor, except here, growth steps are
0N/A * just one-by-one rather than proportional.) Growth requires
0N/A * contention failures in each of three tried slots. Requiring
0N/A * multiple failures for expansion copes with the fact that some
0N/A * failed CASes are not due to contention but instead to simple
0N/A * races between two threads or thread pre-emptions occurring
0N/A * between reading and CASing. Also, very transient peak
0N/A * contention can be much higher than the average sustainable
3735N/A * levels. An attempt to decrease the max limit is usually made
3735N/A * when a non-slot-zero wait elapses without being fulfilled.
0N/A * Threads experiencing elapsed waits move closer to zero, so
0N/A * eventually find existing (or future) threads even if the table
0N/A * has been shrunk due to inactivity. The chosen mechanics and
0N/A * thresholds for growing and shrinking are intrinsically
0N/A * entangled with indexing and hashing inside the exchange code,
0N/A * and can't be nicely abstracted out.
0N/A *
0N/A * Hashing: Each thread picks its initial slot to use in accord
0N/A * with a simple hashcode. The sequence is the same on each
0N/A * encounter by any given thread, but effectively random across
0N/A * threads. Using arenas encounters the classic cost vs quality
0N/A * tradeoffs of all hash tables. Here, we use a one-step FNV-1a
0N/A * hash code based on the current thread's Thread.getId(), along
0N/A * with a cheap approximation to a mod operation to select an
0N/A * index. The downside of optimizing index selection in this way
0N/A * is that the code is hardwired to use a maximum table size of
0N/A * 32. But this value more than suffices for known platforms and
0N/A * applications.
0N/A *
0N/A * Probing: On sensed contention of a selected slot, we probe
0N/A * sequentially through the table, analogously to linear probing
0N/A * after collision in a hash table. (We move circularly, in
0N/A * reverse order, to mesh best with table growth and shrinkage
0N/A * rules.) Except that to minimize the effects of false-alarms
0N/A * and cache thrashing, we try the first selected slot twice
0N/A * before moving.
0N/A *
0N/A * Padding: Even with contention management, slots are heavily
0N/A * contended, so use cache-padding to avoid poor memory
0N/A * performance. Because of this, slots are lazily constructed
0N/A * only when used, to avoid wasting this space unnecessarily.
0N/A * While isolation of locations is not much of an issue at first
0N/A * in an application, as time goes on and garbage-collectors
0N/A * perform compaction, slots are very likely to be moved adjacent
0N/A * to each other, which can cause much thrashing of cache lines on
0N/A * MPs unless padding is employed.
0N/A *
0N/A * This is an improvement of the algorithm described in the paper
0N/A * "A Scalable Elimination-based Exchange Channel" by William
0N/A * Scherer, Doug Lea, and Michael Scott in Proceedings of SCOOL05
0N/A * workshop. Available at: http://hdl.handle.net/1802/2104
0N/A */
0N/A
0N/A /** The number of CPUs, for sizing and spin control */
0N/A private static final int NCPU = Runtime.getRuntime().availableProcessors();
0N/A
0N/A /**
0N/A * The capacity of the arena. Set to a value that provides more
0N/A * than enough space to handle contention. On small machines
0N/A * most slots won't be used, but it is still not wasted because
0N/A * the extra space provides some machine-level address padding
0N/A * to minimize interference with heavily CAS'ed Slot locations.
0N/A * And on very large machines, performance eventually becomes
0N/A * bounded by memory bandwidth, not numbers of threads/CPUs.
0N/A * This constant cannot be changed without also modifying
0N/A * indexing and hashing algorithms.
0N/A */
0N/A private static final int CAPACITY = 32;
0N/A
0N/A /**
0N/A * The value of "max" that will hold all threads without
0N/A * contention. When this value is less than CAPACITY, some
0N/A * otherwise wasted expansion can be avoided.
0N/A */
0N/A private static final int FULL =
0N/A Math.max(0, Math.min(CAPACITY, NCPU / 2) - 1);
0N/A
0N/A /**
0N/A * The number of times to spin (doing nothing except polling a
0N/A * memory location) before blocking or giving up while waiting to
0N/A * be fulfilled. Should be zero on uniprocessors. On
0N/A * multiprocessors, this value should be large enough so that two
0N/A * threads exchanging items as fast as possible block only when
0N/A * one of them is stalled (due to GC or preemption), but not much
0N/A * longer, to avoid wasting CPU resources. Seen differently, this
0N/A * value is a little over half the number of cycles of an average
0N/A * context switch time on most systems. The value here is
0N/A * approximately the average of those across a range of tested
0N/A * systems.
0N/A */
0N/A private static final int SPINS = (NCPU == 1) ? 0 : 2000;
0N/A
0N/A /**
0N/A * The number of times to spin before blocking in timed waits.
0N/A * Timed waits spin more slowly because checking the time takes
0N/A * time. The best value relies mainly on the relative rate of
0N/A * System.nanoTime vs memory accesses. The value is empirically
0N/A * derived to work well across a variety of systems.
0N/A */
0N/A private static final int TIMED_SPINS = SPINS / 20;
0N/A
0N/A /**
0N/A * Sentinel item representing cancellation of a wait due to
0N/A * interruption, timeout, or elapsed spin-waits. This value is
0N/A * placed in holes on cancellation, and used as a return value
0N/A * from waiting methods to indicate failure to set or get hole.
0N/A */
0N/A private static final Object CANCEL = new Object();
0N/A
0N/A /**
0N/A * Value representing null arguments/returns from public
0N/A * methods. This disambiguates from internal requirement that
0N/A * holes start out as null to mean they are not yet set.
0N/A */
0N/A private static final Object NULL_ITEM = new Object();
0N/A
0N/A /**
0N/A * Nodes hold partially exchanged data. This class
0N/A * opportunistically subclasses AtomicReference to represent the
0N/A * hole. So get() returns hole, and compareAndSet CAS'es value
0N/A * into hole. This class cannot be parameterized as "V" because
0N/A * of the use of non-V CANCEL sentinels.
0N/A */
0N/A private static final class Node extends AtomicReference<Object> {
0N/A /** The element offered by the Thread creating this node. */
0N/A public final Object item;
0N/A
0N/A /** The Thread waiting to be signalled; null until waiting. */
0N/A public volatile Thread waiter;
0N/A
0N/A /**
0N/A * Creates node with given item and empty hole.
0N/A * @param item the item
0N/A */
0N/A public Node(Object item) {
0N/A this.item = item;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * A Slot is an AtomicReference with heuristic padding to lessen
0N/A * cache effects of this heavily CAS'ed location. While the
0N/A * padding adds noticeable space, all slots are created only on
0N/A * demand, and there will be more than one of them only when it
0N/A * would improve throughput more than enough to outweigh using
0N/A * extra space.
0N/A */
0N/A private static final class Slot extends AtomicReference<Object> {
0N/A // Improve likelihood of isolation on <= 64 byte cache lines
0N/A long q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe;
0N/A }
0N/A
0N/A /**
0N/A * Slot array. Elements are lazily initialized when needed.
0N/A * Declared volatile to enable double-checked lazy construction.
0N/A */
0N/A private volatile Slot[] arena = new Slot[CAPACITY];
0N/A
0N/A /**
0N/A * The maximum slot index being used. The value sometimes
0N/A * increases when a thread experiences too many CAS contentions,
0N/A * and sometimes decreases when a spin-wait elapses. Changes
0N/A * are performed only via compareAndSet, to avoid stale values
0N/A * when a thread happens to stall right before setting.
0N/A */
0N/A private final AtomicInteger max = new AtomicInteger();
0N/A
0N/A /**
0N/A * Main exchange function, handling the different policy variants.
0N/A * Uses Object, not "V" as argument and return value to simplify
0N/A * handling of sentinel values. Callers from public methods decode
0N/A * and cast accordingly.
0N/A *
0N/A * @param item the (non-null) item to exchange
0N/A * @param timed true if the wait is timed
0N/A * @param nanos if timed, the maximum wait time
0N/A * @return the other thread's item, or CANCEL if interrupted or timed out
0N/A */
0N/A private Object doExchange(Object item, boolean timed, long nanos) {
0N/A Node me = new Node(item); // Create in case occupying
0N/A int index = hashIndex(); // Index of current slot
0N/A int fails = 0; // Number of CAS failures
0N/A
0N/A for (;;) {
0N/A Object y; // Contents of current slot
0N/A Slot slot = arena[index];
0N/A if (slot == null) // Lazily initialize slots
0N/A createSlot(index); // Continue loop to reread
0N/A else if ((y = slot.get()) != null && // Try to fulfill
0N/A slot.compareAndSet(y, null)) {
0N/A Node you = (Node)y; // Transfer item
0N/A if (you.compareAndSet(null, item)) {
0N/A LockSupport.unpark(you.waiter);
0N/A return you.item;
0N/A } // Else cancelled; continue
0N/A }
0N/A else if (y == null && // Try to occupy
0N/A slot.compareAndSet(null, me)) {
0N/A if (index == 0) // Blocking wait for slot 0
3203N/A return timed ?
3203N/A awaitNanos(me, slot, nanos) :
3203N/A await(me, slot);
0N/A Object v = spinWait(me, slot); // Spin wait for non-0
0N/A if (v != CANCEL)
0N/A return v;
0N/A me = new Node(item); // Throw away cancelled node
0N/A int m = max.get();
0N/A if (m > (index >>>= 1)) // Decrease index
0N/A max.compareAndSet(m, m - 1); // Maybe shrink table
0N/A }
0N/A else if (++fails > 1) { // Allow 2 fails on 1st slot
0N/A int m = max.get();
0N/A if (fails > 3 && m < FULL && max.compareAndSet(m, m + 1))
0N/A index = m + 1; // Grow on 3rd failed slot
0N/A else if (--index < 0)
0N/A index = m; // Circularly traverse
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a hash index for the current thread. Uses a one-step
0N/A * FNV-1a hash code (http://www.isthe.com/chongo/tech/comp/fnv/)
0N/A * based on the current thread's Thread.getId(). These hash codes
0N/A * have more uniform distribution properties with respect to small
0N/A * moduli (here 1-31) than do other simple hashing functions.
0N/A *
0N/A * <p>To return an index between 0 and max, we use a cheap
0N/A * approximation to a mod operation, that also corrects for bias
0N/A * due to non-power-of-2 remaindering (see {@link
0N/A * java.util.Random#nextInt}). Bits of the hashcode are masked
0N/A * with "nbits", the ceiling power of two of table size (looked up
0N/A * in a table packed into three ints). If too large, this is
0N/A * retried after rotating the hash by nbits bits, while forcing new
0N/A * top bit to 0, which guarantees eventual termination (although
0N/A * with a non-random-bias). This requires an average of less than
0N/A * 2 tries for all table sizes, and has a maximum 2% difference
0N/A * from perfectly uniform slot probabilities when applied to all
0N/A * possible hash codes for sizes less than 32.
0N/A *
0N/A * @return a per-thread-random index, 0 <= index < max
0N/A */
0N/A private final int hashIndex() {
0N/A long id = Thread.currentThread().getId();
0N/A int hash = (((int)(id ^ (id >>> 32))) ^ 0x811c9dc5) * 0x01000193;
0N/A
0N/A int m = max.get();
0N/A int nbits = (((0xfffffc00 >> m) & 4) | // Compute ceil(log2(m+1))
0N/A ((0x000001f8 >>> m) & 2) | // The constants hold
0N/A ((0xffff00f2 >>> m) & 1)); // a lookup table
0N/A int index;
0N/A while ((index = hash & ((1 << nbits) - 1)) > m) // May retry on
0N/A hash = (hash >>> nbits) | (hash << (33 - nbits)); // non-power-2 m
0N/A return index;
0N/A }
0N/A
0N/A /**
0N/A * Creates a new slot at given index. Called only when the slot
0N/A * appears to be null. Relies on double-check using builtin
0N/A * locks, since they rarely contend. This in turn relies on the
0N/A * arena array being declared volatile.
0N/A *
0N/A * @param index the index to add slot at
0N/A */
0N/A private void createSlot(int index) {
0N/A // Create slot outside of lock to narrow sync region
0N/A Slot newSlot = new Slot();
0N/A Slot[] a = arena;
0N/A synchronized (a) {
0N/A if (a[index] == null)
0N/A a[index] = newSlot;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Tries to cancel a wait for the given node waiting in the given
0N/A * slot, if so, helping clear the node from its slot to avoid
0N/A * garbage retention.
0N/A *
0N/A * @param node the waiting node
0N/A * @param the slot it is waiting in
0N/A * @return true if successfully cancelled
0N/A */
0N/A private static boolean tryCancel(Node node, Slot slot) {
0N/A if (!node.compareAndSet(null, CANCEL))
0N/A return false;
0N/A if (slot.get() == node) // pre-check to minimize contention
0N/A slot.compareAndSet(node, null);
0N/A return true;
0N/A }
0N/A
0N/A // Three forms of waiting. Each just different enough not to merge
0N/A // code with others.
0N/A
0N/A /**
0N/A * Spin-waits for hole for a non-0 slot. Fails if spin elapses
0N/A * before hole filled. Does not check interrupt, relying on check
0N/A * in public exchange method to abort if interrupted on entry.
0N/A *
0N/A * @param node the waiting node
0N/A * @return on success, the hole; on failure, CANCEL
0N/A */
0N/A private static Object spinWait(Node node, Slot slot) {
0N/A int spins = SPINS;
0N/A for (;;) {
0N/A Object v = node.get();
0N/A if (v != null)
0N/A return v;
0N/A else if (spins > 0)
0N/A --spins;
0N/A else
0N/A tryCancel(node, slot);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Waits for (by spinning and/or blocking) and gets the hole
0N/A * filled in by another thread. Fails if interrupted before
0N/A * hole filled.
0N/A *
0N/A * When a node/thread is about to block, it sets its waiter field
0N/A * and then rechecks state at least one more time before actually
0N/A * parking, thus covering race vs fulfiller noticing that waiter
0N/A * is non-null so should be woken.
0N/A *
0N/A * Thread interruption status is checked only surrounding calls to
0N/A * park. The caller is assumed to have checked interrupt status
0N/A * on entry.
0N/A *
0N/A * @param node the waiting node
0N/A * @return on success, the hole; on failure, CANCEL
0N/A */
0N/A private static Object await(Node node, Slot slot) {
0N/A Thread w = Thread.currentThread();
0N/A int spins = SPINS;
0N/A for (;;) {
0N/A Object v = node.get();
0N/A if (v != null)
0N/A return v;
0N/A else if (spins > 0) // Spin-wait phase
0N/A --spins;
0N/A else if (node.waiter == null) // Set up to block next
0N/A node.waiter = w;
0N/A else if (w.isInterrupted()) // Abort on interrupt
0N/A tryCancel(node, slot);
0N/A else // Block
0N/A LockSupport.park(node);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Waits for (at index 0) and gets the hole filled in by another
0N/A * thread. Fails if timed out or interrupted before hole filled.
0N/A * Same basic logic as untimed version, but a bit messier.
0N/A *
0N/A * @param node the waiting node
0N/A * @param nanos the wait time
0N/A * @return on success, the hole; on failure, CANCEL
0N/A */
0N/A private Object awaitNanos(Node node, Slot slot, long nanos) {
0N/A int spins = TIMED_SPINS;
0N/A long lastTime = 0;
0N/A Thread w = null;
0N/A for (;;) {
0N/A Object v = node.get();
0N/A if (v != null)
0N/A return v;
0N/A long now = System.nanoTime();
0N/A if (w == null)
0N/A w = Thread.currentThread();
0N/A else
0N/A nanos -= now - lastTime;
0N/A lastTime = now;
0N/A if (nanos > 0) {
0N/A if (spins > 0)
0N/A --spins;
0N/A else if (node.waiter == null)
0N/A node.waiter = w;
0N/A else if (w.isInterrupted())
0N/A tryCancel(node, slot);
0N/A else
0N/A LockSupport.parkNanos(node, nanos);
0N/A }
0N/A else if (tryCancel(node, slot) && !w.isInterrupted())
0N/A return scanOnTimeout(node);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Sweeps through arena checking for any waiting threads. Called
0N/A * only upon return from timeout while waiting in slot 0. When a
0N/A * thread gives up on a timed wait, it is possible that a
0N/A * previously-entered thread is still waiting in some other
0N/A * slot. So we scan to check for any. This is almost always
0N/A * overkill, but decreases the likelihood of timeouts when there
0N/A * are other threads present to far less than that in lock-based
0N/A * exchangers in which earlier-arriving threads may still be
0N/A * waiting on entry locks.
0N/A *
0N/A * @param node the waiting node
0N/A * @return another thread's item, or CANCEL
0N/A */
0N/A private Object scanOnTimeout(Node node) {
0N/A Object y;
0N/A for (int j = arena.length - 1; j >= 0; --j) {
0N/A Slot slot = arena[j];
0N/A if (slot != null) {
0N/A while ((y = slot.get()) != null) {
0N/A if (slot.compareAndSet(y, null)) {
0N/A Node you = (Node)y;
0N/A if (you.compareAndSet(null, node.item)) {
0N/A LockSupport.unpark(you.waiter);
0N/A return you.item;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A }
0N/A return CANCEL;
0N/A }
0N/A
0N/A /**
0N/A * Creates a new Exchanger.
0N/A */
0N/A public Exchanger() {
0N/A }
0N/A
0N/A /**
0N/A * Waits for another thread to arrive at this exchange point (unless
0N/A * the current thread is {@linkplain Thread#interrupt interrupted}),
0N/A * and then transfers the given object to it, receiving its object
0N/A * in return.
0N/A *
0N/A * <p>If another thread is already waiting at the exchange point then
0N/A * it is resumed for thread scheduling purposes and receives the object
0N/A * passed in by the current thread. The current thread returns immediately,
0N/A * receiving the object passed to the exchange by that other thread.
0N/A *
0N/A * <p>If no other thread is already waiting at the exchange then the
0N/A * current thread is disabled for thread scheduling purposes and lies
0N/A * dormant until one of two things happens:
0N/A * <ul>
0N/A * <li>Some other thread enters the exchange; or
3203N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
3203N/A * the current thread.
0N/A * </ul>
0N/A * <p>If the current thread:
0N/A * <ul>
0N/A * <li>has its interrupted status set on entry to this method; or
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while waiting
0N/A * for the exchange,
0N/A * </ul>
0N/A * then {@link InterruptedException} is thrown and the current thread's
0N/A * interrupted status is cleared.
0N/A *
0N/A * @param x the object to exchange
0N/A * @return the object provided by the other thread
0N/A * @throws InterruptedException if the current thread was
0N/A * interrupted while waiting
0N/A */
0N/A public V exchange(V x) throws InterruptedException {
0N/A if (!Thread.interrupted()) {
3203N/A Object v = doExchange((x == null) ? NULL_ITEM : x, false, 0);
0N/A if (v == NULL_ITEM)
0N/A return null;
0N/A if (v != CANCEL)
0N/A return (V)v;
0N/A Thread.interrupted(); // Clear interrupt status on IE throw
0N/A }
0N/A throw new InterruptedException();
0N/A }
0N/A
0N/A /**
0N/A * Waits for another thread to arrive at this exchange point (unless
0N/A * the current thread is {@linkplain Thread#interrupt interrupted} or
0N/A * the specified waiting time elapses), and then transfers the given
0N/A * object to it, receiving its object in return.
0N/A *
0N/A * <p>If another thread is already waiting at the exchange point then
0N/A * it is resumed for thread scheduling purposes and receives the object
0N/A * passed in by the current thread. The current thread returns immediately,
0N/A * receiving the object passed to the exchange by that other thread.
0N/A *
0N/A * <p>If no other thread is already waiting at the exchange then the
0N/A * current thread is disabled for thread scheduling purposes and lies
0N/A * dormant until one of three things happens:
0N/A * <ul>
0N/A * <li>Some other thread enters the exchange; or
0N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
0N/A * the current thread; or
0N/A * <li>The specified waiting time elapses.
0N/A * </ul>
0N/A * <p>If the current thread:
0N/A * <ul>
0N/A * <li>has its interrupted status set on entry to this method; or
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while waiting
0N/A * for the exchange,
0N/A * </ul>
0N/A * then {@link InterruptedException} is thrown and the current thread's
0N/A * interrupted status is cleared.
0N/A *
0N/A * <p>If the specified waiting time elapses then {@link
0N/A * TimeoutException} is thrown. If the time is less than or equal
0N/A * to zero, the method will not wait at all.
0N/A *
0N/A * @param x the object to exchange
0N/A * @param timeout the maximum time to wait
0N/A * @param unit the time unit of the <tt>timeout</tt> argument
0N/A * @return the object provided by the other thread
0N/A * @throws InterruptedException if the current thread was
0N/A * interrupted while waiting
0N/A * @throws TimeoutException if the specified waiting time elapses
0N/A * before another thread enters the exchange
0N/A */
0N/A public V exchange(V x, long timeout, TimeUnit unit)
0N/A throws InterruptedException, TimeoutException {
0N/A if (!Thread.interrupted()) {
3203N/A Object v = doExchange((x == null) ? NULL_ITEM : x,
0N/A true, unit.toNanos(timeout));
0N/A if (v == NULL_ITEM)
0N/A return null;
0N/A if (v != CANCEL)
0N/A return (V)v;
0N/A if (!Thread.interrupted())
0N/A throw new TimeoutException();
0N/A }
0N/A throw new InterruptedException();
0N/A }
0N/A}