… While locking can prevent iterators from throwing ConcurrentMofdificationException, You have to remember to use locking everywhere a shared collection might be iterated. This is trickier than it sounds …
Brian Goetz p.83-84
Question: The following code could throw ConcurrentMofdificationException, even though add() is synchronized, why?
public class HiddenIterator {
private final Set set = new HashSet();
public synchronized void add(Integer i) {
set.add(i);
}
public synchronized void remove(Integer i) {
set.remove(i);
}
public void addTenThings() {
Random r = new Random();
for (int index = 0; index < 10; index++;) {
add(r.nextInt());
}
System.out.println("Added ten elements to set: " + set);
}
}
Looking forward for your answers dear readers