Re: Why is Observerable.setChanged() synchronized
"Thomas Weidenfeller" <nobody@ericsson.invalid> wrote in message
news:eice4e$pep$1@news.al.sw.ericsson.se...
tomerbd1@gmail.com wrote:
I'm looking at java.util.Observable code and I noticed that
setChanged() is synchronized, however i can't figure out why... anyone
can help me?
protected synchronized void setChanged() {
changed = true;
}
A couple of remarks, non of which might apply:
(b) One can see such things in several of the original Java 1.0 classes,
e.g. the pre-collection classes like Hashtable. My guess is that the
original Java designers were a little bit naive when it came to
multithreading and synchronization.
Or, more likely, they understood it quite well
If you want a change to the state of an object to be visible in all threads,
you need to synchronize both the code that makes the change and the code
that checks for the change. Observable does this correctly:
protected synchronized void setChanged() {
changed = true;
}
protected synchronized void clearChanged() {
changed = false;
}
public synchronized boolean hasChanged() {
return changed;
}
Without the synchronization, there is no guarantee under the Java memory
model that the result of a call to setChanged() in thread 1 will result in
hasChanged() returning "true" in thread 2.