ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Exchanger.java
Revision: 1.58
Committed: Fri Dec 23 21:17:36 2011 UTC (12 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.57: +2 -2 lines
Log Message:
tiny comment improvement

File Contents

# User Rev Content
1 dl 1.2 /*
2 dl 1.16 * Written by Doug Lea, Bill Scherer, and Michael Scott with
3     * assistance from members of JCP JSR-166 Expert Group and released to
4     * the public domain, as explained at
5 jsr166 1.48 * http://creativecommons.org/publicdomain/zero/1.0/
6 dl 1.2 */
7    
8 tim 1.1 package java.util.concurrent;
9 jsr166 1.54 import java.util.concurrent.atomic.AtomicInteger;
10     import java.util.concurrent.atomic.AtomicReference;
11 dl 1.38 import java.util.concurrent.locks.LockSupport;
12 tim 1.1
13     /**
14 dl 1.28 * A synchronization point at which threads can pair and swap elements
15 jsr166 1.39 * within pairs. Each thread presents some object on entry to the
16 dl 1.28 * {@link #exchange exchange} method, matches with a partner thread,
17 jsr166 1.39 * and receives its partner's object on return. An Exchanger may be
18     * viewed as a bidirectional form of a {@link SynchronousQueue}.
19     * Exchangers may be useful in applications such as genetic algorithms
20     * and pipeline designs.
21 tim 1.1 *
22     * <p><b>Sample Usage:</b>
23 jsr166 1.29 * Here are the highlights of a class that uses an {@code Exchanger}
24     * to swap buffers between threads so that the thread filling the
25     * buffer gets a freshly emptied one when it needs it, handing off the
26     * filled one to the thread emptying the buffer.
27 jsr166 1.50 * <pre> {@code
28 tim 1.1 * class FillAndEmpty {
29 jsr166 1.29 * Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
30 dl 1.9 * DataBuffer initialEmptyBuffer = ... a made-up type
31     * DataBuffer initialFullBuffer = ...
32 tim 1.1 *
33     * class FillingLoop implements Runnable {
34     * public void run() {
35 dl 1.9 * DataBuffer currentBuffer = initialEmptyBuffer;
36 tim 1.1 * try {
37     * while (currentBuffer != null) {
38     * addToBuffer(currentBuffer);
39 dl 1.30 * if (currentBuffer.isFull())
40 tim 1.1 * currentBuffer = exchanger.exchange(currentBuffer);
41     * }
42 tim 1.7 * } catch (InterruptedException ex) { ... handle ... }
43 tim 1.1 * }
44     * }
45     *
46     * class EmptyingLoop implements Runnable {
47     * public void run() {
48 dl 1.9 * DataBuffer currentBuffer = initialFullBuffer;
49 tim 1.1 * try {
50     * while (currentBuffer != null) {
51     * takeFromBuffer(currentBuffer);
52 dl 1.30 * if (currentBuffer.isEmpty())
53 tim 1.1 * currentBuffer = exchanger.exchange(currentBuffer);
54     * }
55 tim 1.7 * } catch (InterruptedException ex) { ... handle ...}
56 tim 1.1 * }
57     * }
58     *
59     * void start() {
60     * new Thread(new FillingLoop()).start();
61     * new Thread(new EmptyingLoop()).start();
62     * }
63 jsr166 1.50 * }}</pre>
64 tim 1.1 *
65 jsr166 1.27 * <p>Memory consistency effects: For each pair of threads that
66     * successfully exchange objects via an {@code Exchanger}, actions
67     * prior to the {@code exchange()} in each thread
68     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
69     * those subsequent to a return from the corresponding {@code exchange()}
70     * in the other thread.
71 brian 1.22 *
72 tim 1.1 * @since 1.5
73 dl 1.16 * @author Doug Lea and Bill Scherer and Michael Scott
74 dl 1.11 * @param <V> The type of objects that may be exchanged
75 tim 1.1 */
76     public class Exchanger<V> {
77 dl 1.55
78 dl 1.16 /*
79 jsr166 1.57 * Overview: The core algorithm is, for an exchange "slot",
80 dl 1.55 * and a participant (caller) with an item:
81 dl 1.16 *
82 jsr166 1.56 * for (;;) {
83 dl 1.55 * if (slot is empty) { // offer
84     * place item in a Node;
85     * if (can CAS slot from empty to node) {
86     * wait for release;
87     * return matching item in node;
88     * }
89     * }
90     * else if (can CAS slot from node to empty) { // release
91     * get the item in node;
92     * set matching item in node;
93     * release waiting thread;
94     * }
95     * // else retry on CAS failure
96     * }
97     *
98     * This is among the simplest forms of a "dual data structure" --
99     * see Scott and Scherer's DISC 04 paper and
100     * http://www.cs.rochester.edu/research/synchronization/pseudocode/duals.html
101     *
102     * This works great in principle. But in practice, like many
103     * algorithms centered on atomic updates to a single location, it
104     * scales horribly when there are more than a few participants
105     * using the same Exchanger. So the implementation instead uses a
106     * form of elimination arena, that spreads out this contention by
107     * arranging that some threads typically use different slots,
108     * while still ensuring that eventually, any two parties will be
109     * able to exchange items. That is, we cannot completely partition
110     * across threads, but instead give threads arena indices that
111     * will on average grow under contention and shrink under lack of
112     * contention. We approach this by defining the Nodes that we need
113     * anyway as ThreadLocals, and include in them per-thread index
114     * and related bookkeeping state. (We can safely reuse per-thread
115     * nodes rather than creating them fresh each time because slots
116     * alternate between pointing to a node vs null, so cannot
117 jsr166 1.57 * encounter ABA problems. However, we do need some care in
118 dl 1.55 * resetting them between uses.)
119     *
120     * Implementing an effective arena requires allocating a bunch of
121     * space, so we only do so upon detecting contention (except on
122     * uniprocessors, where they wouldn't help, so aren't used).
123     * Otherwise, exchanges use the single-slot slotExchange method.
124     * On contention, not only must the slots be in different
125     * locations, but the locations must not encounter memory
126     * contention due to being on the same cache line (or more
127     * generally, the same coherence unit). Because, as of this
128     * writing, there is no way to determine cacheline size, we define
129     * a value that is enough for common platforms. Additionally,
130     * extra care elsewhere is taken to avoid other false/unintended
131     * sharing and to enhance locality, including adding padding to
132     * Nodes, embedding "bound" as an Exchanger field, and reworking
133     * some park/unpark mechanics compared to LockSupport versions.
134     *
135     * The arena starts out with only one used slot. We expand the
136     * effective arena size by tracking collisions; i.e., failed CASes
137     * while trying to exchange. By nature of the above algorithm, the
138     * only kinds of collision that reliably indicate contention are
139     * when two attempted releases collide -- one of two attempted
140     * offers can legitimately fail to CAS without indicating
141     * contention by more than one other thread. (Note: it is possible
142     * but not worthwhile to more precisely detect contention by
143     * reading slot values after CAS failures.) When a thread has
144     * collided at each slot within the current arena bound, it tries
145     * to expand the arena size by one. We track collisions within
146     * bounds by using a version (sequence) number on the "bound"
147     * field, and conservatively reset collision counts when a
148     * participant notices that bound has been updated (in either
149     * direction).
150     *
151     * The effective arena size is reduced (when there is more than
152     * one slot) by giving up on waiting after a while and trying to
153     * decrement the arena size on expiration. The value of "a while"
154     * is an empirical matter. We implement by piggybacking on the
155     * use of spin->yield->block that is essential for reasonable
156     * waiting performance anyway -- in a busy exchanger, offers are
157     * usually almost immediately released, in which case context
158     * switching on multiprocessors is extremely slow/wasteful. Arena
159     * waits just omit the blocking part, and instead cancel. The spin
160     * count is empirically chosen to be a value that avoids blocking
161     * 99% of the time under maximum sustained exchange rates on a
162     * range of test machines. Spins and yields entail some limited
163     * randomness (using a cheap xorshift) to avoid regular patterns
164     * that can induce unproductive grow/shrink cycles. (Using a
165     * pseudorandom also helps regularize spin cycle duration by
166     * making branches unpredictable.) Also, during an offer, a
167     * waiter can "know" that it will be released when its slot has
168     * changed, but cannot yet proceed until match is set. In the
169     * mean time it cannot cancel the offer, so instead spins/yields.
170     * Note: It is possible to avoid this secondary check by changing
171     * the linearization point to be a CAS of the match field (as done
172     * in one case in the Scott & Scherer DISC paper), which also
173     * increases asynchrony a bit, at the expense of poorer collision
174     * detection and inability to always reuse per-thread nodes. So
175     * the current scheme is typically a better tradeoff.
176     *
177     * On collisions, indices traverse the arena cyclically in reverse
178     * order, restarting at the maximum index (which will tend to be
179     * sparsest) when bounds change. (On expirations, indices instead
180     * are halved until reaching 0.) It is possible (and has been
181     * tried) to use randomized, prime-value-stepped, or double-hash
182     * style traversal instead of simple cyclic traversal to reduce
183     * bunching. But empirically, whatever benefits these may have
184     * don't overcome their added overhead: We are managing operations
185     * that occur very quickly unless there is sustained contention,
186     * so simpler/faster control policies work better than more
187     * accurate but slower ones.
188     *
189     * Because we use expiration for arena size control, we cannot
190     * throw TimeoutExceptions in the timed version of the public
191     * exchange method until the arena size has shrunken to zero (or
192     * the arena isn't enabled). This may delay response to timeout
193     * but is still within spec.
194     *
195     * Essentially all of the implementation is in methods
196     * slotExchange and arenaExchange. These have similar overall
197     * structure, but differ in too many details to combine. The
198     * slotExchange method uses the single Exchanger field "slot"
199     * rather than arena array elements. However, it still needs
200     * minimal collision detection to trigger arena construction.
201     * (The messiest part is making sure interrupt status and
202     * InterruptedExceptions come out right during transitions when
203     * both methods may be called. This is done by using null return
204     * as a sentinel to recheck interrupt status.)
205     *
206 jsr166 1.57 * As is too common in this sort of code, methods are monolithic
207 dl 1.55 * because most of the logic relies on reads of fields that are
208     * maintained as local variables so can't be nicely factored --
209     * mainly, here, bulky spin->yield->block/cancel code), and
210     * heavily dependent on intrinsics (Unsafe) to use inlined
211 jsr166 1.57 * embedded CAS and related memory access operations (that tend
212 dl 1.55 * not to be as readily inlined by dynamic compilers when they are
213     * hidden behind other methods that would more nicely name and
214     * encapsulate the intended effects). This includes the use of
215     * putOrderedX to clear fields of the per-thread Nodes between
216     * uses. Note that field Node.item is not declared as volatile
217     * even though it is read by releasing threads, because they only
218 jsr166 1.57 * do so after CAS operations that must precede access, and all
219 dl 1.55 * uses by the owning thread are otherwise acceptably ordered by
220     * other operations. (Because the actual points of atomicity are
221     * slot CASes, it would also be legal for the write to Node.match
222     * in a release to be weaker than a full volatile write. However,
223     * this is not done because it could allow further postponement of
224     * the write, delaying progress.)
225     */
226    
227     /**
228     * The byte distance (as a shift value) between any two used slots
229     * in the arena. 1 << ASHIFT should be at least cacheline size.
230     */
231     private static final int ASHIFT = 7;
232    
233     /**
234     * The maximum supported arena index. The maximum allocatable
235     * arena size is MMASK + 1. Must be a power of two minus one, less
236     * than (1<<(31-ASHIFT)). The cap of 255 (0xff) more than suffices
237     * for the expected scaling limits of the main algorithms.
238 dl 1.16 */
239 dl 1.55 private static final int MMASK = 0xff;
240    
241     /**
242     * Unit for sequence/version bits of bound field. Each successful
243     * change to the bound also adds SEQ.
244     */
245     private static final int SEQ = MMASK + 1;
246 dl 1.2
247 dl 1.32 /** The number of CPUs, for sizing and spin control */
248 dl 1.37 private static final int NCPU = Runtime.getRuntime().availableProcessors();
249 dl 1.32
250 jsr166 1.17 /**
251 dl 1.55 * The maximum slot index of the arena: The number of slots that
252     * can in principle hold all threads without contention, or at
253     * most the maximum indexable value.
254 dl 1.37 */
255 dl 1.55 static final int FULL = (NCPU >= (MMASK << 1)) ? MMASK : NCPU >>> 1;
256 dl 1.37
257     /**
258 dl 1.55 * The bound for spins while waiting for a match. The actual
259     * number of iterations will on average be about twice this value
260     * due to randomization. Note: Spinning is disabled when NCPU==1.
261 dl 1.37 */
262 dl 1.55 private static final int SPINS = 1 << 10;
263 dl 1.37
264     /**
265 dl 1.55 * Value representing null arguments/returns from public
266     * methods. Needed because the API originally didn't disallow null
267     * arguments, which it should have.
268 dl 1.16 */
269 dl 1.55 private static final Object NULL_ITEM = new Object();
270 dl 1.34
271     /**
272 dl 1.55 * Sentinel value returned by internal exchange methods upon
273     * timeout, to avoid need for separate timed versions of these
274     * methods.
275 dl 1.34 */
276 dl 1.55 private static final Object TIMED_OUT = new Object();
277 dl 1.34
278     /**
279 dl 1.55 * Nodes hold partially exchanged data, plus other per-thread
280     * bookkeeping.
281 dl 1.34 */
282 dl 1.55 static final class Node {
283     int index; // Arena index
284     int bound; // Last recorded value of Exchanger.bound
285     int collides; // Number of CAS failures at current bound
286     int hash; // Pseudo-random for spins
287     Object item; // This thread's current item
288     volatile Object match; // Item provided by releasing thread
289     volatile Thread parked; // Set to this thread when parked, else null
290    
291     // Padding to ameliorate unfortunate memory placements
292     Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe, pf;
293     Object q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe, qf;
294     }
295    
296     /** The corresponding thread local class */
297     static final class Participant extends ThreadLocal<Node> {
298     public Node initialValue() { return new Node(); }
299     }
300 dl 1.32
301     /**
302 dl 1.55 * Per-thread state
303 dl 1.32 */
304 dl 1.55 private final Participant participant;
305 dl 1.32
306     /**
307 dl 1.55 * Elimination array; null until enabled (within slotExchange).
308     * Element accesses use emulation of volatile gets and CAS.
309     */
310     private volatile Node[] arena;
311 dl 1.5
312 dl 1.34 /**
313 dl 1.55 * Slot used until contention detected.
314 dl 1.34 */
315 dl 1.55 private volatile Node slot;
316 dl 1.5
317 dl 1.16 /**
318 dl 1.55 * The index of the largest valid arena position, OR'ed with SEQ
319     * number in high bits, incremented on each update. The initial
320     * update from 0 to SEQ is used to ensure that the arena array is
321     * constructed only once.
322 dl 1.16 */
323 dl 1.55 private volatile int bound;
324 dl 1.2
325 dl 1.16 /**
326 dl 1.55 * Exchange function when arenas enabled. See above for explanation.
327 dl 1.30 *
328 dl 1.55 * @param item the (nonnull) item to exchange
329 dl 1.30 * @param timed true if the wait is timed
330 jsr166 1.58 * @param ns if timed, the maximum wait time, else 0L
331 dl 1.55 * @return the other thread's item; or null if interrupted; or
332     * TIMED_OUT if timed and timed out
333     */
334     private final Object arenaExchange(Object item, boolean timed, long ns) {
335     Node[] a = arena;
336     Node p = participant.get();
337     for (int i = p.index;;) { // access slot at i
338     int b, m, c; long j; // j is raw array offset
339     Node q = (Node)U.getObjectVolatile(a, j = (i << ASHIFT) + ABASE);
340     if (q != null && U.compareAndSwapObject(a, j, q, null)) {
341     Object v = q.item; // release
342     q.match = item;
343     Thread w = q.parked;
344     if (w != null)
345     U.unpark(w);
346     return v;
347 dl 1.37 }
348 dl 1.55 else if (i <= (m = (b = bound) & MMASK) && q == null) {
349     p.item = item; // offer
350     if (U.compareAndSwapObject(a, j, null, p)) {
351 jsr166 1.56 long end = (timed && m == 0) ? System.nanoTime() + ns : 0L;
352 dl 1.55 Thread t = Thread.currentThread(); // wait
353     for (int h = p.hash, spins = SPINS;;) {
354     Object v = p.match;
355     if (v != null) {
356     U.putOrderedObject(p, MATCH, null);
357     p.item = null; // clear for next use
358     p.hash = h;
359     return v;
360     }
361     else if (spins > 0) {
362     h ^= h << 1; h ^= h >>> 3; h ^= h << 10; // xorshift
363     if (h == 0) // initialize hash
364     h = SPINS | (int)t.getId();
365     else if (h < 0 && // approx 50% true
366     (--spins & ((SPINS >>> 1) - 1)) == 0)
367     Thread.yield(); // two yields per wait
368     }
369     else if (U.getObjectVolatile(a, j) != p)
370     spins = SPINS; // releaser hasn't set match yet
371     else if (!t.isInterrupted() && m == 0 &&
372     (!timed ||
373     (ns = end - System.nanoTime()) > 0L)) {
374     U.putObject(t, BLOCKER, this); // emulate LockSupport
375     p.parked = t; // minimize window
376     if (U.getObjectVolatile(a, j) == p)
377     U.park(false, ns);
378     p.parked = null;
379     U.putObject(t, BLOCKER, null);
380     }
381     else if (U.getObjectVolatile(a, j) == p &&
382     U.compareAndSwapObject(a, j, p, null)) {
383     if (m != 0) // try to shrink
384     U.compareAndSwapInt(this, BOUND, b, b + SEQ - 1);
385     p.item = null;
386     p.hash = h;
387     i = p.index >>>= 1; // descend
388     if (Thread.interrupted())
389     return null;
390     if (timed && m == 0 && ns <= 0L)
391     return TIMED_OUT;
392     break; // expired; restart
393     }
394     }
395     }
396     else
397     p.item = null; // clear offer
398 dl 1.2 }
399 dl 1.55 else {
400     if (p.bound != b) { // stale; reset
401     p.bound = b;
402     p.collides = 0;
403     i = (i != m || m == 0) ? m : m - 1;
404     }
405     else if ((c = p.collides) < m || m == FULL ||
406     !U.compareAndSwapInt(this, BOUND, b, b + SEQ + 1)) {
407     p.collides = c + 1;
408     i = (i == 0) ? m : i - 1; // cyclically traverse
409     }
410     else
411     i = m + 1; // grow
412     p.index = i;
413 dl 1.34 }
414 dl 1.37 }
415     }
416 dl 1.2
417 dl 1.37 /**
418 dl 1.55 * Exchange function used until arenas enabled. See above for explanation.
419     *
420     * @param item the item to exchange
421     * @param timed true if the wait is timed
422 jsr166 1.58 * @param ns if timed, the maximum wait time, else 0L
423 dl 1.55 * @return the other thread's item; or null if either the arena
424     * was enabled or the thread was interrupted before completion; or
425     * TIMED_OUT if timed and timed out
426     */
427     private final Object slotExchange(Object item, boolean timed, long ns) {
428     Node p = participant.get();
429     Thread t = Thread.currentThread();
430     if (t.isInterrupted()) // preserve interrupt status so caller can recheck
431     return null;
432    
433     for (Node q;;) {
434     if ((q = slot) != null) {
435     if (U.compareAndSwapObject(this, SLOT, q, null)) {
436     Object v = q.item;
437     q.match = item;
438     Thread w = q.parked;
439     if (w != null)
440     U.unpark(w);
441     return v;
442     }
443     // create arena on contention, but continue until slot null
444     if (NCPU > 1 && bound == 0 &&
445     U.compareAndSwapInt(this, BOUND, 0, SEQ))
446     arena = new Node[(FULL + 2) << ASHIFT];
447     }
448     else if (arena != null)
449     return null; // caller must reroute to arenaExchange
450     else {
451     p.item = item;
452     if (U.compareAndSwapObject(this, SLOT, null, p))
453     break;
454     p.item = null;
455     }
456 dl 1.16 }
457    
458 dl 1.55 // await release
459     int h = p.hash;
460 jsr166 1.56 long end = timed ? System.nanoTime() + ns : 0L;
461 dl 1.55 int spins = (NCPU > 1) ? SPINS : 1;
462     Object v;
463     while ((v = p.match) == null) {
464     if (spins > 0) {
465     h ^= h << 1; h ^= h >>> 3; h ^= h << 10;
466     if (h == 0)
467     h = SPINS | (int)t.getId();
468     else if (h < 0 && (--spins & ((SPINS >>> 1) - 1)) == 0)
469     Thread.yield();
470 jsr166 1.53 }
471 dl 1.55 else if (slot != p)
472     spins = SPINS;
473     else if (!t.isInterrupted() && arena == null &&
474     (!timed || (ns = end - System.nanoTime()) > 0L)) {
475     U.putObject(t, BLOCKER, this);
476     p.parked = t;
477     if (slot == p)
478     U.park(false, ns);
479     p.parked = null;
480     U.putObject(t, BLOCKER, null);
481 dl 1.37 }
482 dl 1.55 else if (U.compareAndSwapObject(this, SLOT, p, null)) {
483     v = timed && ns <= 0L && !t.isInterrupted() ? TIMED_OUT : null;
484     break;
485 dl 1.16 }
486     }
487 dl 1.55 U.putOrderedObject(p, MATCH, null);
488     p.item = null;
489     p.hash = h;
490     return v;
491 dl 1.37 }
492    
493     /**
494     * Creates a new Exchanger.
495     */
496     public Exchanger() {
497 dl 1.55 participant = new Participant();
498 tim 1.1 }
499    
500     /**
501     * Waits for another thread to arrive at this exchange point (unless
502 jsr166 1.44 * the current thread is {@linkplain Thread#interrupt interrupted}),
503 tim 1.1 * and then transfers the given object to it, receiving its object
504     * in return.
505 jsr166 1.17 *
506 tim 1.1 * <p>If another thread is already waiting at the exchange point then
507     * it is resumed for thread scheduling purposes and receives the object
508 jsr166 1.39 * passed in by the current thread. The current thread returns immediately,
509 tim 1.1 * receiving the object passed to the exchange by that other thread.
510 jsr166 1.17 *
511 jsr166 1.15 * <p>If no other thread is already waiting at the exchange then the
512 tim 1.1 * current thread is disabled for thread scheduling purposes and lies
513     * dormant until one of two things happens:
514     * <ul>
515     * <li>Some other thread enters the exchange; or
516 jsr166 1.45 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
517     * the current thread.
518 tim 1.1 * </ul>
519     * <p>If the current thread:
520     * <ul>
521 jsr166 1.15 * <li>has its interrupted status set on entry to this method; or
522 jsr166 1.44 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
523 jsr166 1.15 * for the exchange,
524 tim 1.1 * </ul>
525 jsr166 1.15 * then {@link InterruptedException} is thrown and the current thread's
526     * interrupted status is cleared.
527 tim 1.1 *
528     * @param x the object to exchange
529 dl 1.30 * @return the object provided by the other thread
530     * @throws InterruptedException if the current thread was
531     * interrupted while waiting
532 jsr166 1.15 */
533 jsr166 1.52 @SuppressWarnings("unchecked")
534 tim 1.1 public V exchange(V x) throws InterruptedException {
535 dl 1.55 Object v;
536 jsr166 1.56 Object item = (x == null) ? NULL_ITEM : x; // translate null args
537 dl 1.55 if ((arena != null ||
538     (v = slotExchange(item, false, 0L)) == null) &&
539     ((Thread.interrupted() || // disambiguates null return
540     (v = arenaExchange(item, false, 0L)) == null)))
541     throw new InterruptedException();
542 jsr166 1.56 return (v == NULL_ITEM) ? null : (V)v;
543 tim 1.1 }
544    
545     /**
546     * Waits for another thread to arrive at this exchange point (unless
547 jsr166 1.44 * the current thread is {@linkplain Thread#interrupt interrupted} or
548 jsr166 1.31 * the specified waiting time elapses), and then transfers the given
549     * object to it, receiving its object in return.
550 tim 1.1 *
551     * <p>If another thread is already waiting at the exchange point then
552     * it is resumed for thread scheduling purposes and receives the object
553 jsr166 1.39 * passed in by the current thread. The current thread returns immediately,
554 tim 1.1 * receiving the object passed to the exchange by that other thread.
555     *
556 jsr166 1.15 * <p>If no other thread is already waiting at the exchange then the
557 tim 1.1 * current thread is disabled for thread scheduling purposes and lies
558     * dormant until one of three things happens:
559     * <ul>
560     * <li>Some other thread enters the exchange; or
561 jsr166 1.44 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
562     * the current thread; or
563 tim 1.1 * <li>The specified waiting time elapses.
564     * </ul>
565     * <p>If the current thread:
566     * <ul>
567 jsr166 1.15 * <li>has its interrupted status set on entry to this method; or
568 jsr166 1.44 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
569 jsr166 1.15 * for the exchange,
570 tim 1.1 * </ul>
571 jsr166 1.15 * then {@link InterruptedException} is thrown and the current thread's
572     * interrupted status is cleared.
573 tim 1.1 *
574 dl 1.37 * <p>If the specified waiting time elapses then {@link
575     * TimeoutException} is thrown. If the time is less than or equal
576     * to zero, the method will not wait at all.
577 tim 1.1 *
578     * @param x the object to exchange
579     * @param timeout the maximum time to wait
580 dl 1.30 * @param unit the time unit of the <tt>timeout</tt> argument
581     * @return the object provided by the other thread
582     * @throws InterruptedException if the current thread was
583     * interrupted while waiting
584     * @throws TimeoutException if the specified waiting time elapses
585     * before another thread enters the exchange
586 jsr166 1.15 */
587 jsr166 1.52 @SuppressWarnings("unchecked")
588 jsr166 1.15 public V exchange(V x, long timeout, TimeUnit unit)
589 tim 1.1 throws InterruptedException, TimeoutException {
590 dl 1.55 Object v;
591 jsr166 1.56 Object item = (x == null) ? NULL_ITEM : x;
592 dl 1.55 long ns = unit.toNanos(timeout);
593     if ((arena != null ||
594     (v = slotExchange(item, true, ns)) == null) &&
595     ((Thread.interrupted() ||
596     (v = arenaExchange(item, true, ns)) == null)))
597     throw new InterruptedException();
598     if (v == TIMED_OUT)
599     throw new TimeoutException();
600 jsr166 1.56 return (v == NULL_ITEM) ? null : (V)v;
601 dl 1.55 }
602    
603     // Unsafe mechanics
604     private static final sun.misc.Unsafe U;
605     private static final long BOUND;
606     private static final long SLOT;
607     private static final long MATCH;
608     private static final long BLOCKER;
609     private static final int ABASE;
610     static {
611     int s;
612     try {
613     U = sun.misc.Unsafe.getUnsafe();
614     Class<?> ek = Exchanger.class;
615     Class<?> nk = Node.class;
616     Class<?> ak = Node[].class;
617     Class<?> tk = Thread.class;
618     BOUND = U.objectFieldOffset
619     (ek.getDeclaredField("bound"));
620     SLOT = U.objectFieldOffset
621     (ek.getDeclaredField("slot"));
622     MATCH = U.objectFieldOffset
623     (nk.getDeclaredField("match"));
624     BLOCKER = U.objectFieldOffset
625     (tk.getDeclaredField("parkBlocker"));
626     s = U.arrayIndexScale(ak);
627     // ABASE absorbs padding in front of element 0
628     ABASE = U.arrayBaseOffset(ak) + (1 << ASHIFT);
629    
630     } catch (Exception e) {
631     throw new Error(e);
632 dl 1.34 }
633 dl 1.55 if ((s & (s-1)) != 0 || s > (1 << ASHIFT))
634     throw new Error("Unsupported array scale");
635 dl 1.34 }
636 dl 1.55
637 tim 1.1 }