开发者

Difference between using synchronized on "this" and a private "new Object"?

开发者 https://www.devze.com 2023-01-18 18:39 出处:网络
Will following 2 code block achieve t开发者_开发问答he same result. What is the difference better then, if any?

Will following 2 code block achieve t开发者_开发问答he same result. What is the difference better then, if any?

class test {
 Object obj = new Object();

 void test(){
  synchronized(obj){

  }
 }

 void test1(){
  synchronized(this){

  }
 }
}


No, they don't do the same thing. One of them acquires the monitor on "this", and the other acquires the monitor on the object referred to by obj.

Normally it's a better idea to synchronize using a private variable, never exposing that variables value to any other code. That means you know that the code in your class is the only code which will be synchronizing on that object, which makes your code easier to reason about. If you synchronize on any monitor which other code could also synchronize on (including the this reference) you've got much more code to reason about when considering thread safety, deadlocking etc.

0

精彩评论

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

关注公众号