Sandeep Kumar Sandeep Kumar - 1 year ago 169
Java Question

synchronize(this) vs synchronize(MyClass.class)

Possible Duplicate:

Java Synchronized Block for .class

I was reading through an article on synchronization. I am confused on below points and need more clarification

1) For synchronization block. How

// code

differs from


2) Synchronizing instance method means threads will have to get exclusive lock on the instance, while synchronizing static method means thread will have to acquire a lock on whole class(correct me if I am wrong). So if a class have three methods and one of them is static synchronized then if a thread acquire lock on that method means it will acquire lock on whole class so is that means the other two will also get locked and no other method will be able to access those two methods as whole class is having lock?

Answer Source

MyClass.class and this are different things, are different references to different objects.

this - is the reference to particular this instance of class, and

MyClass.class - is the reference to MyClass description object.

This synchronization blocks differs in that the first will synchronize all threads that deal concretely with this instance of MyClass, and the second one will synchronize all threads independently of which object on which this method was called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download