java referencemap,Java:如何以原子方式替换Map中的所有值?

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.

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) {

//???

}

}

At the moment I use ConcurrentSkipListMap as implementation of a ConcurrentMap, but that isn't a requirement.

The only way I see to solve this problem is to make the global state volatile and completely replace the map or use a AtomicReferenceFieldUpdater.

Is there a better way?

My updates are quite frequent, once or twice a second, but chance only very few values. Also the whole map will only ever contain fewer than 20 values.

解决方案

Approach with CAS and AtomicReference would be to copy map content on each bulk update.

AtomicReference> workingMapRef = new AtomicReference<>(new HashMap<>());

This map can be concurrent, but for "bulk updates" it is read-only. Then in updateState looping doUpdateState() until you get true and that means that your values has been updated.

void updateState() {

while (!doUpdateState());

}

boolean doUpdateState() {

Map workingMap = workingMapRef.get();

//copy map content

Map newState = new HashMap<>(workingMap); //you can make it concurrent

newState.put("b", "b1");

newState.put("c", "c2");

newState.put("d", "d1");

return workingMapRef.compareAndSet(workingMap, newState);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值