简体   繁体   English

synchronized(this)和synchronized方法有什么区别

[英]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. 在字节码级别, synchronized方法将其对同步的需要通告为方法的访问标志中的位集。 The JVM looks for this bit flag and synchronizes appropriately. JVM查找此位标志并进行适当的同步。

The synchronized block implements its synchronization through a sequence of bytecode operations stored in the class file's definition of the method. synchronized块通过存储在类文件的方法定义中的一系列字节码操作来实现其同步。

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. JIT可能会消除性能差异。

Check out this portion of this article: 看看这篇文章的这一部分:

http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/#4 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. 它解释了虽然功能一致(同步方法要么锁定实例对象,要么在静态方法的情况下锁定方法所在的类的Class对象),同步方法更加优化,因为它不是在字节码中同步(如同步块语句那样),它在JVM级别进行同步。

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. 最好只在需要时锁定,并尽快释放其他线程的锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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