Well, firstly it should be pointed out that:
public void blah() {
synchronized (this) {
// do stuff
}
}
is semantically equivalent to:
public synchronized void blah() {
// do stuff
}
Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that
synchronized(this)
should be avoided. Instead, they claim, a lock on a private reference is to be preferred.
Some of the given reasons are:
- some evil code may steal your lock (very popular this one, also has an "accidentally" variant)
- all synchronized methods within the same class use the exact same lock, which reduces throughput
- you are (unnecessarily) exposing too much information
I'll cover each point separately.
- Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)I'm more worried about accidentally. What it amounts to is that this use of
this
is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things likeCollections.synchronizedMap
(see the javadoc). - All synchronized methods within the same class use the exact same lock, which reduces throughputThis is overly simplistic thinking; just getting rid of
synchronized(this)
won't solve the problem. Proper synchronization for throughput will take more thought. - You are (unnecessarily) exposing too much informationThis is a variant of #1. Use of
synchronized(this)
is part of your interface. If you don't want/need this exposed, don't do it.
Comments
Post a Comment