我应该同步 notifyObservers 调用吗?

Should I synchronize notifyObservers calls?

我找到了 Observable 的这个实现:

public class ObservableObject extends Observable {
    private static ObservableObject instance = new ObservableObject();

    public static ObservableObject getInstance() {
        return instance;
    }

    private ObservableObject() {
    }

    public void updateValue(Object data) {
        synchronized (this) {
            // The call to setChanged marks this Observable object as having been changed; the hasChanged method will now return true.
            setChanged();
            notifyObservers(data);
        }
    }
}

我想了解的是 default implementation 使用 synchronized 块和在我上面找到的代码中使用 synchronized 块有什么区别,是否需要两者?,是有更好(正确)的方法吗?

你不应该在持有锁的情况下调用 notifyObservers。由于链接代码评论中引用的原因,发布的代码有缺陷:

We don't want the Observer doing callbacks into arbitrary code while holding its own Monitor. The code where we extract each Observable from the Vector and store the state of the Observer needs synchronization, but notifying observers does not (should not). The worst result of any potential race-condition here is that:

1) a newly-added Observer will miss a notification in progress

2) a recently unregistered Observer will be wrongly notified when it doesn't care

方法 notifyObservers 包括更新 java.util.Observable 代码小心保持不同步的观察者的调用。如果 observable 在更新观察者时持有自己的锁,而 observable 无法控制观察者的行为,则无法确定锁可以持有多长时间,从而影响 observable 的响应能力。