前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >面试官来了:讲讲快速失败和安全失败的区别?

面试官来了:讲讲快速失败和安全失败的区别?

作者头像
后台技术汇
发布2022-05-28 13:06:54
3270
发布2022-05-28 13:06:54
举报
文章被收录于专栏:后台技术汇

Java 的 Fail-fast 和 Safe-fast 有什么区别?

快速失败& 安全失败

【快速失败】

在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出Concurrent Modification Exception。

  1. 原理:迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。集合在被遍历期间如果内容发生变化,就会改变modCount的值。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。
  2. 注意:这里异常的抛出条件是检测到 (modCount!=expectedmodCount) 这个条件。如果集合发生变化时修改modCount值刚好又设置为了expectedmodCount值,则异常不会抛出。因此,不能依赖于这个异常是否抛出而进行并发操作的编程,这个异常只建议用于检测并发修改的bug。
  3. 场景:java.util包下的集合类都是快速失败的,不能在多线程下发生并发修改(迭代过程中被修改)

【安全失败】

采用安全失败机制的集合容器,在遍历时不是直接在集合内容上访问的,而是先复制原有集合内容,在拷贝的集合上进行遍历。

  1. 原理:由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发Concurrent Modification Exception。
  2. 缺点:基于拷贝内容的优点是避免了Concurrent Modification Exception,但同样地,迭代器并不能访问到修改后的内容,即:迭代器遍历的是开始遍历那一刻拿到的集合拷贝,在遍历期间原集合发生的修改迭代器是不知道的。
  3. 场景:java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改

ConcurrentModificationException

我们看下 ConcurrentModificationException 源码:

  • ConcurrentModificationException 属于运行时异常;
  • 注释清楚写明白了:此异常可能由检测到并发的方法引发,因为该对象的修改不被允许。而可能引发这种异常的对象,则可能来源于以下的工具类: Collection,Iterator,Spliterator,ListIterator,Vector, LinkedList,HashSet,Hashtable,TreeMap,AbstractList等。
代码语言:javascript
复制

/**
 * This exception may be thrown by methods that have detected concurrent
 * modification of an object when such modification is not permissible.
 * @author  Josh Bloch
 * @see     Collection
 * @see     Iterator
 * @see     Spliterator
 * @see     ListIterator
 * @see     Vector
 * @see     LinkedList
 * @see     HashSet
 * @see     Hashtable
 * @see     TreeMap
 * @see     AbstractList
 * @since   1.2
 */
public class ConcurrentModificationException extends RuntimeException {
    private static final long serialVersionUID = -3666751008965953603L;
    public ConcurrentModificationException() {
    }
    public ConcurrentModificationException(String message) {
        super(message);
    }
    public ConcurrentModificationException(Throwable cause) {
        super(cause);
    }
    public ConcurrentModificationException(String message, Throwable cause) {
        super(message, cause);
    }
}

源码案例

ArrayList & Vector

ArrayList 本质是一个对象数组,是非线程安全的容器;

而 Vector 则是该容器的线程安全版本,它的线程安全策略是:在 的开放api基础上,都加上了互斥锁 -- synchronized,使得对容器的任何操作都串行化执行。

我们都知道,序列化不会自动保存static和transient变量,因此我们若要保存它们,则需要通过writeObject()和readObject()去手动读写,所以通过writeObject()方法,写入要保存的变量。

ArrayList的私有方法writeObject(快速失败)

代码语言:javascript
复制
  /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
   
    /**
     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
     * is, serialize it).
     *
     * @serialData The length of the array backing the <tt>ArrayList</tt>
     *             instance is emitted (int), followed by all of its elements
     *             (each an <tt>Object</tt>) in the proper order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();
        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);
        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

代码分析

我们走读这个代码段,在方法的末尾处有个 (modCount != expectedModCount) 判断。条件满足,则抛出了 ConcurrentModificationException 异常。

Vector的私有方法writeObject(安全失败)

我们走读下 Vector 的

writeObject(java.io.ObjectOutputStream s) 方法:

代码语言:javascript
复制
   /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     */
    protected Object[] elementData;
    /**
     * Save the state of the {@code Vector} instance to a stream (that
     * is, serialize it).
     * This method performs synchronization to ensure the consistency
     * of the serialized data.
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

代码分析

我们走读这个代码段,发现了在将容器数据传递给输出流ObjectOutputStream时,使用了 synchronized 锁住了一个代码块。这个代码块的内容呢,就是将容器的数据克隆一份到临时内存,最后写入到输出流;整个过程并不影响原来容器的数据 elementData 的任何属性(只读),因此达到安全失败的要求。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-02-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 后台技术汇 微信公众号,前往查看

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

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Java 的 Fail-fast 和 Safe-fast 有什么区别?
  • ConcurrentModificationException
  • 源码案例
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档