Thursday, March 26, 2009

Static synchronized Method in java

Static synchronized methods synchronize on the class object (this.getClass()) of the class.
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class)
{
}

In JAVA we hav a class named CLASS. JVM creates an object of this class every time a class is loaded thus a class itself has a monitor object so when we make a method static synchonized, thread takes the ownership of this object which JVM creates..this is how a method can be declared as both static and synchronized

Static Methods can be declared Synchronized

- Associated with every class is a Class object (there is a class Class)

- Static synchronized methods acquire the lock of the Class obj for their class

- Two threads can not execute static synchronized methods of the same class at the same time

- If static data is shared between two threads, it must be protected using static synchronized methods



Acquiring the Class object lock in a static synchronized method, has no effect on any object of that class.

It is possible to invoke synchronized methods of an object while another thread holds the Class object lock in a static synchronized method.

Only the other static synchronized methods are blocked.



Synchronized Statements
Enables :

- executing code that acquires the lock of any object, not just the current object

- acquiring the lock for duration of less than a whole method



The synchronized statement has two parts:

- an object whose lock is to be acquired

- a statement to be executed when this lock is acquired



General Form :



synchronized (expr) {

statements

}



expr – is an object reference.

When the lock is obtained – the statements in the block are executed

At the end of the block – the lock is released



A synchronized statement block with a this reference is equivalent to a synchronized method in this object:



synchronized ( this ){

statements

}

Example : make all array elements positive:



public static void abs ( int[] arr ){

synchronized ( arr ) {

for (int i = 0;i < arr.length;i++){

if(arr[i]<0) arr[i] *= -1;

}

}

}



Because arrays objects do not have synchronized methods this is the only way to protect them when they can be shared.

No comments: