Saturday 1 March 2014

synchronization

Synchronization is a process of orderly sharing of system resources

Will explore the need of synchronization and how to use it in java with an example.

Problem Description:
I have 2 threads want to print data from 0 to 4 in orderly. Like (0 1 2 3 4 0 1 2 3 4)

Solution without synchronization
class PrintWithOutSynch implements Runnable{
 public void run(){
  print1to10();
 }

 void print1to10(){
  for(int i=0; i < 10; i++){
   System.out.println(i);
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(InterruptedException e){
   }
  }
 }

 public static void main(String args[]){
  PrintWithOutSynch task1 = new PrintWithOutSynch();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  t1.start();
  t2.start();
 }
}
    
Output
0 0 1 1 2 2 3 3 4 4

But we are expecting output like 0 1 2 3 4 0 1 2 3 4.

So what is wrong with this approach
Since threads are independent, both threads works parallel. If thread1 enters into sleep, thread2 has a chance to run, if thread2 enters into sleep, thread1 has a chance to run.

How to solve the problem
Make the print method as synchronized, if a method declared as synchronized, then at a time only one thread can enters into the synchronized method of a particular object(here for task1 object). Remaining threads wait until the thread which enters into the synchronized method finishes its execution or releases the lock voluntarily.

Solution with Synchronization
class PrintWithOutSynch implements Runnable{
 public void run(){
  print1to10();
 }

 synchronized void print1to10(){
  for(int i=0; i < 5; i++){
   System.out.print(i +" ");
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(InterruptedException e){
   }
  }
 }

 public static void main(String args[]){
  PrintWithOutSynch task1 = new PrintWithOutSynch();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  t1.start();
  t2.start();
 }
}
   
Output

0 1 2 3 4 0 1 2 3 4


volatile keyword                                                 Synchronized methods                                                 Home

No comments:

Post a Comment