ConcurrentModificationException异常

来源:互联网 发布:360软件宝库 编辑:程序博客网 时间:2024/05/17 23:59

http://blog.csdn.net/lirunfa/article/details/7353857

最近在写android程序的过程中,对容器ArrayList操作的时候,碰到了java.util.ConcurrentModificationException异常,是在遍历一个容器的时候,删除容器里面的元素:

[java] view plaincopy
  1. foreach(element e: list){  
  2.     if(condition){  
  3.         list.remove(e);  
  4.     }  
  5. };  


官方文档中的说法是这样的:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.(concurrent是同时发生,大概意思是当一个object被同时修改的时候,而且该修改是不允许的,就会报这个异常)

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.(这种称作fail-fast迭代器,它们失效的很快而且很干净利落而不是愿意冒发生不确定行为的危险, 大概就是说, 遇到这种情况迭代器自己直接就把自己给失效了)

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. (这种异常不总是在一个object被不同线程同时修改时抛出, 即不是总是抛出这个异常)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.(当一个线程对一个容器操作的时候, 例如用fail-fast迭代器边遍历边修改这个容器,就是抛出这个异常)

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 throwConcurrentModificationException 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.


        感觉有点像STL中的迭代器失效,解决这个异常的方法是:

[java] view plaincopy
  1.      Iterator<Element> e = list.iterator();    
  2.      while(e.hasNext()){    
  3. Element element = e.next();  
  4. if(condition){  
  5.     e.remove();  
  6. }  
  7.      }  
0 0
原创粉丝点击