并发散列表不需要同步getter / setter? [英] Does a concurrent hashmap not require synchronized getters/setters?

查看:136
本文介绍了并发散列表不需要同步getter / setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用的是并发散列表,并且我有设置和获取值的方法,那么我需要使用并发散列表来使得getter和setter同步?这是多余的吗?一个设计更好吗?

另外,没有同步的并发hashmap比带同步getter和setter的hashmap快吗?这是一个高性能系统



谢谢

解决方案

    $ $ b $ li $ java.util.concurrent.ConcurrentHashMap 是线程安全的
  1. 它比使用 synchronized(object)

  2. 您仍然需要小心,不要像这样的代码创建逻辑竞争条件。 b
    $ b

      if(map.get(key)!= null){
    map.put(key,new SomethingStrictlyUnique());作为一个经验法则,用并发集合替换同步集合可以作为一个经验法则提供戏剧性的可扩展性改进,而且风险很小。 根据 javadoc ,ConcurrentHashMap返回的迭代器是弱一致的因此它们可以容忍并发修改,遍历构造迭代器时存在的元素,并且在构造迭代器后 可以反映对集合的修改。



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. 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.

这篇关于并发散列表不需要同步getter / setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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