Java Map.computIfAbsent 死循环问题
先看一下代码
1 | Map<String, Integer> map = new HashMap<>(); |
输出:
{a=0}
如果使用 ConcurrentHashMap 呢
1 | Map<String, Integer> map = new ConcurrentHashMap<>(); |
输出:
死循环,不会输出
总结
- 在
computeIfAbsent里的remappingFunction里一定不要修改原 map,否则结果可能会不符合预期
ConcurrentHashMap 的 key 和 value 不能为 null