首页 > 解决方案 > ConcurrentHashMap 上的双重检查锁定是线程安全的吗?

问题描述

在许多情况下,在 Java 中实现双重检查锁定不是线程安全的(未同步的代码部分可以返回部分初始化的值)。但是,我使用双重检查锁定来检查一个值是否在 aConcurrentHashMap中,如果不是,则输入一个同步块,创建对象,然后put在映射中。这个线程安全吗?也就是说,putorget方法ConcurrentHashMap是否会添加或返回部分构造的值(或做一些其他意想不到的行为)?还是getandput方法是原子的,即成功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;
    }

    ...
}

标签: java

解决方案


推荐阅读