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.
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.