Java荟萃进修(四) fail-fast总结
当前位置:以往代写 > JAVA 教程 >Java荟萃进修(四) fail-fast总结
2019-06-14

Java荟萃进修(四) fail-fast总结

Java荟萃进修(四) fail-fast总结

副标题#e#

 fail-fast总结(通过ArrayList来说明fail-fast的道理、办理步伐)

前面,我们已经进修了ArrayList。接下来,我们以ArrayList为例,对Iterator的fail-fast机制举办相识。

1 fail-fast简介

fail-fast 机制是java荟萃(Collection)中的一种错误机制。当多个线程对同一个荟萃的内容举办操纵时,就大概会发生fail-fast事件。
譬喻:当某一个线程A通过iterator去遍历某荟萃的进程中,若该荟萃的内容被其他线程所改变了;那么线程A会见集适时,就会抛出ConcurrentModificationException异常,发生fail-fast事件。

在具体先容fail-fast机制的道理之前,先通过一个示例来认识fail-fast。

2 fail-fast示例

示例代码:(FastFailTest.java)

import java.util.*;
import java.util.concurrent.*;
     
/*
 * @desc java荟萃中Fast-Fail的测试措施。
 *
 *   fast-fail事件发生的条件:当多个线程对Collection举办操纵时,若个中某一个线程通过iterator去遍历集适时,该荟萃的内容被其他线程所改变;则会抛出ConcurrentModificationException异常。
 *   fast-fail办理步伐:通过util.concurrent荟萃包下的相应类去处理惩罚,则不会发生fast-fail事件。
 *
 *   本例中,别离测试ArrayList和CopyOnWriteArrayList这两种环境。ArrayList会发生fast-fail事件,而CopyOnWriteArrayList不会发生fast-fail事件。
 *   (01) 利用ArrayList时,会发生fast-fail事件,抛出ConcurrentModificationException异常;界说如下:
 *            private static List<String> list = new ArrayList<String>();
 *   (02) 利用时CopyOnWriteArrayList,不会发生fast-fail事件;界说如下:
 *            private static List<String> list = new CopyOnWriteArrayList<String>();
 *
 * @author skywang
 */
public class FastFailTest {
     
    private static List<String> list = new ArrayList<String>();
    //private static List<String> list = new CopyOnWriteArrayList<String>();
    public static void main(String[] args) {
         
        // 同时启动两个线程对list举办操纵!
        new ThreadOne().start();
        new ThreadTwo().start();
    }
     
    private static void printAll() {
        System.out.println("");
     
        String value = null;
        Iterator iter = list.iterator();
        while(iter.hasNext()) {
            value = (String)iter.next();
            System.out.print(value+", ");
        }
    }
     
    /**
     * 向list中依次添加0,1,2,3,4,5,每添加一个数之后,就通过printAll()遍历整个list
     */
    private static class ThreadOne extends Thread {
        public void run() {
            int i = 0;
            while (i<6) {
                list.add(String.valueOf(i));
                printAll();
                i++;
            }
        }
    }
     
    /**
     * 向list中依次添加10,11,12,13,14,15,每添加一个数之后,就通过printAll()遍历整个list
     */
    private static class ThreadTwo extends Thread {
        public void run() {
            int i = 10;
            while (i<16) {
                list.add(String.valueOf(i));
                printAll();
                i++;
            }
        }
    }
     
}

运行功效:
运行该代码,抛出异常java.util.ConcurrentModificationException!即,发生fail-fast事件!

功效说明:
(01) FastFailTest中通过 new ThreadOne().start() 和 new ThreadTwo().start() 同时启动两个线程去操纵list。
   ThreadOne线程:向list中依次添加0,1,2,3,4,5。每添加一个数之后,就通过printAll()遍历整个list。
   ThreadTwo线程:向list中依次添加10,11,12,13,14,15。每添加一个数之后,就通过printAll()遍历整个list。
(02) 当某一个线程遍历list的进程中,list的内容被别的一个线程所改变了;就会抛出ConcurrentModificationException异常,发生fail-fast事件。

3 fail-fast办理步伐

fail-fast机制,是一种错误检测机制。它只能被用来检测错误,因为JDK并不担保fail-fast机制必然会产生。若在多线程情况下利用fail-fast机制的荟萃,发起利用“java.util.concurrent包下的类”去代替“java.util包下的类”。
所以,本例中只需要将ArrayList替换成java.util.concurrent包下对应的类即可。
即,将代码

private static List<String> list = new ArrayList<String>();

替换为

private static List<String> list = new CopyOnWriteArrayList<String>();

则可以办理该步伐。


#p#副标题#e#

4 fail-fast道理

发生fail-fast事件,是通过抛出ConcurrentModificationException异常来触发的。
那么,ArrayList是如何抛出ConcurrentModificationException异常的呢?

我们知道,ConcurrentModificationException是在操纵Iterator时抛出的异常。我们先看看Iterator的源码。ArrayList的Iterator是在父类AbstractList.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();
        }
    }
     
    ...
}

#p#分页标题#e#

从中,我们可以发此刻挪用 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;
    }
     
    ...
}

查察本栏目

#p#副标题#e#

从中,我们发明:无论是add()、remove(),照旧clear(),只要涉及到修改荟萃中的元素个数时,城市改变modCount的值。

#p#分页标题#e#

接下来,我们再系统的梳理一下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事件。

5 办理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();
        }
    }
       
    ...
     
}

从中,我们可以看出:

#p#分页标题#e#

(01) 和ArrayList担任于AbstractList差异,CopyOnWriteArrayList没有担任于AbstractList,它仅仅只是实现了List接口。
(02) ArrayList的iterator()函数返回的Iterator是在AbstractList中实现的;而CopyOnWriteArrayList是本身实现Iterator。
(03) ArrayList的Iterator实现类中挪用next()时,会“挪用checkForComodification()较量‘expectedModCount’和‘modCount’的巨细”;可是,CopyOnWriteArrayList的Iterator实现类中,没有所谓的checkForComodification(),更不会抛出ConcurrentModificationException异常!

    关键字:

在线提交作业