我在多线程应用程序中编写了一个观察者模式,我想知道我的实现是否正常工作:
private void notifyObservers() {
Set<Observer> localObservers;
synchronized(MONITOR) {
if (mObservers != null)
observersCopy = new HashSet<>(observers);
}
for (Observer observer : localObservers) {
observer.update();
}
}
我的想法是否正确:
1. Thread A call notifyObservers().
2. Thread B call notifyObservers().
3. Thread A comes in synchronized section and hold lock.
4. Thread B is waiting before synchronized section.
5. Thread A creates his own copy of observers and leaves a synchronized section.
6. Thread B comes in synchronized section and hold lock, creates his own copy of observers and leaves a synchronized section.
7. Both threads notifies observers on their own copies.
我的问题是observers
的这些副本是否仅存在于创建副本的线程线程的本地内存中?是否意味着线程A具有独立且不共享的观察者副本,而线程B也具有独立且不共享的副本?