Does a concurrent hashmap not require synchronized getters/setters?

后端 未结 2 676
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 15:14

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

2条回答
  •  盖世英雄少女心
    2021-01-19 15:25

    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.

提交回复
热议问题