Java中的线程安全观察者模式

时间:2017-12-16 23:34:31

标签: java multithreading synchronization

我在多线程应用程序中编写了一个观察者模式,我想知道我的实现是否正常工作:

    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也具有独立且不共享的副本?

0 个答案:

没有答案