Java synchronized block vs. Collections.synchronizedMap

后端 未结 7 1877
天涯浪人
天涯浪人 2020-11-28 03:35

Is the following code set up to correctly synchronize the calls on synchronizedMap?

public class MyClass {
  private static Map

        
相关标签:
7条回答
  • 2020-11-28 04:10

    The way you have synchronized is correct. But there is a catch

    1. Synchronized wrapper provided by Collection framework ensures that the method calls I.e add/get/contains will run mutually exclusive.

    However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.

    1. You could have used a concurrent implementation of Map available in Collection framework. 'ConcurrentHashMap' benefit is

    a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.

    b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.

    c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.

    0 讨论(0)
提交回复
热议问题