How to refresh HashMap while clients read from it

后端 未结 3 998
误落风尘
误落风尘 2021-01-27 09:12

I have a static HashMap that is initialized on server startup. Clients initialize their data from this map when they login.
Now I need to refresh this map, but

3条回答
  •  有刺的猬
    2021-01-27 10:00

    First of all your map needs to be declared as volatile in order to ensure that each thread has the last version of it, then here is how you could proceed:

    public void refresh() {
        synchronized (MyClass.class) {
            Map newMap = prepareData();
            map = Collections.unmodifiableMap(newMap);
        }
    }
    

    And your map would be declared as below:

    private static volatile Map map = ...
    

提交回复
热议问题