RSS

Synchronization and Concurrent programming in Java

12 Sep

Lets look at simple example to understand the concurrency.
Think about you are going to implement the software like stock controlling. Multiple users access the same value at same time that means different threads access the same value and doing some modification on it. if we don’t handle the concurrent access correctly then we cannot guaranty visibility of the modification of values to one thread to the other, so will look at how to handle it correctly.

1. I have Stock class that is created only one instance and do the incCount() operation in different threads as follows

public class Stock {

   private static int count = 0;

   public synchronized void  incCount() {
       System.out.println("Thread name" + Thread.currentThread().getName());
       System.out.println("Befor :"+count);
       count = count+1;
       System.out.println("After :"+count);
    }   
    
}

public class StockThread implements Runnable{
//This Stock variable is initializing only the first time
   private static final Stock stock = new Stock();

     public static void main(String[] args) {
         //Here we create the three threads and run at the same time
         Thread a = new Thread(new StockThread()," first");
         Thread b = new Thread(new StockThread()," second");
         Thread c = new Thread(new StockThread()," third");
         c.start();
         a.start();
         b.start();
     }
    
    @Override
    public void run() {
        
        for(int i=0;i<500;i++){
            //increase the count buy using shared Stock
            stock.incCount();
           
        }
    }
}

2. Now if you have multiple instances of the Stock.class and doing the operation incCount() in different threads then above code is not thread safe. so you have to change the code as follows.

public class Stock {

   private static int count = 0;

   public static synchronized void  incCount() {
       System.out.println("Thread name" + Thread.currentThread().getName());
       System.out.println("Befor :"+count);
       count = count+1;
       System.out.println("After :"+count);
    }   
    
}

public class StockThread implements Runnable{

     public static void main(String[] args) {
         //Here we create the three threads and run at the same time
         Thread a = new Thread(new StockThread()," first");
         Thread b = new Thread(new StockThread()," second");
         Thread c = new Thread(new StockThread()," third");
         c.start();
         a.start();
         b.start();
     }
    
    @Override
    public void run() {
       //multiple Objects 
        Stock stock = new Stock();
        for(int i=0;i<500;i++){
            //increase the count buy using shared Stock
            stock.incCount();
           
        }
    }
}

Ok now let me explain the scenario in the example 1,
we used “synchronized” keyword to the local method so that means if you access this method by using same Stock instance with different threads code is in thread safe because its lock the synchronized method with object reference.

So If you run the same method at same time through the different threads by using same Stock object then all operations are going perfectly one after one.

But you access the same method at same time through the different threads by using different Stock objects then your code is not in thread safe.

In the second scenario I have used the “static synchronized” for the operation incCount() then what happens the synchronized method take the lock as Class. So if you came with different object no matter it will smoothly going one after one.

The same goal can achieve with the following code block as well.

public class Stock {

   private static int count = 0;

   public  void  incCount() {
       synchronized(Stock.class){
       System.out.println("Thread name" + Thread.currentThread().getName());
       System.out.println("Befor :"+count);
        count = count+1;
       System.out.println("After :"+count);
       }
    }   
    
}

public class StockThread implements Runnable{

     public static void main(String[] args) {
         //Here we create the three threads and run at the same time
         Thread a = new Thread(new StockThread()," first");
         Thread b = new Thread(new StockThread()," second");
         Thread c = new Thread(new StockThread()," third");
         c.start();
         a.start();
         b.start();
     }
    
    @Override
    public void run() {
       //multiple Objects 
        Stock stock = new Stock();
        for(int i=0;i<500;i++){
            //increase the count buy using shared Stock
            stock.incCount();
           
        }
    }
}
Advertisements
 
1 Comment

Posted by on September 12, 2013 in java

 

Tags: , ,

One response to “Synchronization and Concurrent programming in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: