Fail-fast

具体来说就是,当创建了iterator后,如果对list进行了结构性的修改,并且不是通过iterator的方法进行的修改(add、remove)那么就会抛出@ConcurrentModificationException异常

LinkedList中,定义了私有类ListItr实现ListIterator接口,在该类中定义了一个名叫expectedModCount的int变量,且=modCount

该值的作用就是控制在使用Iterator进行集合操作时,保证并发访问的安全型,如果在调用iterator的方法操作集合时,发现expectedModcount  != modCount,则会抛出@ConcurrentModificationException异常

 private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;
    ......
}    

比如说ListItr中的remove方法

public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            //unlink方法会使modCount+1
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            //期望的修改次数+1
            expectedModCount++;
        }


//检查两者是否相等
final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

但如果在使用iterator进行操作时,直接调用了非iterator的修改方法,那么modCount和expectModCount就不相等,抛出异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值