ConcurrentHashMap vs ReentrantReadWriteLock based Custom Map for Reloading

后端 未结 3 640
无人及你
无人及你 2021-02-04 12:24

Java Gurus,

Currently we have a HashMap which is being read frequently and modified occasionally and w

3条回答
  •  我寻月下人不归
    2021-02-04 13:01

    It seems you are not sure as to how what Peter Lawrey suggests can be implemented. It could look like this:

    class YourClass {
        private volatile Map map;
    
        //constructors etc.
    
        public void reload() {
            Map newMap = getNewValues();
            map = Collections.unmodifiableMap(newMap);
        }
    }
    

    There are no concurrency issues because:

    • The new map is created via a local variable, which by definition is not shared - getNewValues does not need to be synchronized or atomic
    • The assignement to map is atomic
    • map is volatile, which guarantees that other threads will see the change

提交回复
热议问题