java - 我应该同步 notifyObservers 调用吗?

标签 java multithreading observable observer-pattern synchronized

我发现了 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 block 的使用和我在上面找到的代码中的 synchronized block 的使用,两者都需要吗?有更好(正确)的方法吗?

最佳答案

你不应该在持有锁的情况下调用 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 的响应能力。

关于java - 我应该同步 notifyObservers 调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355953/

相关文章:

javascript - 在一个标签中取消订阅可观察到禁用所有?

android - RxJava + 改造,获取列表并为每个项目添加额外信息

java - 应用架构 : keeping serial connections open in java

java - Spring事务JMS+MyBatis

java - 使用 GridBagLayout 时如何将 TextArea 从 "snapping"停止为不同的大小

c++ - 对 STL 容器的安全并行只读访问

java - 如何在手机 hibernate 时继续使用 onSensorChanged()?

.net - MSTest:断言线程执行

c++ - 了解使用 std::condition_variable 的示例

javascript - 可观察数组的 knockout 过滤