gpt4 book ai didi

Java:如何原子地替换映射中的所有值?

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:36 24 4
gpt4 key购买 nike

我在多线程环境中有一个有状态 bean,它将其状态保存在映射中。现在我需要一种方法来在一个原子操作中替换该映射的所有值。

public final class StatefulBean {

private final Map<String, String> 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<String, String> 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<String, String> newState) {
//???
}
}

目前,我使用 ConcurrentSkipListMap 作为 ConcurrentMap 的实现,但这不是必需的。

我认为解决此问题的唯一方法是使全局状态 volatile 并完全替换 map 或使用AtomicReferenceFieldUpdater。有更好的办法吗?

我的更新非常频繁,每秒一次或两次,但机会只有很少的值。此外,整个 map 将只包含少于 20 个值。

最佳答案

采用 CAS 和 AtomicReference 的方法将在每次批量更新时复制 map 内容。

AtomicReference<Map<String, String>> workingMapRef = new AtomicReference<>(new HashMap<>());

此映射可以是并发的,但对于“批量更新”,它是只读的。然后在 updateState 中循环 doUpdateState() 直到得到 true,这意味着您的值已更新。

void updateState() {
while (!doUpdateState());
}

boolean doUpdateState() {
Map<String, String> workingMap = workingMapRef.get();
//copy map content
Map<String, String> 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);
}

关于Java:如何原子地替换映射中的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52011767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com