Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between synchronized(this) and synchronized method

Lets say we have these 2 sample code :

public synchronized void getSomething(){      this.hello = "hello World"; } 

and this one

public void getSomething(){    synchronized(this){      this.hello = "hello World";    } } 

So some one can tell me what's the difference now?

like image 547
Tarik Avatar asked Dec 09 '10 04:12

Tarik


People also ask

What is difference between synchronized method and synchronized block?

Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.

What is synchronized this in Java?

synchronized (this) is syntax to implement block-level synchronization. It means that on this object only and only one thread can excute the enclosed block at one time.

What are synchronized methods and synchronized statements?

Answer: Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.


1 Answers

The two different methods are functionally equivalent. There may be a very small performance difference:

At the bytecode level, the synchronized method advertises its need for synchronization as a bit set in the method's access flag. The JVM looks for this bit flag and synchronizes appropriately.

The synchronized block implements its synchronization through a sequence of bytecode operations stored in the class file's definition of the method.

So the synchronized method might potentially execute slightly faster and take up less space in terms of bytecode.

Again, the two are, by specification, functionally identical.

I'm guessing that the performance difference is negligible and code style guidelines should win out. Some compilers might even optimize away the block into an access flag. And JIT may take the performance difference away.

like image 159
Mike Clark Avatar answered Sep 19 '22 17:09

Mike Clark