Java 并发hashmap是否不需要同步的getter/setter?

Java 并发hashmap是否不需要同步的getter/setter?,java,hashmap,concurrenthashmap,Java,Hashmap,Concurrenthashmap,如果我使用的是并发hashmap,并且我有设置和获取值的方法,就像我使用的是并发hashmap一样,那么我需要同步getter和setter吗?这是多余的吗?一种设计更好吗 另外,没有同步的并发hashmap是否比具有同步getter和setter的hashmap更快?这是一个高性能的系统 多谢各位 java.util.concurrent.ConcurrentHashMap是线程安全的 它比使用synchronized(对象) 您仍然需要小心,不要通过这样的代码创建“逻辑”竞争条件 if (m

如果我使用的是并发hashmap,并且我有设置和获取值的方法,就像我使用的是并发hashmap一样,那么我需要同步getter和setter吗?这是多余的吗?一种设计更好吗

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

多谢各位

  • java.util.concurrent.ConcurrentHashMap
    是线程安全的
  • 它比使用
    synchronized(对象)
  • 您仍然需要小心,不要通过这样的代码创建“逻辑”竞争条件

    if (map.get(key) != null) {
        map.put(key, new SomethingStrictlyUnique());
    }
    
  • 根据经验,用并发集合替换同步集合可以在风险很小的情况下提供显著的可伸缩性改进

  • 根据,ConcurrentHashMap返回的迭代器是“弱一致的”(而不是快速失效的),因此它们允许并发修改,遍历迭代器构造时存在的元素,并可能在迭代器构造后反映对集合的修改

  • 1) 如果您有只执行一个操作(比如get方法只返回给定键的map值)或任何线程安全操作的getter和setter方法,那么这些getter和setter不需要显式的同步块

    2) 是的,使用不带同步块的并发hashmap将大大提高性能


    注意:ConcurrentHashMap是弱一致的,在大多数情况下是可以接受的。

    您设置了什么?使用put和get设置值?或者为hashmap本身创建getter和setter?是的,我的方法包含put和get。