集合类-fasi-fail(快速失败机制)

fasi-fail是Java集合的一种错误机制,当多个线程去访问同一个集合进行操作时,比如某个线程通过iterator去访问时另外一个线程去改变集合中的某个元素时就可能会抛出ConcurrentModificationException异常,产生fail-fast事件。

分析源码

fail-fast出现是在遍历集合的时候出现的,也就是对集合进行迭代的时候,对集合进行迭代的时候都是操作迭代器,集合中的内部类:(ArrayList源码)

private class Itr implements Iterator<E> {
        int cursor;       
        int lastRet = -1; 
        int expectedModCount = modCount;//---------------------1

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

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            //………此处代码省略…………
        }

        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();
            }
        }

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

在调用next,remove方法时都会调用checkForComodification方法,而这个方法会去检查一个modeCount是否和expectedModCount相等,
modCount变量在集合调用add,remove,clear方法都会自增
在迭代的时候每次都会检查这个变量是否与expectedModCount一致,因为如果是在集合中添加或者删除元素modCount的值都会发生改变。

解决方法

  • 对于涉及到更改集合中元素个数的操作通通加上synchronized,或者利用Collections.synchronizedList强制他们的操作都是同步的。(全部方法加关键字synchronized)
  • 使用CopyOnWriteArrayList来替换ArrayList
CopyOnWriteArrayList为什么有用
 public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            //对数组进行复制
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

//同时还有remove,set等都是对底层数组进行一次复制

那如何保证内存的一致性呢?毕竟又没有modCount去记录
看上面的 Object[] elements = getArray();源码

final Object[] getArray() {
        return array;
    }
这个array用了volatile去保证内存一致性
  /** The array, accessed only via getArray/setArray. */
    private transient volatile Object[] array;

参考文章:https://www.cnblogs.com/duzhentong/p/8597512.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值