Exchanger in Java

Many synchronization aid were added as the part of java.util.concurrent package in Java 5 like CyclicBarrier, Semaphore. One more synchronization aid added as part of Java concurrency is Exchanger. In this post we’ll see what is Exchanger in Java, how does it work and an example of Exchanger.

Exchanger in Java Concurrency

Exchanger in Java is a synchronization aid that helps in exchanging the data between two threads. When two threads call exchange() method the objects supplied by these two threads are exchanged.
Exchanger in Java
Exchanger can be used in a Producer-Consumer scenario where a producer thread produces a buffer which can be exchanged with an empty buffer from consumer thread.

Java Exchanger class constructor

Exchanger class in Java has only one constructor.

  • Exchanger()– Creates a new Exchanger.

Java Exchanger class methods

Exchanger class in Java has only one method exchange() which has two overloaded forms.

  • exchange(V x)– Waits for another thread to arrive at this exchange point (unless the current thread is interrupted), and then transfers the given object to it, receiving its object in return.
  • exchange(V x, long timeout, TimeUnit unit)– Waits for another thread to arrive at this exchange point (unless the current thread is interrupted or the specified waiting time elapses), and then transfers the given object to it, receiving its object in return.

Exchanger example

Here is an example of producer consumer threads where threads use Exchanger to exchange data.

The data which is exchanged is of type DataBuffer.

DataBuffer.java

Output

That’s all for the topic Exchanger in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.