我正在开发一个项目,使用观察者设计模式。主题类是:
public class Subject {
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
public void deattach(Observer observer) {
observers.remove(observer);
}
}
观察者接口是:
public abstract class Observer implements Runnable{
protected Subject subject;
public abstract void update();
public abstract void process();
}
其中一个被命名为HexObserver的观察者是:
public class HexaObserver extends Observer {
private ExecutorService threadpool = Executors.newFixedThreadPool(10);
public HexaObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("Hex String: "
+ Integer.toHexString(subject.getState()));
Future future = threadpool.submit(new HexaObserver(subject));
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("In run :D :D :D");
}
@Override
public void process() {
// TODO
}
}
需要测试的类是:
public class Demo {
public static void main(String[] args) {
Subject subject = new Subject();
HexaObserver hob = new HexaObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
}
}
当我尝试运行这个程序时,它报错了:
First state change: 15
Hex String: f
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Observer.Subject.notifyAllObservers(Subject.java:23)
at Observer.Subject.setState(Subject.java:15)
at Observer.Demo.main(Demo.java:12)
In run :D :D :D
我不明白为什么会出现这个错误,因为当我们尝试在不允许的情况下同时修改某个对象时,ConcurrentModificationException
就会被抛出。
我是否漏掉了什么?
ArrayList
更改为并发实现,例如CopyOnWriteArrayList
。 - BretCupdate()
中添加了一个新的HexaObserver
(包括构造函数中的隐式附加)。可能意图使用submit(this)
吗?或者提交一个新的不可变且线程安全的对象,而无需隐式附加。 - Markus Kull