This code will throw Concurrent Modification Exception if the list is modified in doSomething(). Is it possible to avoid it by enclosing the code in some synchronized block?
List l = Collections.synchronizedList(new ArrayList());
// normal iteration -- can throw ConcurrentModificationException
// may require external synchronization
for (Iterator i=list.iterator(); i.hasNext(); ) {
doSomething(i.next());
}
if you are removing an item from the list, you can do it by calling
iterator.remove()instead oflist.remove(iterator.next())if you are adding an item – well, create a copy of the iterated list and add it there
if the code snippet above is part of the same method, then you don’t need a synchronized list or synchronized blocks – no other thread can access the local list.