Basic java synchronization
i have a question, wh开发者_开发知识库at is difference between
StringBuilder sb = new StringBuilder();
public void sync(){
synchronized(sb){
};
}
and
public void sync(){
synchronized(this){
};
}
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).
It's exactly the same syntax. In both cases, you're synchronizing using a particular reference - the synchronized block will acquire the monitor associated with the object that the reference refers to. In both cases, other threads will be blocked if they try to acquire the monitor for the same object, until the original thread releases the monitor.
It's just that in the first case the reference is sb
, and in the second case it's this
. The value of this
is just a reference, like any other (except guaranteed not to be null).
In java synchronization is done around a concept called a monitor. The argument to the synchronized
is which monitor you are locking.
精彩评论