-
Notifications
You must be signed in to change notification settings - Fork 1.3k
HashMap 多线程操作导致死循环问题
cxuan edited this page Jun 15, 2020
·
1 revision
HashMap 不是一个线程安全的容器,在高并发场景下,应该使用 ConcurrentHashMap
,在多线程场景下使用 HashMap 会造成死循环问题(基于 JDK1.7),出现问题的位置在 rehash
处,也就是
do {
Entry<K,V> next = e.next; // <--假设线程一执行到这里就被调度挂起了
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
这是 JDK1.7 的 rehash 代码片段,在并发的场景下会形成环。
JDK1.8 也会造成死循环问题。