[Java - Synchronization] Exchanger

1) Intro

Exchanger is a synchronization point at which threads can swap elements. "Swap" meaning each thread passes one element and receives the partner's element in return. Whenever a thread arrives at the exchange point or method, it must wait for the other thread to arrive.

There is also an overloaded version, exchange(V x, long timeout, TimeUnit unit). If the corresponding pairing thread does not arrive at the exchange point within timeout specified, the waiting Thread throws a java.util.concurrent.TimeoutException.

In application, exchangers can be useful in genetic algorithms and neural network.

2) Example

2.1) Code



2.2) Output

Consumer now has Ready Queue
Producer now has Empty Queue

In the above example, we create an Exchanger Object of the type String. The Producer thread produces a “filled queue”and exchanges it with the Consumer thread for an “empty queue”.(The filled and empty queue mentioned here are just dummy string object, for the sake of brevity.). Similarly, we can proceed to exchange any type of object between two threads, merely by changing the type parameter of Exchanger instance.

3) Another Example

Here, the Exchanger swaps 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.


Memory consistency effects: For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to a return from the corresponding exchange() in the other thread.

4) Resource:

Comments

Popular posts from this blog

[Redis] Redis Cluster vs Redis Sentinel

[Unit Testing] Test Doubles (Stubs, Mocks....etc)

[Node.js] Pending HTTP requests lead to unresponsive nodeJS