This is related, but definitely not identical, to this famous SO question:
Avoid synchronized(this) in Java?
Very often I've got an "observable subject" that likes to notify its observers when it is modified. The notification is basically making "alien method" calls (as they're called in Effective Java etc.) I may have something like this:
public void updateData(params) {
synchronized (this) {
// do some computation here
}
notifyObservers(); // Never, EVER, call an alien method with a lock held (see Effective Java)
}
public synchronized Result getResult() {
...
}
Should I be avoiding the synchronized(this)
and hence also remove the synchronized
from the getResult()
method?
Is this the following that people advising against synchronized(this)
are recommending:
private final Object lock = new Object(); // shiny lock
public void updateDate(params) {
synchronized( lock ) {
...
}
notifyObservers();
}
public Result getResult() {
synchronized( lock ) {
return Result;
}
}
As a bonus question that doesn't warrant it's own SO question: if the latter is recommended, what do people who advise against using synchronized(this) think about the fact that methods in Java can be declared as "synchronized"?