在Observable的notifyObservers方法中,为什么编码器使用arrLocal = obs.toArray();
? 为什么编码器不能直接迭代矢量?由于为什么可观察快照观察者矢量
public void notifyObservers(Object arg) {
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尝试在其回调中添加另一个侦听器(或将其本身作为侦听器),则选项1将创建死锁。 – sje397 2010-12-15 04:42:09
我认为线程本身不能死锁(观察者在同一个线程上调用)。当然,如果有更多的线程以某种方式参与进来,那么是的,那可能会发生。 – Thilo 2010-12-15 04:44:16
但是,选项一会导致ConcurrentModificationException,但如果观察者试图添加另一个侦听器。所以无论如何都要建议副本。 – Thilo 2010-12-15 04:49:19