Friday, September 13, 2013

Synchronization : Lesson 01


Synchronization : Lesson 01

Synchronization is the capability of control the access of multiple threads to any shared resource.
( Only one thread access the shared resource at a time )

Why synchronization ?
  1. To prevent thread interference
  2. To prevent consistency problem

Synchronization types :-
  1. Process synchronization
  2. Thread synchronization

Thread synchronization

2 types:
* Inter thread communication
* mutual exclusive

Mutual Exclusive
Mutual Exclusive helps keep threads form interfering with one another while sharing data.
This can be done in three ways.
      1. by synchronized method
      2. by synchronized block
      3. by static synchronization

Example with no Synchronization -

1. Print.java

public class Print {

        void printMultiplicationNumbers(int n){

             for(int i = 1; i<5; i++){
                  System.out.println(i*n);
                  try{
                        Thread.sleep(500);
                  }catch (Exception e) {
                        // TODO: handle exception
                  }
            }
       }
}

2. Thread01.java

public class Thread01 extends Thread {

        Print print;

        Thread01(Print p){
                this.print = p;
        }

        public void run(){
                print.printMultiplicationNumbers(5);
        }
}

3. Thread02.java
 
public class Thread02 extends Thread {

          Print print;

          Thread02(Print p){
                  this.print = p;
          }

          public void run(){
                  print.printMultiplicationNumbers(100);
          }
}

4. TestExecute.java - class to run above thread simultaneously to access the Print resource java class.

public class TestExecute {

       /**
       * @param args
       */
       public static void main(String[] args)

             Print p = new Print();
             Thread01 thread01 = new Thread01(p);
             Thread02 thread02 = new Thread02(p);

             thread01.start();
             thread02.start();
       }
}


Output ( no-synchronize example) :

5
100
10
200
15
300
20
400


Use of Synchronized method

Declared any method as synchronized, it is known as synchronized method.

Synchronized method used to lock an object for any shared resource.

When a Thread invokes a synchronized method, the lock will be granted and it will returns once the method got return.


Example with synchronized method

1. Print.java – with synchronized method

public class Print {

       synchronized void printMultiplicationNumbers(int n){
            for(int i = 1; i<5; i++){
                 System.out.println(i*n);
                 try{
                      Thread.sleep(500);
                 }catch (Exception e) {
                       // TODO: handle exception
                 }
            }
       }
}


Output ( synchronized example) :

5
10
15
20
100
200
300
400