Thursday, 26 June 2014

Why Synchronization is costly operation

Synchronization is costly operation, because it contains overhead of acquiring and releasing of locks and other thread has to wait until the lock hold is released.

Below program, which will simply iterate a loop 1000000000 times
class WithOutSynchronization implements Runnable{
      public void run(){
         sum();
      }

      public void sum(){
         for(int i=0; i < 1000000000; i++){
         }
      }

      public static void main(String args[]) throws Exception{
         WithOutSynchronization task1 = new WithOutSynchronization();
         Thread t1 = new Thread(task1);
         Thread t2 = new Thread(task1);

         long time1 = System.currentTimeMillis();
         t1.start();
         t2.start();
         t1.join();
         t2.join();
         long time2 = System.currentTimeMillis();

         System.out.println("Time taken is " + (time2-time1));
      }
   }
   

Output
Time taken is 5

will modify the above program, by applying synchronization
  class WithSynchronization implements Runnable{
      public void run(){
         sum();
      }

      public void sum(){
         for(int i=0; i < 1000000000; i++){
            synchronized(this){
            }
         }
      }

      public static void main(String args[]) throws Exception{
         WithSynchronization task1 = new WithSynchronization();
         Thread t1 = new Thread(task1);
         Thread t2 = new Thread(task1);

         long time1 = System.currentTimeMillis();
         t1.start();
         t2.start();
         t1.join();
         t2.join();
         long time2 = System.currentTimeMillis();

         System.out.println("Time taken is " + (time2-time1));
      }
   }
 

Output
Time taken is 18014

Compare the two outputs, for the first program with out synchronization takes 5 milliseconds to execute, with synchronization takes 18014 milliseconds to execute.




                                                 Home

No comments:

Post a Comment