java - 如何线程安全更新 loadingcache 值番石榴图
问题描述
为了测试,在 addCache 方法中,我创建并添加了一个地图。该卡具有键“a”和值“1111”。LoadingCache 的键“b”。
接下来,我想将值“1111”更新为值“2222”。为此,我从 main 方法中传递了所有必要的参数以查找值“1111”。
如何以线程安全的方式将“1111”更新为“2222”?
public class TestCache {
private LoadingCache<String, Map<String, String>> attemptsCache;
public TestCache() {
attemptsCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(1, TimeUnit.HOURS)
.build(new CacheLoader<String, Map<String, String>>() {
@Override
public Map<String, String> load(@Nonnull final String key) {
return Map.of();
}
});
}
public void addCache(final String pathKey, final String inputKey, final String nameValue) {
Map<String, String> map = new HashMap<>();
map.put("a", "1111");
attemptsCache.put("b", map);
// Next, you need to update the map value
}
public static void main(String[] args) throws ExecutionException {
new TestCache().addCache("b","a","2222");
}
}
解决方案
对于该特定场景,您只需调用put
,这会进行线程安全更新。对 Cache 的单独修改始终是线程安全的。
推荐阅读
- javascript - React:单击按钮后重新渲染组件
- r - R Shiny - updateSelectizeInput 与观察者的意外行为
- vhdl - 在 VHDL 中将 3D RAM 合成为 BRAM 阵列
- python - 无法覆盖 Odoo 13 上的写入方法
- typescript - why is extends keys T not a valid index
- ios - 如何使用查看更多按钮在表格视图中制作水平集合视图
- sql - Service Broker/数据库镜像传输连接端点发生错误,错误:8474,状态
- python - 如何在 mongo 查询中找到最新记录?
- angular - 大理石测试可观察到在方法调用后发生变化?
- sql - 我如何在 postgres 中加入 2 个单独的连接?