Does a concurrent hashmap not require synchronized getters/setters?

走远了吗. 提交于 2019-12-01 21:26:39

问题


If i was using a concurrent hashmap and i had methods which set and got values, as im using a concurrent hashmap would i need to make the getter and setter synchronized? Is this redundant? Is one design better?

Also, is a concurrent hashmap without synchronization faster than a hashmap with synchronized getters and setters? This is for a high performance system

Thank you


回答1:


  1. java.util.concurrent.ConcurrentHashMap is thread safe
  2. It is faster than using synchronized(object)
  3. You still need to be careful not to create a "logical" race condition by code like this

    if (map.get(key) != null) {
        map.put(key, new SomethingStrictlyUnique());
    }
    
  4. As a rule of thumb, replacing synchronized collections with concurrent collections can offer dramatic scalability improvements with little risks.

  5. According to the javadoc, iterators returned by ConcurrentHashMap are "weakly consistent" (instead of fail-fast), so they tolerate concurrent modification, traverse elements as they existed when the iterator was constructed, and may reflect modifications to the collection after the construction of the iterator.




回答2:


1) If you've getter & setter methods which does only one operation (like get method will only return the map value for the given key) or any thread-safe operation, then you don't need an explicit synchronized block for those getter & setter.

2) Yes, using concurrent hashmap without synchronized block will greatly improve performance.

Note : ConcurrentHashMap is weakly consistent which is acceptable in most cases.



来源:https://stackoverflow.com/questions/4701261/does-a-concurrent-hashmap-not-require-synchronized-getters-setters

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