首頁  >  文章  >  Java  >  java HashMap的不安全實例分析

java HashMap的不安全實例分析

WBOY
WBOY轉載
2023-05-25 21:46:04815瀏覽

原理分析

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.");
            }
        }
    }
}

以上是java HashMap的不安全實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除