前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 源代码里的failure mode

java 源代码里的failure mode

原创
作者头像
CoffeeLand
修改2020-03-09 10:21:03
7370
修改2020-03-09 10:21:03
举报
文章被收录于专栏:CoffeeLand

Table of Content

  • fail-fast 机制
  • fail-safe 机制
  • refers

fail-fast

fail-fast: java对于使用iterator迭代器来遍历集合元素时, 对同时使用集合的add/remove修改集合元素, 这样由于集合用自身的方法修改时仅仅修改了自身的modCount,但是修改不了iterator的expectedModCount, 触发了fail-fast的条件,使得程序会停止这种修改行为并上报error的一种机制.

fail-fast的案例

代码语言:javascript
复制
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() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            return cursor != elementCount;
        }
        
        ......
        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.remove(lastRet);
                expectedModCount = modCount;
            }
            cursor = lastRet;
            lastRet = -1;
        }
        
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
}

代码语言:javascript
复制
会抛出ConcurrentModificationException

fail-fast集合

CopyOnWriteArrayList, ConcurrentHashMap

fail-fast的解决方案

  • 使用基础for循环, 不要用foreach循环, foreach循环的底层是while和iterator
  • 使用fail-safe的集合

fail-safe

fail-safe的iterator在遍历时对集合的结构性更改(add,remove, update)不会throw CME异常, 因为这些fail-safe的集合是CopyOnWrite (COW), 也就是这些集合在做结构性更改的时候是对集合的clone进行操作, 等修改完再让oldRef = newRef

fail-safe 集合

CopyOnWriteArrayList, ConcurrentHashMap

Refers


此篇文章对你有帮助, 请不要吝啬你的赞, 因为这是对我创作的支持.

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Table of Content
  • fail-fast
    • fail-fast的案例
      • fail-fast集合
        • fail-fast的解决方案
        • fail-safe
          • fail-safe 集合
          • Refers
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档