JDK1.8 ConcurrentHashMap的死循环bug

562 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

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