下面是一些僞代碼,如下所示。防止併發修改異常的最佳方法
public class MyObject
{
private List<Object> someStuff;
private Timer timer;
public MyObject()
{
someStuff = new ArrayList<Object>();
timer = new Timer(new TimerTask(){
public void run()
{
for(Object o : someStuff)
{
//do some more stuff involving add and removes possibly
}
}
}, 0, 60*1000);
}
public List<Object> getSomeStuff()
{
return this.someStuff;
}
}
所以基本上的問題是,在上面的代碼中未列出的其他對象調用getSomeStuff()來獲取列表用於只讀目的。當發生這種情況時,我在計時器線程中獲得了併發修改異常。我試着讓getSomeStuff方法同步,甚至在計時器線程中嘗試同步塊,但仍然不斷收到錯誤。什麼是阻止併發訪問列表最簡單的方法?
但是,在線程中完成的工作(添加和刪除)必須實際上保留在列表對象中。我只是不希望其他線程訪問列表進行讀取(foreach循環),導致JVM出現異常。 – thatidiotguy 2012-04-19 14:17:37
好的,請參閱我的關於刪除/迭代列表的更新。 – 2012-04-19 14:34:01
我想我只是覺得用Java的synchronize關鍵字做一些事情是可能的,但你是說這不是這種情況?這些Lock和ReadWriteLock包含哪些包?另外,我只需要在定時器的run方法執行時鎖定列表本身,這是你推薦的方法嗎? – thatidiotguy 2012-04-19 14:44:08