java快速失败分析

首先,上单线程版的。

import java.util.ArrayList;
import java.util.Iterator;


public class ConcurrentModification {

 
 public static void main(String[] args) {
  
  ArrayList<Integer> list=new ArrayList();
  for(int i=0;i<10;i++)
  {
   list.add(i);
  }
  Iterator it=list.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
   list.remove(it.next());
  }
 }
}


 

java源码解析:

AbstractList$Itr

<span style="font-size:18px;">	final void checkForComodification() {
	    if (modCount != expectedModCount)
		throw new ConcurrentModificationException();
	}
    }</span>


这个方法被遍历系列调用(next、previous),也会被修改系列方法调用(add、remove、set)。

modCount为实际修改次数,expectedModCount为期望修改次数。如果实际修改次数不等于期望修改次数的话,就会抛出如上异常。

那么我们看看next()方法:

<span style="font-size:18px;">   public boolean remove(Object o) {
	if (o == null) {
            for (int index = 0; index < size; index++)
		if (elementData[index] == null) {
		    fastRemove(index);
		    return true;
		}
	} else {
	    for (int index = 0; index < size; index++)
		if (o.equals(elementData[index])) {
		    fastRemove(index);
		    return true;
		}
        }
	return false;
    }</span>


而fastRemove()方法代码如下:

<span style="font-size:18px;">    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }</span>


很显然,只修改了modCount,但是expectedModCount并未变,那么到下一个next()方法时就会出现不一致,抛出异常。

 

至于避免的方法有两种:

Collections.synchronizedList()方法

CopyOnWriteArrayList

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值