ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Exchanger.java
Revision: 1.21
Committed: Sun Jun 19 23:13:42 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +2 -1 lines
Log Message:
doc fixes

File Contents

# Content
1 /*
2 * Written by Doug Lea, Bill Scherer, and Michael Scott with
3 * assistance from members of JCP JSR-166 Expert Group and released to
4 * the public domain, as explained at
5 * http://creativecommons.org/licenses/publicdomain
6 */
7
8 package java.util.concurrent;
9 import java.util.concurrent.*; // for javadoc (till 6280605 is fixed)
10 import java.util.concurrent.locks.*;
11 import java.util.concurrent.atomic.*;
12 import java.util.Random;
13
14 /**
15 * A synchronization point at which two threads can exchange objects.
16 * Each thread presents some object on entry to the {@link #exchange
17 * exchange} method, and receives the object presented by the other
18 * thread on return.
19 *
20 * <p><b>Sample Usage:</b>
21 * Here are the highlights of a class that uses an <tt>Exchanger</tt> to
22 * swap buffers between threads so that the thread filling the
23 * buffer gets a freshly
24 * emptied one when it needs it, handing off the filled one to
25 * the thread emptying the buffer.
26 * <pre>
27 * class FillAndEmpty {
28 * Exchanger&lt;DataBuffer&gt; exchanger = new Exchanger();
29 * DataBuffer initialEmptyBuffer = ... a made-up type
30 * DataBuffer initialFullBuffer = ...
31 *
32 * class FillingLoop implements Runnable {
33 * public void run() {
34 * DataBuffer currentBuffer = initialEmptyBuffer;
35 * try {
36 * while (currentBuffer != null) {
37 * addToBuffer(currentBuffer);
38 * if (currentBuffer.full())
39 * currentBuffer = exchanger.exchange(currentBuffer);
40 * }
41 * } catch (InterruptedException ex) { ... handle ... }
42 * }
43 * }
44 *
45 * class EmptyingLoop implements Runnable {
46 * public void run() {
47 * DataBuffer currentBuffer = initialFullBuffer;
48 * try {
49 * while (currentBuffer != null) {
50 * takeFromBuffer(currentBuffer);
51 * if (currentBuffer.empty())
52 * currentBuffer = exchanger.exchange(currentBuffer);
53 * }
54 * } catch (InterruptedException ex) { ... handle ...}
55 * }
56 * }
57 *
58 * void start() {
59 * new Thread(new FillingLoop()).start();
60 * new Thread(new EmptyingLoop()).start();
61 * }
62 * }
63 * </pre>
64 *
65 * @since 1.5
66 * @author Doug Lea and Bill Scherer and Michael Scott
67 * @param <V> The type of objects that may be exchanged
68 */
69 public class Exchanger<V> {
70 /*
71 * The underlying idea is to use a stack to hold nodes containing
72 * pairs of items to be exchanged. Except that:
73 *
74 * * Only one element of the pair is known on creation by a
75 * first-arriving thread; the other is a "hole" waiting to be
76 * filled in. This is a degenerate form of the dual stacks
77 * described in "Nonblocking Concurrent Objects with Condition
78 * Synchronization", by W. N. Scherer III and M. L. Scott.
79 * 18th Annual Conf. on Distributed Computing, Oct. 2004.
80 * It is "degenerate" in that both the items and the holes
81 * are shared in the same nodes.
82 *
83 * * There isn't really a stack here! There can't be -- if two
84 * nodes were both in the stack, they should cancel themselves
85 * out by combining. So that's what we do. The 0th element of
86 * the "arena" array serves only as the top of stack. The
87 * remainder of the array is a form of the elimination backoff
88 * collision array described in "A Scalable Lock-free Stack
89 * Algorithm", by D. Hendler, N. Shavit, and L. Yerushalmi.
90 * 16th ACM Symposium on Parallelism in Algorithms and
91 * Architectures, June 2004. Here, threads spin (using short
92 * timed waits with exponential backoff) looking for each
93 * other. If they fail to find others waiting, they try the
94 * top spot again. As shown in that paper, this always
95 * converges.
96 *
97 * The backoff elimination mechanics never come into play in
98 * common usages where only two threads ever meet to exchange
99 * items, but they prevent contention bottlenecks when an
100 * exchanger is used by a large number of threads.
101 */
102
103 /**
104 * Size of collision space. Using a size of half the number of
105 * CPUs provides enough space for threads to find each other but
106 * not so much that it would always require one or more to time
107 * out to become unstuck. Note that the arena array holds SIZE+1
108 * elements, to include the top-of-stack slot.
109 */
110 private static final int SIZE =
111 (Runtime.getRuntime().availableProcessors() + 1) / 2;
112
113 /**
114 * Base unit in nanoseconds for backoffs. Must be a power of two.
115 * Should be small because backoffs exponentially increase from
116 * base.
117 */
118 private static final long BACKOFF_BASE = 128L;
119
120 /**
121 * Sentinel item representing cancellation. This value is placed
122 * in holes on cancellation, and used as a return value from Node
123 * methods to indicate failure to set or get hole.
124 */
125 static final Object FAIL = new Object();
126
127 /**
128 * The collision arena. arena[0] is used as the top of the stack.
129 * The remainder is used as the collision elimination space.
130 * Each slot holds an AtomicReference<Node>, but this cannot be
131 * expressed for arrays, so elements are casted on each use.
132 */
133 private final AtomicReference[] arena;
134
135 /** Generator for random backoffs and delays. */
136 private final Random random = new Random();
137
138 /**
139 * Creates a new Exchanger.
140 */
141 public Exchanger() {
142 arena = new AtomicReference[SIZE + 1];
143 for (int i = 0; i < arena.length; ++i)
144 arena[i] = new AtomicReference();
145 }
146
147 /**
148 * Main exchange function, handling the different policy variants.
149 * Uses Object, not "V" as argument and return value to simplify
150 * handling of internal sentinel values. Callers from public
151 * methods cast accordingly.
152 * @param item the item to exchange.
153 * @param timed true if the wait is timed.
154 * @param nanos if timed, the maximum wait time.
155 * @return the other thread's item.
156 */
157 private Object doExchange(Object item, boolean timed, long nanos)
158 throws InterruptedException, TimeoutException {
159 Node me = new Node(item);
160 long lastTime = (timed)? System.nanoTime() : 0;
161 int idx = 0; // start out at slot representing top
162 int backoff = 0; // increases on failure to occupy a slot
163
164 for (;;) {
165 AtomicReference<Node> slot = (AtomicReference<Node>)arena[idx];
166
167 // If this slot is already occupied, there is a waiting item...
168 Node you = slot.get();
169 if (you != null) {
170 Object v = you.fillHole(item);
171 slot.compareAndSet(you, null);
172 if (v != FAIL) // ... unless it was cancelled
173 return v;
174 }
175
176 // Try to occupy this slot
177 if (slot.compareAndSet(null, me)) {
178 // If this is top slot, use regular wait, else backoff-wait
179 Object v = ((idx == 0)?
180 me.waitForHole(timed, nanos) :
181 me.waitForHole(true, randomDelay(backoff)));
182 slot.compareAndSet(me, null);
183 if (v != FAIL)
184 return v;
185 if (Thread.interrupted())
186 throw new InterruptedException();
187 if (timed) {
188 long now = System.nanoTime();
189 nanos -= now - lastTime;
190 lastTime = now;
191 if (nanos <= 0)
192 throw new TimeoutException();
193 }
194
195 me = new Node(item); // Throw away nodes on failure
196 if (backoff < SIZE - 1) // Increase or stay saturated
197 ++backoff;
198 idx = 0; // Restart at top
199 }
200
201 else // Retry with a random non-top slot <= backoff
202 idx = 1 + random.nextInt(backoff + 1);
203
204 }
205 }
206
207 /**
208 * Returns a random delay less than (base times (2 raised to backoff))
209 */
210 private long randomDelay(int backoff) {
211 return ((BACKOFF_BASE << backoff) - 1) & random.nextInt();
212 }
213
214 /**
215 * Nodes hold partially exchanged data. This class
216 * opportunistically subclasses AtomicReference to represent the
217 * hole. So get() returns hole, and compareAndSet CAS'es value
218 * into hole. Note that this class cannot be parameterized as V
219 * because the sentinel value FAIL is only of type Object.
220 */
221 static final class Node extends AtomicReference<Object> {
222 private static final long serialVersionUID = -3221313401284163686L;
223
224 /** The element offered by the Thread creating this node. */
225 final Object item;
226 /** The Thread creating this node. */
227 final Thread waiter;
228
229 /**
230 * Creates node with given item and empty hole.
231 * @param item the item.
232 */
233 Node(Object item) {
234 this.item = item;
235 waiter = Thread.currentThread();
236 }
237
238 /**
239 * Tries to fill in hole. On success, wakes up the waiter.
240 * @param val the value to place in hole.
241 * @return on success, the item; on failure, FAIL.
242 */
243 Object fillHole(Object val) {
244 if (compareAndSet(null, val)) {
245 LockSupport.unpark(waiter);
246 return item;
247 }
248 return FAIL;
249 }
250
251 /**
252 * Waits for and gets the hole filled in by another thread.
253 * Fails if timed out or interrupted before hole filled.
254 * @param timed true if the wait is timed.
255 * @param nanos if timed, the maximum wait time.
256 * @return on success, the hole; on failure, FAIL.
257 */
258 Object waitForHole(boolean timed, long nanos) {
259 long lastTime = (timed)? System.nanoTime() : 0;
260 Object h;
261 while ((h = get()) == null) {
262 // If interrupted or timed out, try to cancel by
263 // CASing FAIL as hole value.
264 if (Thread.currentThread().isInterrupted() ||
265 (timed && nanos <= 0))
266 compareAndSet(null, FAIL);
267 else if (!timed)
268 LockSupport.park();
269 else {
270 LockSupport.parkNanos(nanos);
271 long now = System.nanoTime();
272 nanos -= now - lastTime;
273 lastTime = now;
274 }
275 }
276 return h;
277 }
278 }
279
280 /**
281 * Waits for another thread to arrive at this exchange point (unless
282 * it is {@link Thread#interrupt interrupted}),
283 * and then transfers the given object to it, receiving its object
284 * in return.
285 *
286 * <p>If another thread is already waiting at the exchange point then
287 * it is resumed for thread scheduling purposes and receives the object
288 * passed in by the current thread. The current thread returns immediately,
289 * receiving the object passed to the exchange by that other thread.
290 *
291 * <p>If no other thread is already waiting at the exchange then the
292 * current thread is disabled for thread scheduling purposes and lies
293 * dormant until one of two things happens:
294 * <ul>
295 * <li>Some other thread enters the exchange; or
296 * <li>Some other thread {@link Thread#interrupt interrupts} the current
297 * thread.
298 * </ul>
299 * <p>If the current thread:
300 * <ul>
301 * <li>has its interrupted status set on entry to this method; or
302 * <li>is {@link Thread#interrupt interrupted} while waiting
303 * for the exchange,
304 * </ul>
305 * then {@link InterruptedException} is thrown and the current thread's
306 * interrupted status is cleared.
307 *
308 * @param x the object to exchange
309 * @return the object provided by the other thread.
310 * @throws InterruptedException if current thread was interrupted
311 * while waiting
312 */
313 public V exchange(V x) throws InterruptedException {
314 try {
315 return (V)doExchange(x, false, 0);
316 } catch (TimeoutException cannotHappen) {
317 throw new Error(cannotHappen);
318 }
319 }
320
321 /**
322 * Waits for another thread to arrive at this exchange point (unless
323 * it is {@link Thread#interrupt interrupted}, or the specified waiting
324 * time elapses),
325 * and then transfers the given object to it, receiving its object
326 * in return.
327 *
328 * <p>If another thread is already waiting at the exchange point then
329 * it is resumed for thread scheduling purposes and receives the object
330 * passed in by the current thread. The current thread returns immediately,
331 * receiving the object passed to the exchange by that other thread.
332 *
333 * <p>If no other thread is already waiting at the exchange then the
334 * current thread is disabled for thread scheduling purposes and lies
335 * dormant until one of three things happens:
336 * <ul>
337 * <li>Some other thread enters the exchange; or
338 * <li>Some other thread {@link Thread#interrupt interrupts} the current
339 * thread; or
340 * <li>The specified waiting time elapses.
341 * </ul>
342 * <p>If the current thread:
343 * <ul>
344 * <li>has its interrupted status set on entry to this method; or
345 * <li>is {@link Thread#interrupt interrupted} while waiting
346 * for the exchange,
347 * </ul>
348 * then {@link InterruptedException} is thrown and the current thread's
349 * interrupted status is cleared.
350 *
351 * <p>If the specified waiting time elapses then {@link TimeoutException}
352 * is thrown.
353 * If the time is
354 * less than or equal to zero, the method will not wait at all.
355 *
356 * @param x the object to exchange
357 * @param timeout the maximum time to wait
358 * @param unit the time unit of the <tt>timeout</tt> argument.
359 * @return the object provided by the other thread.
360 * @throws InterruptedException if current thread was interrupted
361 * while waiting
362 * @throws TimeoutException if the specified waiting time elapses before
363 * another thread enters the exchange.
364 */
365 public V exchange(V x, long timeout, TimeUnit unit)
366 throws InterruptedException, TimeoutException {
367 return (V)doExchange(x, true, unit.toNanos(timeout));
368 }
369 }