Java Exchanger example

Java Exchanger example
Exchanger class is introduced with java 1.5 with other classes such ConcurrentHashMap, CountDownLatch, Semaphores.
Exchanger class is used to exchange object between two threads. Exchanger simply waits until two separate threads calls exchange method, when it happens, it exchanges data supplied by threads.Two threads can pair and swap objects between them. Exchanger class may be useful in genetic algorithms or pipeline design.

It has two overloaded version of exchange method.

  • exchange(V x): It waits for another thread to arrive at exchange point and exchange object with that thread.
  • exchange(V x, long timeout, TimeUnit unit): It waits for another thread for specific time interval provided in the method and exchange object with that thread.
Let’s understand with help of example:

We have two threads i.e. Producer and Consumer and they will exchange Country objects. Producer will create Country objects and Consumer will return dummy country objects.

Let’s first create Country class. It just have one attribute called countryName.
Now we will create main class called and it will have two other classes called Producer and Consumer which will implement runnable interface.
When you run above program, you will get below output.
If you notice, producer has exchanged two country object (India and Bhutan) with consumer and got dummy country objects in return.
If you want to understand more realistic use of Exchanger. Producer and consumer may exchange buffers. When buffer is full, Producer will provide full buffer to consumer and Consumer will return empty buffer in return.

đź’» Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️


You may also like:

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.