java HashMap的不安全实例分析
作者:WeekendFlower
时间:2023-05-01
浏览:2
原理分析1、在HashMap中,put()方法行代码modCount++,这个代码一看就是线程不安全。2、在扩展过程中取值不准确,HashMap的扩展将创建一个新空数组,并将旧的项目填入新的数组,如果此时去取值,则可以获得null值。实例publicclassHashMapNotSafe{publicstaticvoidmain(String[]args){finalMapmap=newHashMap();finalIntegertargetKey=65535;//65535finalStringtarg
本文目录
原理分析
1、在HashMap中,put()方法行代码modCount++,这个代码一看就是线程不安全。
2、在扩展过程中取值不准确,HashMap的扩展将创建一个新空数组,并将旧的项目填入新的数组,如果此时去取值,则可以获得null值。
实例
public class HashMapNotSafe {
public static void main(String[] args) {
final Map 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.");
}
}
}
}
作者最新文章
ArchiveofOurOwn官网链接及同人文学阅读入口
2026-10-30 10:21
多张照片怎么合成PDF文件?三种图片转PDF工具怎么选?
2026-10-29 15:06
音述AI作品如何复制分享链接发给好友
2026-10-27 12:00
冰点还原怎么打开 程序启动步骤
2026-10-23 13:35
keyshot怎么做爆炸图 零件展开步骤
2026-10-21 10:46
上一篇:
mysql如何查询最小值
下一篇:
java自带的四种线程池是什么
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































