在JDK1.8版本中,ConcurrentHashMap中存在死循环bug,下面是bug重现代码:
package com.hiwe.demo.cache;
import java.util.concurrent.ConcurrentHashMap;
public class TestCache {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(16);
map.computeIfAbsent(
"AaAa",
key -> {
return map.computeIfAbsent(
"BBBB",
key2 -> 42);
}
);
System.out.println("程序完成");
}
}
执行以上代码,程序会进入死循环状态,导致CPU使用率暴涨。
bug原因:
因为"AaAa"和“BBBB”的hash值相同,会定位到用一个bucket中,这样就形成了CAS嵌套,产生死循环问题。具体的可以看源码分析。
解决:
禁止在向ConcurrentHashMap中嵌套执行computeIfAbsent/putIfAbsent操作。
本文介绍了JDK1.8中ConcurrentHashMap的一个潜在死循环bug,该bug发生在两个键的哈希值相同时,导致CAS嵌套循环。通过示例代码展示了问题的触发条件,并提出了解决方案,即避免在ConcurrentHashMap中嵌套使用computeIfAbsent或putIfAbsent操作,以防止CPU使用率异常升高。

1592

被折叠的 条评论
为什么被折叠?



