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){
}
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
thisreference) you’ve got much more code to reason about when considering thread safety, deadlocking etc.