I understand that similar questions have been asked before. I just have an additional question.
I have inherited code that is like the following. It is looping over a list using Iterator. The loop does not appear to make any changes to the List. The exception happens with a call to next() method. This is Eclipse RCP code. It is possible that another thread might be modifying the list.
for (Iterator iter = mylist.iterator(); iter.hasNext();) {
MyItem myItem = (MyItem) iter.next(); // ConcurrentModificationException happens here
.
.
.
}
I tried putting the code in a synchronized block but that did not resolve it. But when I change it to a regular for loop, I do not get the exception.
int list_size = myList.size();
for (int i = 0; i < list_size; i++) {
MyItem myItem = (MyItem) myList.get(i);
.
.
.
}
Even though I am not getting an exception here, is it possible that the list can still get modified by another thread while the above for loop is in progress? If so what are my alternatives? If I place the for loop in a synchronized block, would it guarantee that the list would not be modified while the loop is in progress?