Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its exchange() method. When that occurs, it exchanges the data supplied by the threads. It can also be viewed as a bidirectional SynchronousQueue. It is a generic class that is declared as below.
Here, V specifies the type of data being exchanged.
java.lang.Object ↳ java.util.concurrent.Exchanger<V>
- Exchanger() – Creates a new Exchanger object with default values for its members.
exchange(V x)– When invoked this function causes the current thread to suspend its execution and wait for another thread to call its exchange method. When another thread calls its exchange method, the threads exchange their data and the execution resumes.
public V exchange(V x) throws InterruptedException
exchange(V x, long timeout, TimeUnit unit)– When invoked this function causes the current thread to suspend its execution and wait for another thread to call its exchange method. When another thread calls its exchange method, the threads exchange their data and the execution resumes. The thread waits only for the duration specified by the timeout argument and in case if timeout duration elapses, a TimeoutException is thrown.
public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException
Example to demonstrate working of Exchanger class:
Got: ABCDE Got: FGHIJ Timeout Occurred
- URL class in Java with Examples
- JavaFX | Cursor class with examples
- StringBuilder Class in Java with Examples
- Date class in Java (With Examples)
- AbstractSet Class in Java with Examples
- Calendar Class in Java with examples
- Java AWT | Cursor class with examples
- Java.util.IntSummaryStatistics class with Examples
- BitSet class methods in Java with Examples | Set 3
- Math class methods in Java with Examples | Set 2
- Java.util.DoubleSummaryStatistics class with Examples
- ResourceBundle and ListResourceBundle class in Java with Examples
- Java.lang.InheritableThreadLocal Class with Examples
- Java.util.LongSummaryStatistics class with Examples
- Java Guava | binomial(int n, int k) of LongMath Class with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.