Java: How to atomically replace all values in a Map?

后端 未结 6 1289
忘了有多久
忘了有多久 2020-12-11 07:04

I have a stateful bean in an multi-threaded enviroment, which keeps its state in a map. Now I need a way to replace all values of that map in one atomic action.

         


        
6条回答
  •  心在旅途
    2020-12-11 07:14

    Since the map is quite small, it's probably enough to just use synchronized in all places you access it.

    private void atomicallyUpdateState(final Map newState) {
        synchronized(state) {
            state.clear();
            state.putAll(newState);
        }
    }
    

    but don't forget any, like all occurances of things like

    String myStatevalue = state.get("myValue");
    

    need to become

    String myStatevalue;
    synchronized (state) {
        myStatevalue = state.get("myValue");
    }
    

    otherwise the read and update are not synchronized and cause a race condition.

提交回复
热议问题