我在多线程环境中有一个有状态bean,它将状态保存在地图中.现在我需要一种方法来在一个原子动作中替换该映射的所有值.
public final class StatefulBean {
private final Map state = new ConcurrentSkipListMap<>();
public StatefulBean() {
//Initial state
this.state.put("a", "a1");
this.state.put("b", "b1");
this.state.put("c", "c1");
}
public void updateState() {
//Fake computation of new state
final Map newState = new HashMap<>();
newState.put("b", "b1");
newState.put("c", "c2");
newState.put("d", "d1");
atomicallyUpdateState(newState);
/*Expected result
* a: removed
* b: unchanged
* C: replaced
* d: added*/
}
private void atomicallyUpdateState(final Map newState) {
//???
}
}
目前我使用ConcurrentSkipListMap作为ConcurrentMap的实现,但这不是必需的.
我看到解决此问题的唯一方法是使全局状态变为volatile并完全替换映射或使用AtomicReferenceFieldUpdater.
有没有更好的办法?
我的更新非常频繁,每秒一次或两次,但只有很少的值.此外,整个地图只包含少于20个值.