Wednesday, 15 January 2014

What happens when i make any static method as synchronized ??


In Java multi-threading, Synchronization is achieved by the use of locks, each of which is associated with an object by the JVM. For a thread to work on an object, it must have control over the lock associated with it, it must “hold” the lock. Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

Basically there are two types of locks

Object level locklock on instance of the class, when any synchronized method or block are non-static.

Class level lock : lock on the Class, in case of synchronized method or block are static.

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. In case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. The following example show you few ways to access the class object:

class MyClass {

 ....

   public static void main(String[] args) {
      //you can access class object through an instance of that class
      MyClass objectinstance = new MyClass();
      java.lang.Class myclass1 = objectinstance.getClass();

      //non-instance ways
      java.lang.Class myclass2 = Myclass.class;
 java.lang.Class myclass3 = Class.forName("MyClass");
    }

}
The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.
For example
class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  ...
}
It is the equivalent to the following static synchronized block:
synchronized ( MyClass.class ) {
...
}

The Lock on object or instance of class is totally independent from Class level lock. both will execute independently. There will be never any interference between object lock and class level lock.



No comments:

Post a Comment