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
-
For synchronization block. How
synchronized (this) { // code }differs from
synchronized (MyClass.class) { // code } -
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 has three methods and one of them is static synchronized then if a thread acquires lock on that method then that means it will acquire lock on the whole class. So does that mean the other two will also get locked and no other method will be able to access those two methods as the whole class is having lock?
MyClass.classandthisare different things, they are different references to different objects.this– is a reference to this particular instance of the class, andMyClass.class– is a reference to theMyClassdescription object.These synchronization blocks differ 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 method was called.