使用ConcurrentHashMap,什么时候需要同步? [英] Using ConcurrentHashMap, when is synchronizing necessary?

查看:362
本文介绍了使用ConcurrentHashMap,什么时候需要同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ConcurrentHashMap,其中我执行以下操作:

I have a ConcurrentHashMap where i do the following:

sequences = new ConcurrentHashMap<Class<?>, AtomicLong>();

if(!sequences.containsKey(table)) {
    synchronized (sequences) {
        if(!sequences.containsKey(table))
            initializeHashMapKeyValue(table);
    }
}

我的问题是 -

if(!sequences.containsKey(table))

检查同步块中的内容,以便其他线程不会初始化相同的hashmap值?

Check inside the synschronized block so other threads wont initialize the same hashmap value?

也许需要检查,我做错了吗?

Maybe the check is necessary and I am doing it wrong? It seems a bit silly what I'm doing, but i think it is necessary.

推荐答案

全部对ConcurrentHashMap的操作是线程安全的,但线程安全操作是不可组合的。你试图使原子的一对操作:检查在地图中的东西,如果它不存在,把东西放在那里(我假设)。因此,您的问题的答案是,您需要再次检查,您的代码看起来确定。

All operations on a ConcurrentHashMap are thread-safe, but thread-safe operations are not composable. You trying to make atomic a pair of operations: checking for something in the map and, in case it's not there, put something there (I assume). So the answer to your questions is yes, you need to check again, and your code looks ok.

这篇关于使用ConcurrentHashMap,什么时候需要同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆