Locking value objects of a ConcurrentHashMap

社会主义新天地 提交于 2019-12-24 07:36:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!