Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

java - Why concurrentmodificationexception when print a set with System.out.println()?

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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Suppose 2 threads - A and B executing the method addTenThings() at the same time. They can do it, as the method isn't synchronized.

Then if during the time the thread A is executing toString() method of set, thus iterating over it, the thread B is still executing the loop, and invokes the add() method, that might cause ConcurrentModificationException, as both the threads are operating on the same set only. Nothing stops a thread to execute the add(r.nextInt()) statement, while a different thread is executing the print statement in the method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...