I am reading Java Concurrency in Practice, according to some java code in it, System.out.println()
will led to ConcurrentModificationException
. The code is below :
private final Set<Integer> set = new HashSet<Integer>();
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: add ten elements to " + set );
}
Since the System.out.println()
method will just call the toString
method:
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
I still can not understand why ConcurrentModificationException
be throw??