Java.util.ConcurrentModificationException will be thrown if HashMap, Vector, ArrayList are modified at the same time when iterating.
Single-threaded example (from the network)
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();
}
The above example is modified to OK
Iterator<Integer> iterator = list.iterator();
while
(iterator.hasNext()){
Integer integer = iterator.next();
if
(integer==
2
)
iterator.remove();
}
Multithreading
1. Add synchronized
2. Use CopyOnWriteArrayList, ConcurrentHasMap instead