锁定ConcurrentHashMap的值对象 [英] Locking value objects of a ConcurrentHashMap
问题描述
在这篇文章中:
我们可以对每个条目使用Synchronized而不是ConcurrentHashMap吗?
我问我们是否可以使用Synchronized block来锁定HashMap的条目,我了解到我们不能。现在,我的问题是,如果我们有一个ConcurrentHashMap(不是hashMap),其值为ArrayList或TreeMap,那么我可以使用这种方法(使用synchronized)。这里我的意思是:
ConcurrentHashMap< String,ArrayList< String>> map = new ConcurrentHashMap<>();
同步(map.get(key)){
//对数组线程执行一些操作 - 安全,
}
安全吗?我问的原因是我不知道如何通过测试来检查这类问题。
只要您使用 putIfAbsent
操作,是线程安全的。您将始终在同一个对象引用上同步(阻止)。
In this post: Can we use Synchronized for each entry instead of ConcurrentHashMap?
I asked if we can use Synchronized block to lock only entries of a HashMap, which I learnt we cannot. Now, my question is, if we have a ConcurrentHashMap (not hashMap) with values of type ArrayList, or TreeMap, then can I use that approach (using synchronized). Here what I mean:
ConcurrentHashMap<String, ArrayList<String>> map = new ConcurrentHashMap<>();
synchronized (map.get("key")) {
//do something with the array thread-safely,
}
Is it safe? the reason that I am asking is that I don't know how to check this kind of issues by testing.
As long as you use the putIfAbsent
operation, then it will be thread-safe. You will always be synchronizing (blocking) on the same object reference.
这篇关于锁定ConcurrentHashMap的值对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!