Modifying hash map from a single thread and reading from multiple threads?

后端 未结 4 991
余生分开走
余生分开走 2021-01-06 01:15

I have a class in which I am populating a map liveSocketsByDatacenter from a single background thread every 30 seconds and then I have a method getNextSoc

4条回答
  •  情话喂你
    2021-01-06 02:00

    As you can read in detail e.g. here, if multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally to avoid an inconsistent view of the contents. So to be thread safe you should use either Java Collections synchronizedMap() method or a ConcurrentHashMap.

    //synchronizedMap
    private final Map> liveSocketsByDatacenter = Collections.synchronizedMap(new HashMap>());    
    

    or

    //ConcurrentHashMap
    private final Map> liveSocketsByDatacenter = new ConcurrentHashMap>();
    

    As you have very highly concurrent application modifying and reading key value in different threads, you should also have a look at the Producer-Consumer principle, e.g. here.

提交回复
热议问题