[Java concurrent programming practice] ----- "J. U. C": Exchanger

Source: Internet
Author: User

[Java concurrent programming practice] ----- "J. U. C": Exchanger

We have introduced three synchronization auxiliary classes: CyclicBarrier, Barrier, and Phaser. This blog introduces the last one: Exchanger. Jdk api is introduced as follows: synchronization points of threads that can pair and exchange elements in a pair. Each thread presents a method on the entry to the exchange method, matches with the partner thread, and receives the object of its partner when returning the result. Exchanger may be considered as a bidirectional form of SynchronousQueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.

Exchanger, which allows data exchange between concurrent tasks. Specifically, the Exchanger class Allows defining synchronization points between two threads. When both threads reach the synchronization point, they exchange the data structure, so the data structure of the first thread enters the second thread, and the data structure of the second thread enters the first thread.

The definition of Exchanger in the official API is quite concise. One non-argument constructor has two methods:

Constructor:

Exchanger () creates a new Exchanger.

Method:

Exchange (V x): Wait for another thread to reach this switching point (unless the current thread is interrupted), send the given object to this thread, and receive the object of this thread.
Exchange (V x, long timeout, TimeUnit unit): Wait for another thread to reach this switching point (unless the current thread is interrupted or exceeds the specified wait time ), then, the given object is transmitted to the thread and the object of the thread is received.

Exchanger is useful in production-Consumer problem scenarios. In the producer-consumer situation model, it contains a number buffer zone (warehouse), one or more producers, and one or more consumers.

The following is an example of producer-consumer (the example is from java 7 concurrency Programming Practice Manual).

Public class Producer implements Runnable {/*** Data Structure exchanged between Producer and consumer */private List
 
  
Buffer;/*** synchronize the exchange objects between producers and consumers */private final Exchanger
  
   
> Exchanger; Producer (List
   
    
Buffer, Exchanger
    
     
> Exchanger) {this. buffer = buffer; this. exchanger = exchanger;} @ Override public void run () {int cycle = 1; for (int I = 0; I <10; I ++) {System. out. println (Producer: Cycle: + cycle); for (int j = 0; j <10; j ++) {String message = Event + (I * 10) + j); System. out. println (Producer: + message); buffer. add (message) ;}// call exchange () to exchange data with the consumer. try {buffer = exchanger. exchange (buffer);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Producer: + buffer. size (); cycle ++ ;}}}
    
   
  
 

 

Consumer:

Public class Consumer implements Runnable {private List
 
  
Buffer; private final Exchanger
  
   
> Exchanger; public Consumer (List
   
    
Buffer, Exchanger
    
     
> Exchanger) {this. buffer = buffer; this. exchanger = exchanger;} @ Override public void run () {int cycle = 1; for (int I = 0; I <10; I ++) {System. out. println (Consumer: Cycle: + cycle); // call exchange () to exchange data with the Consumer. try {buffer = exchanger. exchange (buffer);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Consumer: + buffer. size (); for (int j = 0; j <10; j ++) {System. out. println (Consumer: + buffer. get (0); buffer. remove (0) ;}cycle ++ ;}}}
    
   
  
 

 

Test:

public class Test {    public static void main(String[] args) {        List
 
   buffer1 = new ArrayList<>();        List
  
    buffer2 = new ArrayList<>();                Exchanger
   
    > exchanger = new Exchanger<>();                Producer producer = new Producer(buffer1, exchanger);        Consumer consumer = new Consumer(buffer2, exchanger);                Thread thread1 = new Thread(producer);        Thread thread2 = new Thread(consumer);                thread1.start();        thread2.start();    }}
   
  
 

 

Running result (Part ):

Producer : Cycle :1Producer : Event 0Producer : Event 1Producer : Event 2Producer : Event 3Producer : Event 4Producer : Event 5Producer : Event 6Producer : Event 7Consumer : Cycle :1Producer : Event 8Producer : Event 9Producer :0Producer : Cycle :2Producer : Event 10Producer : Event 11Producer : Event 12Producer : Event 13Consumer :10Consumer : Event 0Consumer : Event 1Consumer : Event 2Consumer : Event 3Consumer : Event 4Consumer : Event 5Consumer : Event 6Consumer : Event 7Consumer : Event 8Consumer : Event 9Consumer : Cycle :2Producer : Event 14Producer : Event 15Producer : Event 16Producer : Event 17Producer : Event 18Producer : Event 19

First, the Producer and Consumer create a cache list and use the Exchanger to synchronize and exchange data. In consumption, data is obtained by calling Exchanger to synchronize with the producer, while the producer stores data to the cache queue through the for loop and synchronizes the data with the exchanger object consumer. After the consumer obtains data from the exchanger, there are 10 Data in the buffer list, and the producer obtains an empty list. The example above demonstrates how the consumer-producer uses the Exchanger to complete data exchange.

In Exchanger, if a thread has reached the exchanger node, there are three scenarios for its partner nodes:

1. If its partner node has already called the exchanger method between the arrival of the thread, it will wake up its partner and then exchange data to get their own data returned.

2. If its partner node has not reached the switching point, the thread will be suspended, waiting for its partner node to arrive to be awakened to complete data exchange.

3. If the current thread is interrupted, an exception is thrown or a timeout exception is thrown.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.