简体   繁体   中英

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

Will following 2 code block achieve the 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.

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