views:

279

answers:

3

What does this java code means? Will it gain locks on all objects of 'MyClass'

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

And how the above code different from this one:

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

No, the first will get a lock on the class definition of MyClass, not all instances of it. However, if used in an instance, this will effectively block all other instances, since they share a single class definition.

The second will get a lock on the current instance only.

As to whether this makes your objects thread safe, that is a far more complex question - we'd need to see your code!

David M
yes, MyClass.class could be any static variable and have the same effect.
pstanton
+5  A: 

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.

Thomas Jung
"as many threads may enter the block as there are instance" implies that the second form acts as a semaphore which is not true. You should say something like: "synchronised(this) ensures that only one thread can enter the block for a given instance of the class".
liwp
Corrected. I intended to say that.
Thomas Jung
+1  A: 

To add to the other answers:

static void myMethod() {
  synchronized(MyClass.class) {
    //code
  }
}

is equivalent to

static synchronized void myMethod() {
  //code
}

and

void myMethod() {
  synchronized(this) {
    //code
  }
}

is equivalent to

synchronized void myMethod() {
  //code
}
Jorn