java中的Observable的实现除了notifyObservers方法中只用synchronized锁了部分代码块,其它方法都是同步的。
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* 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
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
可以看到调用各个Observer时 不应该同步。因为如果同步的话,Observable类不能知道各个Observer中做了什么,需要锁定多长时间,会使程序卡在这。
同时,Observable类中,存储观察者用的是Vector,这同样是为了保证一致性,虽然类中的每个方法是同步的,但是比如:如果两个线程同时调用添加和删除观察者,也会产生一致性的错误