我正在處理來自TCP套接字(每秒10套)的很多事件,所以我使用多線程來處理這些事件。ConcurrentModificationException在同步方法
public class MainActivity extends Activity {
...
// In this Map I store the tab name and the associated TabHost.TabSpec instance
private static Map<String, TabHost.TabSpec> Tabs = Collections.synchronizedMap(new LinkedHashMap<String, TabHost.TabSpec>());
// In this Map I store pairs of tab-names and a HashSet of undelivered messages
// It's a class that extends Map<String, HashSet<String>> with some additional functions that doesn't have anything to do with Tabs.
private static NamesListing Names = Collections.synchronizedMap(new LinkedHashMap<String, HashSet<String>>());
// Yes, I know the names don't follow the Java standards, but I keeped them for mantaining the question coherence. I will change it in my code, though.
synchronized private static void ProcessEvent(final String name, final String message) {
// Low-priority thread
final Thread lowp = new Thread(
new Runnable() {
public void run() {
final Iterator<String> iter = Tabs.keySet().iterator();
while (iter.hasNext()) {
final String tabname = iter.next();
// This just returns an int making some calculations over the tabname
final int Status = Names.getUserStatus(tabname, message);
// Same than getUserStatus
if ((Names.isUserSpecial(Status)) && (name.equals(tabname))) {
// This just removes a line from the HashSet
Names.delLine(tabname, message);
}
}
}
});
lowp.setPriority(3);
lowp.start();
}
...
}
多數時候這個作品的權利,但有時也有這些事件的一些雪崩,並somethimes我得到一個ConcurrentModificationException的:
12-10 14:08:42.071:E/AndroidRuntime( 28135):FATAL EXCEPTION: 線程-369 12-10 14:08:42.071:E/AndroidRuntime(28135): java.util.ConcurrentModificationException 12-10 14:08:42.071: E/AndroidRuntime(28135):at java.util.LinkedHashMap $ LinkedHashIterator.nextEntry(LinkedHashMap.java:347) 12-10 14:08:42.071: E/AndroidRuntime(28135):at java.util.LinkedHashMap $ KeyIterator.next(LinkedHashMap.java:367)12-10 14:08:42.071:E/AndroidRuntime(28135):at es.irchispano.chat。 MainActivity $ 6.run(MainActivity.java:244)12-10 14:08:42.071:E/AndroidRuntime(28135):在 java.lang.Thread.run(Thread.java:841)
注:244行對應於
final String tabname = iter.next();
聲明。
對我來說這似乎很奇怪,因爲我正在使用Collections.synchronizedMap,並且處理這些行的方法是同步的,那爲什麼它仍然在發生?
謝謝!
---------- ----------編輯
很抱歉的簡潔初始代碼;我試圖儘可能簡化,但顯然這不是一個好主意。我正在粘貼實際的代碼。當然,這些結構中的每一個都被初始化了(否則我不會有問題:-)),現在我將閱讀你所有的良心評論,我會發布我會發現的。謝謝大家的支持!
'doSomeAdditionalStuff()'修改地圖嗎? – rgettman
^因爲這是關鍵:) –
@rgettman不會做任何事情的地圖 – nKn