Exchanger
A
synchronization point at which two threads can exchange objects.
Each thread presents some object on entry to the exchange() method, and
receives the object presented by the other thread as a return value.
For example, below is a class that uses an Exchanger to swap buffers
between threads so that the thread filling the buffer gets a freshly
emptied one when it needs it, handing off the filled one to the
thread emptying the buffer.
class FillAndEmpty {
Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
DataBuffer initialEmptyBuffer = ... a made-up type
DataBuffer initialFullBuffer = ...
class FillingLoop implements Runnable {
public void run() {
DataBuffer currentBuffer = initialEmptyBuffer;
try {
while (currentBuffer != null) {
addToBuffer(currentBuffer);
if (currentBuffer.isFull())
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ... }
}
}
class EmptyingLoop implements Runnable {
public void run() {
DataBuffer currentBuffer = initialFullBuffer;
try {
while (currentBuffer != null) {
takeFromBuffer(currentBuffer);
if (currentBuffer.isEmpty())
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ...}
}
}
void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
}
exchange()
waits for another thread to arrive at this exchange point (unless it
is interrupted), and then transfers the given object to it, receiving
its object in return.
If
another thread is already waiting at the exchange point then it is
resumed and it receives the object passed in by the current thread.
The current thread returns immediately in this case, receiving the
object passed to the exchange by that other thread.
If
no other thread is already waiting at the exchange then the current
thread begins waiting for another thread to arrive at this exchange
point.
|