
原理分析
1、在HashMap中,put()方法行代码modCount++,这个代码一看就是线程不安全。
2、在扩展过程中取值不准确,HashMap的扩展将创建一个新空数组,并将旧的项目填入新的数组,如果此时去取值,则可以获得null值。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class HashMapNotSafe {
public static void main(String[] args) {
final Map<Integer, String> map = new HashMap<>();
final Integer targetKey = 65535;
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的不安全分析,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。