ConcurrentModificationException主要原因及處理方法
當使用 fail-fast iterator 對 Collection 或 Map 進行迭代操作過程中嘗試直接修改 Collection / Map 的內容時,即使是在單線程下運行, java.util.ConcurrentModificationException 異常也將被拋出。
Iterator 是工作在一個獨立的線程中,并且擁有一個 mutex 鎖。 Iterator 被創建之后會建立一個指向原來對象的單鏈索引表,當原來的對象數量發生變化時,這個索引表的內容不會同步改變,所以當索引指針往后移動的時候就找不到要迭代的對象,所以按照 fail-fast 原則 Iterator 會馬上拋出 java.util.ConcurrentModificationException 異常。
所以 Iterator 在工作的時候是不允許被迭代的對象被改變的。但你可以使用 Iterator 本身的方法 remove() 來刪除對象, Iterator.remove() 方法會在刪除當前迭代對象的同時維護索引的一致性。
有意思的是如果你的 Collection / Map 對象實際只有一個元素的時候, ConcurrentModificationException 異常并不會被拋出。這也就是為什么在 javadoc 里面指出: it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Tests {
public static void main(String[] args) {
Set sett = new HashSet();
sett.add(new c("1"));
sett.add(new c("2"));
sett.add(new c("3"));
sett.add(new c("4"));
sett.add(new c("5"));
Iterator it = sett.iterator();
while(it.hasNext()){
c d= (c)it.next();
if("3".equals(d.getC()))
sett.remove(d);
}
}
}
class c{
private String c;
public c(String c){
this.c=c;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}

浙公網安備 33010602011771號