Jan 25, 2014

Synchronization on static method and instance method

Before getting into synchronization concept, lets first understand what is monitor. 

A monitor is a kind of lock that each class owns. And that monitor, at any time can be held only by a single Thread. When a class is instantiated, each instance is allocated with one monitor. 

Consider our class is Student.java 

public class Student{

 public void getStudentName(){
   //Code
 }

  synchronized(this){
     //code
  }
}

When some thread tries to execute the synchronized method/block, first the thread acquires the monitor that belongs to that instance so that the monitor is not available for any other thread of same instance till this thread completes its task and releases the monitor. The monitor could also be released by putting the thread into wait() status. Note here, if a thread acquires the monitor of an instance, then any synchronized block in that instance cannot be accessed by any thread. But anyhow, non synchronized block is still available for access. 

Threads of other instances have access to this synchronized block as each object has its own monitor.


Static synchronized block:
If our Student class has a static synchronized block & any thread try to access this block,  the monitor belongs to the class itself is acquired by the thread that executes the static block. So any thread on any other instances of this class has to wait till this monitor is released. So be cautious while you develop a static synchronized method.

static Synchronized block is given below.

public static synchronized void getStudentDetails(){
   //Code here
}


A class level lock can be made even by following way. They both have similar effect.

public static void getStudentDetails(){
  synchronized(Student.class){
    //Code here
  }

  

No comments:

Post a Comment