在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