In this case the line
mapIterator.next()
throws ConcurrentModificationException
.
The reason behind this is:
There is an int
variable modCount
which provides the number of times list size has been changed, this value is used in every next()
call to check for any modifications in a function checkForComodification()
.
if mapIterator.next()
found change in modCount
while iteration object then it will throw ConcurrentModificationException
.
To avoid this please follow the below points:
You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.