我是靠谱客的博主 幸福糖豆,这篇文章主要介绍安全失败(fail-safe)和 快速失败(fail-fast)前言安全失败(fail-safe)快速失败(fail-fast),现在分享给大家,希望可以做个参考。

java集合机制---- 安全失败(fail-safe)和 快速失败(fail-fast)

  • 前言
  • 安全失败(fail-safe)
    • 场景
    • 原理
  • 快速失败(fail-fast)
    • 场景
    • 原理

前言

刨根问底这是什么!原理是什么!日常编码中其实这个很少用到但是是一个很不错得机制。

安全失败(fail-safe)

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

场景

java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改。

原理

有的小伙伴们肯定有想知道为什么!是怎样一个原理在起作用,那么下面我们就来看看详细解答。
其原理大致如下:
由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发Concurrent Modification Exception。
下面展示一些 jdk1.8中的java.util.concurrent 包下面的源码 以ConcurrentHashMap为例子

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
final V putVal(K key, V value, boolean onlyIfAbsent) { //这里就是为什么ConcurrentHashMap 的key value 不能为null 重点 面试要考你 if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; //复制到新的集合里面在进行操作 这里就不过多介绍存取原理了 后面会单独再开一贴说这个事情 for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); else { V oldVal = null; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; }

快速失败(fail-fast)

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

场景

java.util包下的集合类都是快速失败的,不能在多线程下发生并发修改(迭代过程中被修改)算是一种安全机制吧。

原理

有的小伙伴们肯定有想知道为什么!是怎样一个原理在起作用,那么下面我们就来看看详细解答(我是复读机QAQ)
其原理大致如下:
迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。集合在被遍历期间如果内容发生变化,就会改变modCount的值。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。

ps:这个网上都有很多随便百度就出来了 ,那么有小伙伴会问我没看懂!下面我们来看看 1.8 中怎么实现得
下面展示一些 jdk1.8中的java.util 包下面的源码 以ArrayList为例子

复制代码
1
2
protected transient int modCount = 0;

在其父类AbstractList 类中定义了一个int 的变量 下面都是围绕这个变量来实现的,下面我们以add方法为例。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void add(E e) { // 基本上所有的操作都会先执行这个方法 checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; //这里操作完成后会重新赋值 expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }

让我们看看 checkForComodification 这个方法是干嘛的

复制代码
1
2
3
4
5
6
final void checkForComodification() { //都会检测modCount变量是否为expectedmodCount值 if (modCount != expectedModCount) throw new ConcurrentModificationException(); }

然后在遍历的时候同样是这个机制让我们来看看遍历的代码吧

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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]; }

这种机制也就应验了应用场景中不能在多线程下发生并发修改。

其他方法这里就不一一举例了有兴趣的小伙伴可以去看看源码一下就懂了。

最后

以上就是幸福糖豆最近收集整理的关于安全失败(fail-safe)和 快速失败(fail-fast)前言安全失败(fail-safe)快速失败(fail-fast)的全部内容,更多相关安全失败(fail-safe)和内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(84)

评论列表共有 0 条评论

立即
投稿
返回
顶部