java - ConcurrentHashMap 上的双重检查锁定是线程安全的吗?
问题描述
在许多情况下,在 Java 中实现双重检查锁定不是线程安全的(未同步的代码部分可以返回部分初始化的值)。但是,我使用双重检查锁定来检查一个值是否在 aConcurrentHashMap
中,如果不是,则输入一个同步块,创建对象,然后put
在映射中。这个线程安全吗?也就是说,put
orget
方法ConcurrentHashMap
是否会添加或返回部分构造的值(或做一些其他意想不到的行为)?还是get
andput
方法是原子的,即成功put
保证其他线程将看到放置在映射中的正确构造的对象?代码如下:
public class MyClass {
private static ConcurrentHashMap<KeyObject, SingletonObject> myConcurrentMap = new Concurrent...
...
private static SingletonValue getFromConcurrentMap(KeyObject key) {
SingletonValue singleton = this.myConcurrentHashMap.get(key);
if (singleton == null) {
synchronized (this.myConcurrentHashMap) {
singleton = this.myConcurrentHashMap.get(domainRuleBase);
if (singleton == null) {
singleton = SingletonValue.buildNewInstance();
this.myConcurrentHashMap.put(key, singleton);
}
}
}
return singleton;
}
...
}
解决方案
推荐阅读
- android - 创建重叠浮动动作底部
- sql - 在 SSMS Windows 身份验证方法中登录服务器时出错 ERROR: 18456
- swift - 使用手势后删除视图和移动内容
- macos - 无法设置名为 token 的环境变量
- node.js - “webpack”和“npx-webpack”命令在安装后不起作用
- reactjs - React useState 不使用 requestAnimationFrame 更新
- json - 如何自定义flask错误:JSON正文或post正文或查询字符串中缺少必填参数
- python - Boto3 发送批量电子邮件的方式,带有附件和下载链接
- android - Google play services 登录成功但抛出 ApiException: 8
- tensorflow - 访问在 tf.keras.layers.Layer 子类化中定义的层的输出