ConcurrentModificationException问题?

rmn190 2007-12-02 08:40:23

import java.util.*;

public class TryIteratorRemove {
public static void main(String [] args){
Collection<String> myCollection = new ArrayList<String>(10);

myCollection.add("123");
myCollection.add("456");
myCollection.add("789");

int i=0;

for(Iterator it = myCollection.iterator();it.hasNext();) {
String myObject = (String)it.next();
System.out.println(myObject);

i++;

if(i==1){
//myCollection.remove(myObject);
it.remove();
}
}

System.out.println("After remove,the size of myCollection is: " +
myCollection.size()+" \n and its content is: ");

for(String s : myCollection){
System.out.println(s);
}
}
}


对于上面这段程序,为什么用'myCollection.remove(myObject);'时会报'ConcurrentModificationException'异常?而用'it.remove();'时没事呢?

我想从Java的源代码上找解释,可不知道从哪个类入手,把能想到的类都看了看,也没有解释通,请高手帮我看看。
谢谢!!

后来从书上看到以下解释:
"if one thread changes a collection while another
thread is traversing it through with an iterator the iterator.hasNext() or iterator.next() call will throw
ConcurrentModificationException. Even the synchronized collection wrapper classes SynchronizedMap and
SynchronizedList are only conditionally thread-safe, which means all individual operations are thread-safe but compound
operations where flow of control depends on the results of previous operations may be subject to threading issues."
不过我有以下疑问:
1,上面程序出错是由于线程问题吗?上面说到'当一个线程用iterator遍历collection时,另一个线程修改colleciton,iterator.hasNext()或iterator.next()就会抛出ConcurrentModificationException异常'。我想知道在上面我写的那段程序中是main线程修改这个collection吗?那对collection进行遍历的线程又是哪个呢?是Iterator自己又开了一个线程?
2,有没有例子演示下'all individual operations are thread-safe but compound
operations where flow of control depends on the results of previous operations may be subject to threading issues.'这段说的是什么?这个individual operations指的会是什么?
...全文
146 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
coolzyt 2007-12-02
  • 打赏
  • 举报
回复
我知道这个异常,但没有研究过细节原因。
看你的解释,可以认为是迭代器自己开了一个线程,以集合类为锁进行了操作,所以main线程不能修改吧。
后面说的是就算并发的map也有线程安全的问题,individual operations指的是原子操作,compound operations 指的是混合操作。

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧