Is it possible to use hashmap synchronized getters / setters at the same time?

If I used a parallel hashmap and I had methods that set and receive values, since im using a simultaneous hashmap would I need to synchronize the getter and setter? Is this redundant? Is one design better?

Also, is a simultaneous hash card without sync faster than a hash card with synchronized getters and setters? This is for a high performance system.

thanks

+4
source share
2 answers
  • java.util.concurrent.ConcurrentHashMap is thread safe.
  • This is faster than using synchronized(object)
  • You still need to be careful not to create a “logical” race condition with a code like this

     if (map.get(key) != null) { map.put(key, new SomethingStrictlyUnique()); } 
  • Generally, replacing synchronized collections with concurrent collections can provide significant scalability improvements with little risk.

  • According to javadoc , the iterators returned by ConcurrentHashMap are “weakly matched” (instead of fast and fast), so they suffer simultaneous modification, intersection elements, as they existed when constructing the iterator, and may reflect changes in the collection after constructing the iterator.

+7
source

1) If you have getter and setter methods that perform only one operation (for example, the get method returns only the map value for a given key) or any thread-safe operation, then you do not need an explicit synchronized block for those getters and setters.

2) Yes, using a simultaneous hash card without a synchronized block will significantly improve performance.

Note. ConcurrentHashMap is poorly consistent, which is acceptable in most cases.

+1
source

Source: https://habr.com/ru/post/1335674/


All Articles