【发布时间】:2021-10-01 05:15:22
【问题描述】:
为了测试,在 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?
-
@Louis Wasserman 我不知道,也许吧。我只是问问。