Java.util.concurrent.Exchanger class with Examples

The Java synchronization class known as Exchanger is the most captivating. Through the creation of a synchronization point, it makes the exchange of elements between two threads easier. The data transfer between two threads is made simpler. The way it works is that it just waits for its exchange() method to be called by two different threads. The data provided by the threads is exchanged when that happens. A bidirectional SynchronousQueue is another way to take advantage of it. Below is the declaration of the generic class.

The Class Syntax is:

- The type of data being transferred is indicated here by V.

The Class Hierarchy is given by:

The Constructor that is used is given by:

Exchanger() - adds default values to the members of a newly created Exchanger object.

The Methods that are used in this Exchanger Class are:

1. exchange(V x)- The current thread waits for another thread to call its exchange method before continuing with its execution when this function is invoked. The operation of the threads continues after they exchange data and another thread invokes their exchange method.

Syntax:

2. exchange(V x, long timeout, TimeUnit unit) - The current thread waits for another thread to call its exchange method before continuing with its execution when this function is invoked. The operation of the threads continues after they exchange data, and another thread invokes their exchange procedure. Only the amount of time indicated by the timeout argument is allowed for the thread to wait; if that timeout is exceeded, a TimeoutException is raised.

Syntax:

Example:

The ExchangerExample program shows how to enable thread synchronization and data interchange using the Exchanger class from the java.util.concurrent package. It is made up of two threads: UseString receives and provides these character strings, while MakeString creates new strings.

Implementation:

FileName: ExchangerExample.java

Output:

The string is : ABCDEFGH
The string is : IJKLMNOP
Timeout has been Occurred