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.");
}
}
}
}
作者最新文章
微信PC版登录失败怎么解决
2026-11-25 12:18
电脑微信多账号登录方法详解
2026-11-25 12:18
微信电脑版怎么看好友朋友圈-微信电脑版看好友朋友圈的方法
2026-11-25 12:18
微信电脑版如何用读书功能
2026-11-25 12:18
没带手机微信电脑版怎么登陆 微信电脑版无手机登录解决办法
2026-11-25 12:18
上一篇:
mysql如何查询最小值
下一篇:
java自带的四种线程池是什么
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































