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操作。