简体   繁体   中英

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?

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.

Check out this portion of this article:

http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/#4

It explains that while functionally congruent (synchronizing a method either locks on the instance Object or in the case of a static method the Class object of the class in which the method resides), synchronizing a method is much more optimal because rather than synchronizing in bytecode (as the synchronized block statements do), it synchronizes at the JVM level.

One difference is the granularity of the code that is synchronized. In the first example you are essentially locking the entire method, while in the second example only a section of the method will be locked. The second approach is better for long methods whose bodies do not need to be completely synchronized. Its best to only lock when you need to and release that lock for other threads as soon as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM