对HashMap, Vector、ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常
单线程例子(来自网络)
public
class
Test {
public
static
void
main(String[] args) {
ArrayList<Integer> list =
new
ArrayList<Integer>();
list.add(
2
);
Iterator<Integer> iterator = list.iterator();
while
(iterator.hasNext()){
Integer integer = iterator.next();
if
(integer==
2
)
list.remove(integer);
}
}
}
主要原因在于这个
final
void
checkForComodification() {
if
(modCount != expectedModCount)
throw
new
ConcurrentModificationException();
}
上面的例子修改为就OK
Iterator<Integer> iterator = list.iterator();
while
(iterator.hasNext()){
Integer integer = iterator.next();
if
(integer==
2
)
iterator.remove();
}
多线程
1. 加上synchronized
2. 用CopyOnWriteArrayList,ConcurrentHasMap代替