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:
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Exchanger<String> exchanger = new Exchanger<>(); | |
Runnable laila = () -> { | |
try { | |
String messageFromMajnu = exchanger.exchange("I miss you Majnu!"); | |
} catch (InterruptedException e) { | |
Thread.currentThread.interrupt(); | |
throw new RuntimeException(e); | |
} | |
}; | |
Runnable majnu = () -> { | |
try { | |
String messageFromLaila = exchanger.exchange("I miss you too Laila"); | |
} catch (InterruptedException e) { | |
Thread.currentThread.interrupt(); | |
throw new RuntimeException(e); | |
} | |
}; |
-K Himaanshu Shuklaa..
No comments:
Post a Comment