建议使用的时候要避免key的hashcode重复,如果一样是会发生死循环的。
例子:
Map<String, Integer> map = new ConcurrentHashMap<>(16);
map.computeIfAbsent(
“AaAa”,
key -> {
return map.computeIfAbsent(
“BBBB”,
key2 -> 42);
}
);
先调用了 get 方法,如果返回为 null,则调用 putIfAbsent 方法,这样就能不会有问题了。
改:
if(map.get(“BBBB”)==null){
map.computeIfAbsent(
“BBBB”,
key2 -> 42);
}
map.computeIfAbsent( “AaAa”,
key -> {
return map.get(“BBBB”);
});
jdk 8 ConcurrentHashMap computeIfAbsent 里面也有死循环
最新推荐文章于 2025-11-17 10:35:45 发布
本文解释了在使用ConcurrentHashMap时,如何通过先检查并获取`key2`再进行`computeIfAbsent`操作来防止死循环,提供了一个示例代码的修改建议。

886

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



