Java Synchronized Block for .class

user249739 picture user249739 · Jan 13, 2010 · Viewed 42.7k times · Source

What does this java code mean? Will it gain lock on all objects of MyClass?

synchronized(MyClass.class) {
   //is all objects of MyClass are thread-safe now ??
}

And how the above code differs from this one:

synchronized(this) {
   //is all objects of MyClass are thread-safe now ??
}

Answer

Thomas Jung picture Thomas Jung · Jan 13, 2010

The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block.

With synchronized(this) the block is guarded by the instance. For every instance only one thread may enter the block.

synchronized(X.class) is used to make sure that there is exactly one Thread in the block. synchronized(this) ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instance synchronized(this) is enough.