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

Analysis of unsafe instances of java HashMap

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-05-25 21:46:04
forward
932 people have browsed it

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

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template