问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/38485630/locking-value-objects-of-a-concurrenthashmap