April 03, 2020

#Collections: Part 7 (All about Exchanger in Java)

java.util.concurrent.Exchanger < T > class in Java can be used to share objects between two threads of type T. It provides only a single overloaded method exchange(T t).


It can also be viewed as a bidirectional SynchronousQueue. When two threads have called the exchange() method, Exchanger will swap the objects presented by the threads.

When invoked exchange waits for the other thread in the pair to call it as well. At this point, the second thread finds the first thread is waiting with its object. The thread exchanges the objects they are holding and signals the exchange, and now they can return.

ALSO READ: All about BlockingQueue!

Exchanger could be used to create pipeline kind of patterns with passing data from one thread to the other.

Unlike CountDownLatch, CyclicBarrier, or Semaphore, the Exchanger utility can only synchronize two threads, which makes it ideal for solving the classical producer-consumer problem.

e.g:

-K Himaanshu Shuklaa..

No comments:

Post a Comment