Wednesday, June 18, 2014


Java Collection Itereator to avoid ConcurrentModificationException getting while iterating the collection and try to remove the element from the collecation:

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. This situation can come in case of multithreaded as well as single threaded environment.

To Avoid ConcurrentModificationException in multi-threaded environment:

1. 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.

2. 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.

3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

Example:

public void removeRow(){
Iterator it = new CopyOnWriteArrayList(empGroupList).iterator();
while(it.hasNext()) {
EmpGroupData empData = it.next();
if(empData.isSelected()) {
empGroupList.remove(empData);
}
}
for(EmpGroupData empData: empGroupList) {
System.out.println("empno:"+empData.getEmpNo());
}

}

No comments: