I'm trying to understand the exact differences in synchronisation using:
synchronized(MyClass.class){...}synchronized(myClassInstance.getClass()){...}[edited asMyClass.getClass()doesn't even compile]synchronized(this){...}
Thanks to other posts I get that (1) is used to make sure that there is exactly one thread in the block and that (3) ensures that there is exactly one thread per instance.
(see Java Synchronized Block for .class )
But what does (2) do? Is it identical to (3)?
Class, (2) Doesn't compile: you are using an instance method in a static context, (3) Synchronizes on the instance.myClassInstance, but in that case it would be identical to #1; the class is just referenced differently (that is, ifmyClassInstanceis not an instance of a derived class instead of the base class).MyClass.class.getClass(), couldn't it?class java.lang.Classof course). Well, it would work: it would lock the same way as #1 I presume, but setting a lock on something that is not local is not recommended.