Exchanger is Java’s high level API for sharing data between two threads. It allows one thread to wait while another thread generates or processes data. Once they have prepared data, data objects can be shared between the threads.
Working
There are two important methods in Exchanger class.
V is the type of data to be exchanged. When exhcange() is invoked on a thread, it stops the current thread and waits for other thread to reach the exchange point.
exchange() method waits until it is not invoked on same object by two separate threads or thread is
interrupted.
When exchage() is called by both threads, objects are swaped and thread execution is resumed. If exchange() is already called by a thread and another thread invoked exchange(), other thread is passed the object immidiately and execution is proceeded in both threads.
Exchange with timeout is same as exchange() with one major difference - it waits for specified interval of time. TimeoutException is thrown if no other thread arrives at exchange point in a given time.
Example
We are going to create two threads which will exchange object. I will print object’s hashcode along with thread name to get better understanding of what’s going on.
ThreadA - sends an empty string and prints the string returned from ThreadB.
ThreadB - sends a string (ThreadA) and prints the string returned from ThreadA.