synchronize(this) vs synchronize(MyClass.class)

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

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

MyClass.class - is a reference to the MyClass description 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.


The first example (acquiring lock on this) is meant to be used in instance methods, the second one (acquiring lock on class object) -- in static methods.

If one thread acquires lock on MyClass.class, other threads will have to wait to enter the synchronized block of a static method that this block is located in. Meanwhile, all of the threads will be able to acquire lock for a particular instance of this class and execute instance methods.