开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜