java基础:知道fail-fast,你知道fail-safe吗?

在Collection集合中,有线程安全和线程不安全这2大类的版本。对于线程不安全的类,并发情况下可能会出现fail-fast情况;而线程安全的类,可能出现fail-safe的情况。

fail-fast快速失败

当遍历一个集合对象时,如果集合对象的结构被修改了,就会抛出ConcurrentModificationExcetion异常。
以ArrayList的源码为例,讲解一下fail-fast的机制
1、modCount

    protected transient int modCount = 0;

modCount:代表修改的次数,add、remove操作都会使得modCount自增。
2、array的Iterator中有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
        //A、期望的改变值
        int expectedModCount = modCount;

        Itr() {}

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

        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
}

   public E next() {
		// B、校验modCount和expectedModCount区别
       checkForComodification();
       int i = cursor;
       if (i >= size)
           throw new NoSuchElementException();
       Object[] elementData = ArrayList.this.elementData;
       if (i >= elementData.length)
           throw new ConcurrentModificationException();
       cursor = i + 1;
       return (E) elementData[lastRet = i];
  }
  final void checkForComodification() {
     if (modCount != expectedModCount)
          throw new ConcurrentModificationException();
  }
        

fail-safe 安全失败

Fail-Safe 迭代的出现,是为了解决fail-fast抛出异常处理不方便的情况。fail-safe是针对线程安全的集合类;在java.util.concurrent 包中集合的迭代器,如 ConcurrentHashMap, CopyOnWriteArrayList等默认为都是Fail-Safe。
缺点是

  1. iterator不能保证返回集合更新后的数据,因为其工作在集合克隆上,而非集合本身。
  2. 创建集合拷贝需要相应的开销,包括时间和内存。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值