有关java.util.ConcurrentModificationException


java doc对这个类的定义:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. 



For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator
implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly,
rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future. 





Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the
object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception. 





Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis.
Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

 产生这个异常的原因:并发改动对象,而对象不支持并发改动。

比較常见的是多线程并发,或者单线程遍历集合的时候同一时候改动集合元素。

比方:
package com.doctor.java8;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; /**
* This program crashes by throwing java.util.ConcurrentModificationException. Why? Because the
* iterators of ArrayList are fail-fast; it fails by throwing ConcurrentModificationException if it detects that
* the underlying container has changed when it is iterating over the elements in the container. This behavior
* is useful in concurrent contexts when one thread modifies the underlying container when another thread is
* iterating over the elements of the container.
*
* @author sdcuike
*
* Created on 2016年3月6日 上午10:24:21
*/
public class ModifyingList { /**
* @param args
*/
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("three");
} // one
// Exception in thread "main" java.util.ConcurrentModificationException
// at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
// at java.util.ArrayList$Itr.next(ArrayList.java:851)
// at com.doctor.java8.ModifyingList.main(ModifyingList.java:24) } }

CopyOnWriteArrayList

既然普通集合的iterators是fail-fast的即不支持訪问同一时候改动的场景。那我们用并发容器CopyOnWriteArrayList。


package com.doctor.java8;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; /**
* Modifying CopyOnWriteArrayList
*
* Observe that the element “four” added three times is not printed as part of the output. This is because
* the iterator still has access to the original (unmodified) container that had three elements. If you create a
* new iterator and access the elements, you will find that new elements have been added to aList.
*
* @author sdcuike
*
* Created on 2016年3月6日 上午10:32:39
*/
public class ModifyingCopyOnWriteArrayList { /**
* @param args
*/
public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<>();
list.add("one");
list.add("two");
list.add("three"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("four");
}
// one
// two
// three
System.out.println("============");
iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// one
// two
// three
// four
// four
// four } }

java.util.concurrent.CopyOnWriteArrayList<E>

A thread-safe variant of java.util.ArrayList in which all mutative operations (add,set, and so on) are implemented by making a fresh copy of
the underlying array.

当对CopyOnWriteArrayList调用改动数据操作方法的时候。会copy一份新的内部数组结构,而对原来的内部数组结构没影响。

假设要訪问新的数据,我们必须又一次获取底层新的数组结构的iterator(见上面的程序)。

最新文章

  1. mysql每秒最多能插入多少条数据 ? 死磕性能压测
  2. supervisorctl error: &lt;class &#39;socket.error&#39;&gt;
  3. 关于jsp的总结
  4. cacti web页面访问 settings出错
  5. MongooseJS 4.6.4 发布,MongoDB 连接包
  6. dedecms升级后报错
  7. 传说中的WCF(11):会话(Session)
  8. 【二进制】FZU 2062 Suneast &amp; Yayamao
  9. [转]jquery.vTicker(垂直滚动)
  10. socket+网路编程
  11. 关于VS 2010 RDLC 报表的详细使用说明
  12. Sqrt(x) 牛顿迭代法
  13. javascript练习题(3):基础字符串运算
  14. iOS开发 GET、POST请求方法:NSURLSession篇
  15. [[NSBundle mainBundle] pathForResource:fileName ofType:]获取文件路径不成功
  16. Netty4 学习笔记之一:客户端与服务端通信 demo
  17. beta冲刺6-咸鱼
  18. PS制作简洁漂亮的立体抽丝文字
  19. keepalive配置mysql自动故障转移
  20. redis 删除大key集合的方法

热门文章

  1. cannot connect to host的解决办法
  2. Android使用charles抓包
  3. 书不在多,精读则灵 - Oracle入门书籍推荐
  4. java就业前景发展方向分析
  5. Caffe2:使用Caffe构建LSTM网络
  6. windows 下安装mysql 成功版
  7. PAT_A1144#The Missing Number
  8. Keras学习基础(2)
  9. XX-Net的完整教程
  10. phpMyAdmin使用教程