Sunday, September 19, 2010

Java Hidden Iterator causing ConcurrentModificationException

The " System.out.println("DEBUG: added ten elements to " + set);" effectively compiles into a HiddenIterator that iterates the "set", and this is not thread-safe.

Work around is to wrap "set" into a synchronizedSet

public class HiddenIterator {
@GuardedBy("this")
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 i = 0; i < 10; i++)
add(r.nextInt());
System.out.println("DEBUG: added ten elements to " + set);
}
}

No comments:

Post a Comment