了解Java的安全失败机制(fail-safe)

最近我也在翻看一些源代码,从头到尾的看了一下HashMap的底层发现了一个这个东西——安全失败机制(fail-safe),以此作为记录!


首先,fail-fast 机制是java集合(Collection)中的一种错误机制。

当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。
要了解fail-fast机制,我们首先要对ConcurrentModificationException 异常有所了解。当方法检测到对象的并发修改,但不允许这种修改时就抛出该异常。同时需要注意的是,该异常不会始终指出对象已经由不同线程并发修改,如果单线程违反了规则,同样也有可能会抛出该异常。

注意: 迭代器的快速失败行为无法得到保证,它不能保证一定会出现该错误,但是快速失败操作会尽最大努力抛出ConcurrentModificationException异常,所以因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,ConcurrentModificationException 应该多用于检测 bug。


那么先举一个小例子之后再进入源码,例子如下:

首先,ConcurrentModificationException异常是通过多线程并发修改而造成的问题。那么写一个错误代码看一下红红的异常结果!(单线程情况、多线程情况)

单线程产生异常

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 1.创建一个ArrayList集合
 * 2.在集合中添加10个数字
 * 3.用迭代器遍历该集合
 * 4.在遍历的同时加入条件进行remove移除元素
 * 5.在当条件满足时,会产出异常:java.util.ConcurrentModificationException
 */
public class TestFailSafe1 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i + "");
        }
        Iterator<String> iterator = list.iterator();
        int count = 0;
        while (iterator.hasNext()) {
            if (count == 5) {
                list.remove(5);
            }
            System.out.println(iterator.next());
            count++;
        }
    }
}

在这里插入图片描述
多线程产生异常

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 启动两个线程
 * 对其中一个对list进行迭代
 * 另一个在线程1的迭代过程中去remove一个元素
 * 结果也是产生了异常:java.util.ConcurrentModificationException
 */
public class TestFailSafe {
    private static List<Integer> list = new ArrayList<>();

    private static class thread1 extends Thread {
        @Override
        public void run() {
            Iterator<Integer> integer = list.iterator();
            while (integer.hasNext()) {
                int i = integer.next();
                System.out.println("Thread0 - " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static class thread2 extends Thread {
        @Override
        public void run() {
            int i = 0;
            while (i < 6) {
                System.out.println("Thread1 - " + i);
                if (i == 3) {
                    list.remove(i);
                }
                i++;
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        new thread1().start();
        new thread2().start();

    }
}

在这里插入图片描述
两次运行结果相同,都抛出异常java.util.ConcurrentModificationException!即,产生fail-fast事件!


然后我们就去追一下源码,去看一下ArrayList源码里迭代器的定义!

private class Itr implements Iterator<E> {
		/**
		* cursor:
		* 集合遍历过程中的即将遍历的元素的索引
		* 
		* lastRet:
		* lastRet = -1,默认为-1,即不存在上一个时,为-1,它主要用于记录刚刚遍历过的元素的索引
		* 
		* expectedModCount:
		* 用于判断modCount和expectedModCount的值是否相等的其中一员份子,而初始值为ArrayList中的ModCount
		*/
		int cursor;
        int lastRet = -1;
        int expectedModCount = modCount;

        Itr() {}
        
	@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是抽象类AbstractList中的变量,默认为0,而ArrayList 继承了AbstractList ,所以也有这个变量,modCount用于记录集合操作过程中作的修改次数,与size还是有区别的,并不一定等于size

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

迭代器迭代结束的标志就是hasNext()返回false,而该方法就是用cursor和size(集合中的元素数目)进行对比,当cursor等于size时,表示已经遍历完成。如果有线程对集合结构做出改变,就会发生fail-fast!

	@SuppressWarnings("unchecked")
        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];
        }

可以看出迭代器在调用next()、remove()方法时都是调用checkForComodification()方法来进行检测modCount是否等于expectedModCount的。如果不等于的话就会抛出ConcurrentModificationException 异常,从而就会触发机制,发生fail-fast事件。

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

举例ArrayList中的方法remove
很多ArrayList的方法(比如:clear等操作方法)中都会存在modCount的改变,这就是为什么并发情况下,判断modCount是否等于expectedModCount时,会抛出异常的原因!

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

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

解决办法

  1. 在遍历过程中所有涉及到改变modCount值得地方全部加上synchronized或者直接使用Collections.synchronizedList,不过这个方法有很大的弊端!因为加了锁,每个线程进来的时候都会进入阻塞状态!=,所以效率很低!
  2. 直接使用CopyOnWriteArrayList来替换ArrayList是非常推荐的!因为CopyOnWriteArrayList是ArrayList的线程安全版本,CopyOnWriteArrayList是在有写操作的时候会copy一份数据,然后写完再设置成新的数据。如果想了解其原理的可以看一下这篇文章——CopyOnWriteArrayList是怎么实现写有锁,读无锁,读写之间不堵塞的?(加强版读写分离源码剖析)其核心的话就是Copy了,在改变数据的操作下(比如:add),CopyOnWriterArrayList都会copy现有的数据,再在copy的数据上修改,所以不会直接的造成内部数据的变化。这也是它线程安全的原因,更是解决安全失败机制的好办法!
发布了126 篇原创文章 · 获赞 217 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44170221/article/details/105028266