Thursday, July 3, 2008

-C-O-N-C-E-P-T- Series : Java

Synchronizing a static method and its effect in the multi-threading environment:

Since static code can modify only the static data, you will protect a static data with synchronized keyword. We know that static data and methods have only one copy for all the objects of that class. Therefore, you only need one lock per class to synchronize static methods. Object locks are not required for static methods. Static methods use a class lock for synchronization. This special lock is also an object lock.

Consider following java code:


Fig1


Fig2

Both the figure above are self explanatory, but I would like to elaborate more on Fig2. When we synchronize an instance method, the thread accessing that method acquires "Object Lock" on the object such that no other thread can access that method unless it completes its execution. Now for "synchronized static" method, it acquires "Class Lock" on that class. This class lock also implicitly has object lock, it's because as non-static methods can modify static variables, so we need to also put a lock on synchronized instance variables & this is internally done by the class lock.
Hence if one thread is executing a static synchronized method of a class then it holds a lock on all other synchronized methods of that class and in effect no other thread can call any of the synchronized static methods of that class until this current thread releases the lock.

This concept is really very interesting to learn :)

Stay tuned... :)

2 comments:

Anonymous said...

can you email me: mcbratz-girl@hotmail.co.uk, i have some question wanna ask you.thanks

Anonymous said...

Although there are differences in content, but I still want you to establish Links, I do not know how you advice!


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________