Exchanger

Guide to using the Exchanger<V> class.

We'll cover the following

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

As the name indicates, Exchanger is a construct that can be used to make bidirectional transfers of objects between two threads. Each thread invokes the exchange() method with an item the thread wants to exchange with the other thread. A thread blocks when making the exchange() call until the other thread invokes the exchange() method.

In case of multiple threads, it is not possible for a thread to choose its partner to exchange objects with. Note that the exchange() must be invoked an even number of times during the course of a program to ensure no thread remains blocked when the program exits.

An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.

Example

In the simple example below, we have two threads that exchange String objects with each other. Each thread shares its name with the other thread. The output of the program shows the string that each thread receives from the other thread.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy