商城首页欢迎来到中国正版软件门户

您的位置:首页 >java HashMap的不安全实例分析

java HashMap的不安全实例分析

  发布于2023-05-01 阅读(0)

扫一扫,手机访问

原理分析

1、在HashMap中,put()方法行代码modCount++,这个代码一看就是线程不安全。

2、在扩展过程中取值不准确,HashMap的扩展将创建一个新空数组,并将旧的项目填入新的数组,如果此时去取值,则可以获得null值。

实例

public class HashMapNotSafe {
 
    public static void main(String[] args) {
        final Map<Integer, String> map = new HashMap<>();
 
        final Integer targetKey = 65535; // 65 535
        final String targetValue = "v";
        map.put(targetKey, targetValue);
 
        new Thread(() -> {
            IntStream.range(0, targetKey).forEach(key -> map.put(key, "someValue"));
        }).start();
 
        while (true) {
            if (null == map.get(targetKey)) {
                throw new RuntimeException("HashMap is not thread safe.");
            }
        }
    }
}
本文转载于:https://www.yisu.com/zixun/581660.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注