开发者

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

开发者 https://www.devze.com 2023-01-29 09:04 出处:网络
Lets say we have these 2 sample code : public synchronized void getSomething(){ this.hello = \"hello World\";

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 d开发者_JS百科ifference 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消