Wednesday, 17 September 2014

Exchanger

Exchanger is a point, where two threads can exchange objects.

As shown in the figure, Exchanger represented by rectangle, thread1 and thread2 exchanging object1 and object2 respectively. This exchange is performed by 'exchange' method of Exchanger class.

There are two variants of exchange methods are available.

public V exchange(V x) throws InterruptedException
Waits for another thread to arrive at this exchange point, and then transfers the given object to it, receiving its object in return.

If no other thread is already waiting at the exchange then the current thread is disabled for thread scheduling purposes and lies dormant until one of two things happens:
   a. Some other thread enters the exchange; or
   b. Some other thread interrupts the current thread.

public V exchange(V x, long timeout, TimeUnit unit)
Waits for another thread to arrive at this exchange point, and then transfers the given object to it, receiving its object in return.

If no other thread is already waiting at the exchange then the current thread is disabled for thread scheduling purposes and lies dormant until one of three things happens:
   a. Some other thread enters the exchange; or
   b. Some other thread interrupts the current thread; or
   c. The specified waiting time elapses.

import java.util.concurrent.Exchanger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Producer implements Runnable{
    Exchanger<String> exchangeData = null;
    String message = null;
    private static final Logger LOG = Logger.getLogger(Producer.class.getName());
    
    Producer(Exchanger<String> exchangeData, String message){
        this.exchangeData = exchangeData;
        this.message = message;
    }
    
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName() +":" + message);
        try {
            message = exchangeData.exchange(message);
        } catch (InterruptedException ex) {
            Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(Thread.currentThread().getName() +":" + message);
    }    
}

import java.util.concurrent.Exchanger;

public class ExchangerEx {
    public static void main(String args[]){
        Exchanger<String> exchangeData = new Exchanger<> ();
        
        Producer p1 = new Producer(exchangeData, "Object1");
        Producer p2 = new Producer(exchangeData, "Object2");
        
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p2);
        
        t1.setName("Producer1");
        t2.setName("Producer2");
        
        t1.start();
        t2.start();      
    }
}

Sample Output
Producer1:Object1
Producer2:Object2
Producer2:Object1
Producer1:Object2


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment