Tuesday, October 1, 2013

Exchanger in Java : Concurrency

The Java concurrency API provides a synchronization utility that allows the interchange of data between two concurrent tasks. In more detail, the Exchanger class allows the definition of a synchronization point between two threads. When the two threads arrive to this point, they interchange a data structure so the data structure of the first thread goes to the second one and the data structure of the second thread goes to the first one.
The Exchanger class is meant for exchanging data between two threads. It waits until both the threads have called the exchange() method



This class may be very useful in a situation similar to the producer-consumer problem. This is a classic concurrent problem where you have a common buffer of data, one or more producers of data, and one or more consumers of data. As the Exchanger class only synchronizes two threads, you can use it if you have a producer-consumer problem with one producer and one consumer.

When both threads have called the exchange() method, the Exchanger object actually exchanges the data shared by the threads with each other. 
This class is useful when two threads need to synchronize between them and continuously exchange data.
  • Exchangers may be useful in applications such as genetic algorithms and pipeline designs.
  • An exchanger is more like an object for communication than synchronization
  • Exchangers are used on pairs of threads
  • Exchangers don't break like barriers can (not even when timeouts and interrupts occur)


Let's have a look an example of Exchange class.
In this example we simulate talk between coffeeThread and WaiterThread. These two thread run independently. However, for a chat to happen, they need to listen when other is talking. An Exchanger object provides a means for them to talk to each other.



Sample output:
Coffee : Hello!
waiter : What would you like to have?
Coffee : Cafe-latte
waiter : We have regular,grand & king sizes, which one you like to have?
Coffee : Regular one

These comments explain how the program works. The main concept to be understand with this example is that Exchanger helps coordinate exchanging message between 2 threads. Both the threads wait for each other and use the exchange method to exchange messages.




Related Post
Semaphore in java with example
CountDownLatch In java with example
Java Collection with detailed examples
Garbage Collection + Interview Question Answers



If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

1 comment:

  1. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java Training in Chennai

    ReplyDelete