Home  >  Article  >  Java  >  Analysis of unsafe instances of java HashMap

Analysis of unsafe instances of java HashMap

WBOY
WBOYforward
2023-05-25 21:46:04857browse

Principle Analysis

1. In HashMap, the put() method line code modCount is thread-unsafe at first glance.

2. The value obtained during the expansion process is inaccurate. The expansion of HashMap will create a new empty array and fill in the old items into the new array. If you retrieve the value at this time, you will get a null value. .

Example

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

The above is the detailed content of Analysis of unsafe instances of java HashMap. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete