java - 调整大小时多线程环境中的 HashMap

标签 java hashmap

我正在学习一个教程,它基本上解释了在多线程环境中调整 Hashmap 大小时发生竞争条件的原因:

In Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during their migration to new bucket because java HashMap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop

读完后我有两个问题:

  1. 为什么每个桶的链表是按顺序颠倒的?
  2. 我可以看到可能存在竞争条件,但看不到无限循环是如何产生的?是不是因为一个线程可能将元素头追加到尾,而另一个线程以相反的顺序进行?

请帮我澄清一下,非常感谢!

最佳答案

第一个问题的答案在引用的文本中:

"because java HashMap doesn't append the new element at tail instead it append new element at head to avoid tail traversing"

如果 HashMap 要按插入顺序存储它们,则它必须在每次插入时遍历列表或存储指向列表末尾的额外指针(并维护它)。无论如何,按插入顺序将元素存储在桶中不会带来任何好处(至少我想不出有什么好处)。

第二个问题的答案在这里:

http://mailinator.blogspot.hu/2009/06/beautiful-race-condition.html

关于java - 调整大小时多线程环境中的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973896/

相关文章:

algorithm - 节点 s 的子树中值为 x 的节点数?

java - HashMap中Key的"Normalize"哈希值

java - 如何使用静态方法(不带异常)获取类的名称

java - 如何在 Java 运行时找到类的实例?

java - 是什么让 Hashmap.putIfAbsent 比 containsKey 后接 put 更快?

JAVA - 加速 HashMap 创建

java - 调用多个构造函数 - 只调用同一个构造函数?

java - 如何使用 Java 获取 XML 节点值?

7和8中的Java通配符区别

java - 如何遍历 Hashmap 并将其放入数组/列表结构中?