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.");
}
}
}
}
作者最新文章
再漫画官网首页入口及在线观看方法
2026-11-05 09:42
ArchiveofOurOwn官网链接及同人文学阅读入口
2026-10-30 10:21
多张照片怎么合成PDF文件?三种图片转PDF工具怎么选?
2026-10-29 15:06
音述AI作品如何复制分享链接发给好友
2026-10-27 12:00
冰点还原怎么打开 程序启动步骤
2026-10-23 13:35
上一篇:
mysql如何查询最小值
下一篇:
java自带的四种线程池是什么
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















