集合框架 fail-fast机制(通过ArrayList来说明fail-fast的原理、解决办法)

第一部分:fail-fast简介

第二部分:fail-fast示例

第三部分:fail-fast解决方法

第四部分:fail-fast原理

第五部分:解决fail-fast的原理说明 

第一部分:fail-fast简介

 fail-fast机制是Java集合(collection)中的一种错误机制。当多个线程对同一个集合的内容(也就是数据)进行操作时,就可能会产生fail-fast事件出来。

eg:当线程A通过iterator去遍历某集合的过程中,若该集合的内让你搞被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。下面会有示例展示上述情况,更有助于理解fail-fast事件。

第二部分:fail-fast示例

示例代码:(FailFastTest)


/**
 * Created on 2019/8/24.
 * Title: Simple
 * Description:
 * Copyright: Copyright(c) 2019
 * Company: 
 *
 * @author wy
 */
public class FailFastTest {


    public static void main(String[] args) {
        List<String> list=new ArrayList<>();

        for (int i=1;i<10000;i++){
            list.add("fail-fast"+i);
        }


        new Thread(()->{
            for (String s:list){
                System.out.println(s);
            }
        }).start();
        new Thread(()->{
            try {
                Thread.sleep(10);
                list.add("fail-fast"+1001);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

第三部分:fail-fast解决办法

fail-fast机制,是一种错误检测机制。它只能被用来检测错误,因为JDK本身并不保证fail-fast机制一定会发生。若在多线程环境下,使用存在fail-fast机制(事件)的集合,其实从上述分析来讲,fail-fast机制只是一种检测机制,jdk本身在util包下的类中并没有解决这种问题,只是对错误进行检测而出现,所以在并发多线程场景下,建议使用java.util.concurrent包下的类去取代java.util*包下的类。

所以,在本例中呢只需要将arrayList替换成java.util.concurrent包下对应的类即可。
示例如下: 

/**
 * Created on 2019/8/24.
 * Title: Simple
 * Description:
 * Copyright: Copyright(c) 2019
 * Company:
 *
 * @author wy
 */
public class DealFailFastTest {


    public static void main(String[] args) {
        List<String> list=new CopyOnWriteArrayList<>();

        for (int i=1;i<=10000;i++){
            list.add("fail-fast==="+i);
        }
        new Thread(()->{
            for (String s:list){
                System.out.println(s);
            }
        }).start();
        new Thread(()->{
            try {
                Thread.sleep(10);
                list.add("fail-fast==="+10001);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}

由上述结论可知,concurrent包下就解决了异常这个问题,但是虽然新增了一条数据,但是其实获取到的还是添加之前的那个集合的数据,并没有捕获到异常,其实这种情况并不是线程不安全,数据污染的情况。jdk这个类解决了并发的情况下出现不安全以及数据污染的问题。

数据污染:是线程不安全造成的,后续章节会介绍到,在这一章节就不叙说太多了,举了例子吧:

eg:ArrayList在grow()方法的时候,在size++那一步线程A挂起了,线程B执行进来了,获取到了相同的size,这个时候线程A被唤醒去执行已经把值放在index索引处,线程B继续执行,这个时候,线程B的索引位置和线程A的index相同,这个时候,线程B会把线程A的替换掉,这种情况下就出现了数据污染。我的理解,如果是并行的情况,这种情况更容易存在,因为并行,两个线程互不抢占cpu资源,如果同时开始新的线程,同时执行,同时结束的话,必定会出现数据污染的情况,如果是并发情况存在,只是在这一步发生,才会出现数据污染的情况,当然并行和并发的话,都有可能会出现数据污染的情况,但是并不一定是每次运行都会出现。从官方的角度去讨论并发和并行,对于多核心CPU来讲,最后的效果,其实是很相似的,我的理解似乎可以理解为等同的。在这里又扯到了并发这一块,有点多余,只是刚才涉及到了一些就提了一下。

第四部分:fail-fast原理

产生fail-fast事件,是通过抛出ConcurrentModificationException异常来触发的。

那么Arraylist是如果抛出 ConcurrentModificationException异常的呢?

我们要了解到,ConcurrentModificationException是在Iterator操作时抛出的异常,下面我们就分析一下Iterator的源码,一探究竟。当然ArrayList的Iterator是在父类AbtractList.Java中实现的。代码如下所示:

package java.util;

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {


    // AbstractList中唯一的属性
    // 用来记录List修改的次数:每修改一次(添加/删除等操作),将modCount+1
    protected transient int modCount = 0;

    // 返回List对应迭代器。实际上,是返回Itr对象。
    public Iterator<E> iterator() {
        return new Itr();
    }

    // Itr是Iterator(迭代器)的实现类
    private class Itr implements Iterator<E> {
        int cursor = 0;

        int lastRet = -1;

        // 修改数的记录值。
        // 每次新建Itr()对象时,都会保存新建该对象时对应的modCount;
        // 以后每次遍历List中的元素的时候,都会比较expectedModCount和modCount是否相等;
        // 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
        int expectedModCount = modCount;

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

        public E next() {
            // 获取下一个元素之前,都会判断“新建Itr对象时保存的modCount”和“当前的modCount”是否相等;
            // 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
            checkForComodification();
            try {
                E next = get(cursor);
                lastRet = cursor++;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

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

    ...
}

从中,我们可以发现在调用 next() 和 remove()时,都会执行 checkForComodification()。若 “modCount 不等于 expectedModCount”,则抛出ConcurrentModificationException异常,产生fail-fast事件。

 要搞明白 fail-fast机制,我们就要需要理解什么时候“modCount 不等于 expectedModCount”
从Itr类中,我们知道 expectedModCount 在创建Itr对象时,被赋值为 modCount。通过Itr,我们知道:expectedModCount不可能被修改为不等于 modCount。所以,需要考证的就是modCount何时会被修改。

接下来,我们查看ArrayList的源码,来看看modCount是如何被修改的。

package java.util;

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    // list中容量变化时,对应的同步函数
    public void ensureCapacity(int minCapacity) {
        modCount++;
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }


    // 添加元素到队列最后
    public boolean add(E e) {
        // 修改modCount
        ensureCapacity(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }


    // 添加元素到指定的位置
    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(
            "Index: "+index+", Size: "+size);

        // 修改modCount
        ensureCapacity(size+1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
        elementData[index] = element;
        size++;
    }

    // 添加集合
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        // 修改modCount
        ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
   

    // 删除指定位置的元素 
    public E remove(int index) {
        RangeCheck(index);

        // 修改modCount
        modCount++;
        E oldValue = (E) elementData[index];

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }


    // 快速删除指定位置的元素 
    private void fastRemove(int index) {

        // 修改modCount
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }

    // 清空集合
    public void clear() {
        // 修改modCount
        modCount++;

        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
}

 从中,我们发现:无论是add()、remove(),还是clear(),只要涉及到修改集合中的元素个数时,都会改变modCount的值。

接下来,我们再系统的梳理一下fail-fast是怎么产生的。步骤如下:
(01) 新建了一个ArrayList,名称为arrayList。
(02) 向arrayList中添加内容。
(03) 新建一个“线程a”,并在“线程a”中通过Iterator反复的读取arrayList的值
(04) 新建一个“线程b”,在“线程b”中删除arrayList中的一个“节点A”。
(05) 这时,就会产生有趣的事件了。
       在某一时刻,“线程a”创建了arrayList的Iterator。此时“节点A”仍然存在于arrayList中,创建arrayList时,expectedModCount = modCount(假设它们此时的值为N)。
       在“线程a”在遍历arrayList过程中的某一时刻,“线程b”执行了,并且“线程b”删除了arrayList中的“节点A”。“线程b”执行remove()进行删除操作时,在remove()中执行了“modCount++”,此时modCount变成了N+1
“线程a”接着遍历,当它执行到next()函数时,调用checkForComodification()比较“expectedModCount”和“modCount”的大小;而“expectedModCount=N”,“modCount=N+1”,这样,便抛出ConcurrentModificationException异常,产生fail-fast事件。

至此,我们就完全了解了fail-fast是如何产生的!
即,当多个线程对同一个集合进行操作的时候,某线程访问集合的过程中,该集合的内容被其他线程所改变(即其它线程通过add、remove、clear等方法,改变了modCount的值);这时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。

第五部分:解决fail-fast的原理说明

上面,说明了“解决fail-fast机制的办法”,也知道了“fail-fast产生的根本原因”。接下来,我们再进一步谈谈java.util.concurrent包中是如何解决fail-fast事件的。
还是以和ArrayList对应的CopyOnWriteArrayList进行说明。我们先看看CopyOnWriteArrayList的源码:

源码如下:

package java.util.concurrent;
import java.util.*;
import java.util.concurrent.locks.*;
import sun.misc.Unsafe;

public class CopyOnWriteArrayList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {

    ...

    // 返回集合对应的迭代器
    public Iterator<E> iterator() {
        return new COWIterator<E>(getArray(), 0);
    }

    private static class COWIterator<E> implements ListIterator<E> {
        private final Object[] snapshot;

        private int cursor;

        private COWIterator(Object[] elements, int initialCursor) {
            cursor = initialCursor;
            // 新建COWIterator时,将集合中的元素保存到一个新的拷贝数组中。
            // 这样,当原始集合的数据改变,拷贝数据中的值也不会变化。
            snapshot = elements;
        }

        public boolean hasNext() {
            return cursor < snapshot.length;
        }

        public boolean hasPrevious() {
            return cursor > 0;
        }

        public E next() {
            if (! hasNext())
                throw new NoSuchElementException();
            return (E) snapshot[cursor++];
        }

        public E previous() {
            if (! hasPrevious())
                throw new NoSuchElementException();
            return (E) snapshot[--cursor];
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor-1;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        public void set(E e) {
            throw new UnsupportedOperationException();
        }

        public void add(E e) {
            throw new UnsupportedOperationException();
        }
    }

}

从中,我们可以看出:

(01) 和ArrayList继承于AbstractList不同,CopyOnWriteArrayList没有继承于AbstractList,它仅仅只是实现了List接口。
(02) ArrayList的iterator()函数返回的Iterator是在AbstractList中实现的;而CopyOnWriteArrayList是自己实现Iterator。
(03) ArrayList的Iterator实现类中调用next()时,会“调用checkForComodification()比较‘expectedModCount’和‘modCount’的大小”;但是,CopyOnWriteArrayList的Iterator实现类中,没有所谓的checkForComodification(),更不会抛出ConcurrentModificationException异常,最重要的原因是CopyOnWriteArrayList不会抛ConcurrentModificationException,是因为所有改变其内容的操作(add、remove、clear等),都会copy一份现有数据,在现有数据上修改好,在把原有数据的引用改成指向修改后的数据。而不是在读的时候copy。

周末也不能闲着啊,让自己充实起来,才有利于进步啊,有不对的地方或者不详细的地方小伙伴们指出哦,一起交流

猜你喜欢

转载自blog.csdn.net/crossroads10/article/details/100057428
今日推荐