Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable Java class: clearChanged() and notify observers ... what order?

Tags:

java

If we look at the JavaDoc for the Observable notifyObservers() method, we read the following:

"...then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed."

This is pretty unambiguous (to me). What happens is that we notify each registered observer and THEN the clearChanged() method is invoked. However, in my testing, what I was finding was that the clearChanged() method was being invoked and THEN the registered observers were being called. The order which is documented is reversed from the order of what I seem to actually see.

I then examined the source for Observable and seem to find that experienced behavior (clearChanged() and THEN notified observables is what is coded to happen).

Given that this class has been around since Java 1.1, I must believe that I am somehow incorrect in my assumption that the observers are called and then clearChanged() is called. Can anyone see where my thinking is incorrect?

like image 597
Kolban Avatar asked Dec 06 '25 23:12

Kolban


1 Answers

Your logic is correct. Look at the source code for Observable:

  public void notifyObservers() {
    notifyObservers(null);
}

and

  public void notifyObservers(Object arg) {
    /*
     * a temporary array buffer, used as a snapshot of the state of
     * current Observers.
     */
    Object[] arrLocal;

    synchronized (this) {

        if (!changed)
            return;
        arrLocal = obs.toArray();
        clearChanged();
    }

    for (int i = arrLocal.length-1; i>=0; i--)
        ((Observer)arrLocal[i]).update(this, arg);
}

What you describe is exactly what happens - clearChanged() is called before everything is updated.

Probably just a typo in the Java Docs - Good job on finding it ;)

EDIT: Code from http://docs.oracle.com/javase/7/docs/api/java/util/Observable.html#notifyObservers()

like image 150
Dean Leitersdorf Avatar answered Dec 09 '25 13:12

Dean Leitersdorf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!