i have a question, what is difference between
StringBuilder sb = new StringBuilder();
public void sync(){
synchronized(sb){
};
}
and
public void sync(){
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.
In the first case, you lock on “sb” variable, and in the second case, in “this” object.
This is obvious, but i suppose you want to know which is better.
Well, the first case is better, because you lock on a local variable (consider to make it private) and you are quite sure that no other is going to lock on it than you.
If you lock on “this”, any other thread could use this object to lock, preventing you from running the synchronized code (whereas you safely could).