Java集合框架中的modCount字段与ConcurrentModificationException

 在并发环境下使用Java的集合框架,比如ArrayList、HashMap时,有时候会报ConcurrentModificationException。那么这个异常到底是怎么产生的呢?我们以ArrayList为例来说明这个问题。

1、我们在ArrayList中搜索ConcurrentModificationException,会看到下面的代码:

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

        通过上面的代码可知,ConcurrentModificationException异常是由modCount和expectedModCount不一致所导致的。那么,我们可以看下这个modCount和expectedModCount是啥,有啥作用;

2、查看ArrayList中modCount的字段声明:

//表示list被结构性的修改的次数,这种修改主要包括改变list的大小(新增元素、删除元素)
protected transient int modCount = 0;

ArrayList里有对modCount含义的介绍,大家可以自己看源代码。

接着,我们看下modCount在什么时机会被修改:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }


    ensureExplicitCapacity(minCapacity);
}

//新增元素时,modCount会+1
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;


    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

public E remove(int index) {
    rangeCheck(index);

    //删除元素时,modCount会+1
    modCount++;
    E oldValue = elementData(index);


    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work


    return oldValue;
}

总的来说,当发生改变size变量的操作时,就会触发modCount+1;

3、再来看下expectedModCount

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    //expectedModCount是迭代器里的字段,初始值为ArrayList里的modCount字段
    int expectedModCount = modCount;
}

4、我们再看下什么时候会触发报ConcurrentModificationException的位置

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;


    public boolean hasNext() {
        return cursor != size;
    }


    //迭代器获取下一个元素的操作
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        //size容量变更,触发异常
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    //迭代器的删除操作
    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();


        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }


    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    //这里校验modCount,当迭代器在进行迭代操作时,如果ArrayList的modCount发生变更(也就是ArrayList里的元素数量发生变更),那么就抛出ConcurrentModificationException异常
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

5、总结分析

1)当获取ArrayList的迭代器iterator后,在iterator进行next()或remove()操作时,如果ArrayList的size发生变更时,就会抛出ConcurrentModificationException异常。

2)为什么迭代器在操作时,list的容量发生了变更,就要抛出异常?

        结合iterrator的next方法,我们可以看到,如果没有这个校验,某个线程删除了list的一个元素,此时next方法不知道size变更了,依然去取数组里的数据,会导致数据为null或ArrayIndexOutOfBoundsException异常等问题。

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值