ConcurrentHashMap 陷入无限循环 - 为什么?

在深入分析的时候ConcurrentHashMap,发现网上有一篇博文说evenConcurrentHashMap可能会陷入死循环。


它给出了这个例子。当我运行这段代码时——它卡住了:


public class Test {

    public static void main(String[] args) throws Exception {

        Map<Long, Long> map = new ConcurrentHashMap<>();

        map.put(0L, 0L);

        map.put((1L << 32) + 1, 0L);

        for (long key : map.keySet()) {

            map.put(key, map.remove(key));

        }

    }

}

请解释为什么会出现这种僵局。


沧海一幻觉
浏览 280回答 5
5回答

UYOU

正如其他人已经说过的:这不是死锁,而是无限循环。不管怎样,问题的核心(和标题)是:为什么会这样?其他答案在这里没有详细介绍,但我也很想更好地理解这一点。例如,当您更改行map.put((1L&nbsp;<<&nbsp;32)&nbsp;+&nbsp;1,&nbsp;0L);到map.put(1L,&nbsp;0L);那么它就不会卡住。再一次,问题是为什么。答案是:很复杂。它是并发/集合框架中最复杂的类之一,代码高达 6300 行,其中 230 行注释仅解释了实现的ConcurrentHashMap基本概念,以及为什么神奇且难以阅读的代码实际有效。以下是相当简化的,但至少应该解释基本问题。首先:返回的集合Map::keySet是内部状态的视图。JavaDoc 说:返回此映射中包含的键的 Set 视图。该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。如果在对集合进行迭代时修改映射(除了通过迭代器自己的删除操作),迭代的结果是不确定的。&nbsp;该集支持删除元素,[...](本人强调)但是,JavaDocConcurrentHashMap::keySet说:返回此映射中包含的键的 Set 视图。该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。该集支持删除元素,[...](注意它没有提到未定义的行为!)通常,在遍历 时修改地图keySet会抛出一个ConcurrentModificationException.&nbsp;但是ConcurrentHashMap能够应付这个。它保持一致并且仍然可以迭代,即使结果可能仍然出乎意料 - 就像你的情况一样。得出您观察到的行为的原因:哈希表(或哈希映射)的工作原理基本上是根据键计算哈希值,并将该键用作应将条目添加到的“桶”的指示符。当多个key映射到同一个bucket时,bucket中的entries通常以链表的形式进行管理。的情况也是如此ConcurrentHashMap。以下程序在迭代和修改期间使用一些讨厌的反射黑客来打印表的内部状态 - 特别是表的“桶”,由节点组成:import java.lang.reflect.Array;import java.lang.reflect.Field;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class MapLoop{&nbsp; &nbsp; public static void main(String[] args) throws Exception&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; runTestInfinite();&nbsp; &nbsp; &nbsp; &nbsp; runTestFinite();&nbsp; &nbsp; }&nbsp; &nbsp; private static void runTestInfinite() throws Exception&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Running test with inifinite loop");&nbsp; &nbsp; &nbsp; &nbsp; Map<Long, Long> map = new ConcurrentHashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; map.put(0L, 0L);&nbsp; &nbsp; &nbsp; &nbsp; map.put((1L << 32) + 1, 0L);&nbsp; &nbsp; &nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (long key : map.keySet())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(key, map.remove(key));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Infinite, counter is "+counter);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printTable(map);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (counter == 10)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Bailing out...");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Running test with inifinite loop DONE");&nbsp; &nbsp; }&nbsp; &nbsp; private static void runTestFinite() throws Exception&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Running test with finite loop");&nbsp; &nbsp; &nbsp; &nbsp; Map<Long, Long> map = new ConcurrentHashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; map.put(0L, 0L);&nbsp; &nbsp; &nbsp; &nbsp; map.put(1L, 0L);&nbsp; &nbsp; &nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (long key : map.keySet())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(key, map.remove(key));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Finite, counter is "+counter);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printTable(map);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Running test with finite loop DONE");&nbsp; &nbsp; }&nbsp; &nbsp; private static void printTable(Map<Long, Long> map) throws Exception&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Hack, to illustrate the issue here:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Table now: ");&nbsp; &nbsp; &nbsp; &nbsp; Field fTable = ConcurrentHashMap.class.getDeclaredField("table");&nbsp; &nbsp; &nbsp; &nbsp; fTable.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; Object t = fTable.get(map);&nbsp; &nbsp; &nbsp; &nbsp; int n = Array.getLength(t);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < n; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object node = Array.get(t, i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printNode(i, node);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private static void printNode(int index, Object node) throws Exception&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (node == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("at " + index + ": null");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Hack, to illustrate the issue here:&nbsp; &nbsp; &nbsp; &nbsp; Class<?> c =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class.forName("java.util.concurrent.ConcurrentHashMap$Node");&nbsp; &nbsp; &nbsp; &nbsp; Field fHash = c.getDeclaredField("hash");&nbsp; &nbsp; &nbsp; &nbsp; fHash.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; Field fKey = c.getDeclaredField("key");&nbsp; &nbsp; &nbsp; &nbsp; fKey.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; Field fVal = c.getDeclaredField("val");&nbsp; &nbsp; &nbsp; &nbsp; fVal.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; Field fNext = c.getDeclaredField("next");&nbsp; &nbsp; &nbsp; &nbsp; fNext.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("&nbsp; at " + index + ":");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("&nbsp; &nbsp; hash " + fHash.getInt(node));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("&nbsp; &nbsp; key&nbsp; " + fKey.get(node));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("&nbsp; &nbsp; val&nbsp; " + fVal.get(node));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("&nbsp; &nbsp; next " + fNext.get(node));&nbsp; &nbsp; }}该runTestInfinite案例的输出如下(省略多余部分):Running test with infinite loopInfinite, counter is 0Table now:&nbsp;&nbsp; at 0:&nbsp; &nbsp; hash 0&nbsp; &nbsp; key&nbsp; 4294967297&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next 0=0at 1: nullat 2: null...at 14: nullat 15: nullInfinite, counter is 1Table now:&nbsp;&nbsp; at 0:&nbsp; &nbsp; hash 0&nbsp; &nbsp; key&nbsp; 0&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next 4294967297=0at 1: nullat 2: null...at 14: nullat 15: nullInfinite, counter is 2Table now:&nbsp;&nbsp; at 0:&nbsp; &nbsp; hash 0&nbsp; &nbsp; key&nbsp; 4294967297&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next 0=0at 1: nullat 2: null...at 14: nullat 15: nullInfinite, counter is 3...Infinite, counter is 9...Bailing out...Running test with infinite loop DONE0可以看到 key和 key 4294967297(你的)的条目(1L << 32) + 1总是以 bucket 0 结尾,并且它们被维护为一个链表。所以迭代从keySet这张表开始:Bucket&nbsp; &nbsp;:&nbsp; &nbsp;Contents&nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;0 --> 4294967297&nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null&nbsp; ...&nbsp; &nbsp; :&nbsp; &nbsp;...&nbsp; 15&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null在第一次迭代中,它删除了 key 0,基本上将表变成了这个:Bucket&nbsp; &nbsp;:&nbsp; &nbsp;Contents&nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;4294967297&nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null&nbsp; ...&nbsp; &nbsp; :&nbsp; &nbsp;...&nbsp; 15&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null但是之后会立即添加密钥0,并且它在与 - 相同的存储桶中结束,4294967297因此它被附加在列表的末尾:Bucket&nbsp; &nbsp;:&nbsp; &nbsp;Contents&nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;4294967297 -> 0&nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null&nbsp; ...&nbsp; &nbsp; :&nbsp; &nbsp;...&nbsp; 15&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;null(这由next 0=0输出的一部分指示)。在下一次迭代中,4294967297删除并重新插入,使表恢复到最初的状态。这就是你的无限循环的来源。与此相反,案例的输出runTestFinite是这样的:Running test with finite loopFinite, counter is 0Table now:&nbsp;&nbsp; at 0:&nbsp; &nbsp; hash 0&nbsp; &nbsp; key&nbsp; 0&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next null&nbsp; at 1:&nbsp; &nbsp; hash 1&nbsp; &nbsp; key&nbsp; 1&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next nullat 2: null...at 14: nullat 15: nullFinite, counter is 1Table now:&nbsp;&nbsp; at 0:&nbsp; &nbsp; hash 0&nbsp; &nbsp; key&nbsp; 0&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next null&nbsp; at 1:&nbsp; &nbsp; hash 1&nbsp; &nbsp; key&nbsp; 1&nbsp; &nbsp; val&nbsp; 0&nbsp; &nbsp; next nullat 2: null...at 14: nullat 15: nullRunning test with finite loop DONE可以看到密钥0最终1位于不同的桶中。因此,不存在可以追加删除(和添加)元素的链表,循环在遍历相关元素(即前两个桶)一次后终止。

慕勒3428872

没有僵局。您只是陷入了无限循环。key当我运行这段代码(并在循环中打印)时,控制台反复显示:04294967297042949672970...如果你创建了map一个HashMap实例,你会看到代码引发了一个ConcurrentModificationException. 所以你只是在修改映射的同时遍历它的键,并且ConcurrentHashMap不会抛出并发修改异常,从而使你的循环无休止。

慕莱坞森

我不认为这与提供的线程安全有任何关系ConcurrentHashMap。它甚至看起来根本不像死锁,而是一个无限循环。这是由于映射在迭代键集时被修改,键集由同一个映射支持!以下是文档的摘录map.keySet():该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。如果在对集合进行迭代时修改映射(通过迭代器自己的删除操作除外),则迭代的结果是不确定的。

浮云间

无限循环的原因是以下因素的组合地图条目如何在内部存储密钥迭代器如何工作1个映射条目存储为一个链表数组:transient volatile Node<K,V>[] table每个映射条目都将基于其 hash() 结束于该数组中的一个链表中hash % table.length://simplified pseudocodepublic V put(K key, V value) {&nbsp; &nbsp; int hash = computeHash(key) % table.length&nbsp; &nbsp; Node<K,V> linkedList = table[hash]&nbsp; &nbsp; linkedList.add(new Node(key, value))}具有相同散列值的 2 个键(如 0 和 4294967297)将出现在同一个列表中2个迭代器的工作非常简单:一个接一个地迭代条目。鉴于内部存储基本上是集合的集合,它遍历table[0]列表中的所有条目,等等table[1]。但是有一个实现细节使我们的示例仅针对具有哈希冲突的映射永远运行:public final K next() {&nbsp; &nbsp; Node<K,V> p;&nbsp; &nbsp; &nbsp;if ((p = next) == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new NoSuchElementException();&nbsp; &nbsp; &nbsp;K k = p.key;&nbsp; &nbsp; &nbsp;lastReturned = p;&nbsp; &nbsp; &nbsp;advance();&nbsp; &nbsp; &nbsp;return k;}next ()方法实现返回一个之前预先计算的值,并计算要在将来调用时返回的值。当迭代器被实例化时,它收集第一个元素,当next()第一次被调用时,它收集第二个元素并返回第一个。这是该方法的相关代码advance():Node<K,V>[] tab;&nbsp; &nbsp; &nbsp; &nbsp; // current table; updated if resizedNode<K,V> next;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// the next entry to use. . .final Node<K,V> advance() {&nbsp; &nbsp; Node<K,V> e;&nbsp; &nbsp; if ((e = next) != null)&nbsp; &nbsp; &nbsp; &nbsp; e = e.next;&nbsp; &nbsp; for (;;) {&nbsp; &nbsp; &nbsp; &nbsp; Node<K,V>[] t; int i, n;&nbsp; &nbsp; &nbsp; &nbsp; if (e != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return next = e; // our example will always return here&nbsp; &nbsp; &nbsp; &nbsp; . . .&nbsp; &nbsp; }}以下是我们地图的内部状态是如何演变的:Map<Long, Long> map = new ConcurrentHashMap<>();[ null, null, ... , null ]所有桶(链表)都是空的map.put(0L, 0L);[ 0:0, null, ... , null ]第一个桶有一个条目map.put((1L << 32) + 1, 0L);[ 0:0 -> 4294967297:0, null, ... , null ]第一个桶现在有两个条目第一次迭代,迭代器返回0并将4294967297:0条目保存为nextmap.remove(0)[ 4294967297:0, null, ... , null ]map.put(0, 0) // the entry our iterator holds has its next pointer modified[ 4294967297:0 -> 0:0, null, ... , null ]第二次迭代map.remove(4294967297)[ 0:0, null, ... , null ]map.put(4294967297, 0)[ 0:0 -> 4294967297:0, null, ... , null ]所以在 2 次迭代之后我们回到了开始的位置,因为我们的操作归结为从链表的头部删除一个项目并将其添加到它的尾部,因此我们无法完成消费。对于没有散列冲突的映射,它不会陷入无限循环,因为我们添加的链表已经被迭代器留下了。这是一个证明它的例子:Map<Long, Long> map = new ConcurrentHashMap<>();map.put(0L, 0L);map.put(1L, 0L);int iteration = 0;for (long key : map.keySet()) {&nbsp; &nbsp; map.put((1L << 32) + 1, 0L);&nbsp; &nbsp; map.put((1L << 33) + 2, 0L);&nbsp; &nbsp; map.put((1L << 34) + 4, 0L);&nbsp; &nbsp; System.out.printf("iteration:%d key:%d&nbsp; map size:%d %n", ++iteration, key, map.size());&nbsp; &nbsp; map.put(key, map.remove(key));}输出是:iteration:1 key:0&nbsp; map size:5iteration:2 key:1&nbsp; map size:5在循环中添加的所有项目最终都在同一个桶中 - 第一个 - 我们的迭代器已经消耗的那个。

吃鸡游戏

没有死锁。死锁是当两个(或更多)线程互相阻塞时。很明显,你这里只有一个主线程。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java