将CopyOnWriteArrayList序列化时可能抛出ConcurrentModificationException,如何解决?

forlml 2011-02-14 10:21:25
我用CopyOnWriteArrayList来保存着一个列表,该列表可能被其他线程改变。而在序列化到流的writeObject方法中,其有概率抛出ConcurrentModificationException,这是为什么呢?应该怎么解决?
...全文
275 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
easyroom 2011-02-19
  • 打赏
  • 举报
回复
楼主,堆栈信息贴一下,还有代码

我看了半天CopyOnWriteArrayList也没看出来它怎么可能抛出这个异常
ilrxx 2011-02-14
  • 打赏
  • 举报
回复
arraylist是线程不安全的,如果用了CopyOnWriteArrayList,其底层是arraylist的话,应该也没有好的办法,除非换成线程安全的数据结构,或者你自己重写。。
贪食蛇男 2011-02-14
  • 打赏
  • 举报
回复
多个线程不能同时修改一个集合
forlml 2011-02-14
  • 打赏
  • 举报
回复
异常底层是由ArrayList里面抛出的,但是按理说CopyOnWriteArrayList说了是线程安全,那么我在直接writeObject的时候应该获得一个不变的ArrayList才对吧。可是竟然会出问题……

数据肯定会被修改,只是怎么才能保证在writeObject的时候不出问题。因为程序有不少地方是把对象序列化的,同时不少地方是在修改该对象的,所以想找一个在修改的同时序列化能不出问题的容器……
  • 打赏
  • 举报
回复
并发修改异常
你在写入的同时,数据有可能被其他程序改动了。






希望对你有帮助
dracularking 2011-02-14
  • 打赏
  • 举报
回复
The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.

看后面的解释,对iterator的修改貌似也是不支持或不会反映到iterator上的,这个层面来讲应该是安全的,不知道lz能不能还原一小段模拟程序,类似如下:


public static void main(String[] args) {
CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList<Integer>();
cowal.add(1);
cowal.add(2);
cowal.add(3);

List<Integer> sub = cowal.subList(1, 2);
cowal.add(4);
sub.get(0); // throws ConcurrentModificationException
}


humanity 2011-02-14
  • 打赏
  • 举报
回复
CopyOnWriteArrayList 假设在迭代器的迭代中是不会修改这个 list 的,如果你在迭代过程中通过迭代器去修改它(Iterator iter ... iter.set(xxx))就会出现这个异常。

它工作时,修改的操作仅发生在 List 中定义的方法,如果你想在它的迭代器中也修改它,那还是需要同步的。

62,614

社区成员

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

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