Reputation: 4245
The cache holdes a map that frequently changed in both local and backend. I uses AtomicLong as the map value type. When I want to change the value in the cached map, I did this below
private static final LoadingCache<String, Map<Integer, AtomicLong>> NWZs = CacheBuilder.newBuilder()
private void incNWZ(String word, Integer topic, int delta) throws ExecutionException {
Map<Integer, AtomicLong> wincm = NWZs.get(word);
if (!wincm.containsKey(topic)) {
wincm.put(topic, new AtomicLong(0));
}
wincm.get(topic).addAndGet(delta);
}
My question is if I called incNWZ
, will the value in cache changed when next time it read out?
Upvotes: 0
Views: 460
Reputation: 46472
It will, assuming that
wincm
not present in the cacheMap
you modified won't get evicted and reloaded againI guess the second case is OK as I hope you modify both the cached value and the original data in place they come from. But there are funny gotchas like
or the other way round
Upvotes: 1
Reputation: 4245
The following code shows then it will work
private static final LoadingCache<String, Map<Integer, AtomicLong>> NWZs = CacheBuilder.newBuilder()
.weakKeys()
.weakValues()
.expireAfterWrite(60, TimeUnit.MINUTES)
.expireAfterAccess(20, TimeUnit.MINUTES)
.build(
new CacheLoader<String, Map<Integer, AtomicLong>>() {
@Override
public Map<Integer, AtomicLong> load(String word) throws Exception {
Map<Integer, AtomicLong> map = new HashMap<>();
map.put(0, new AtomicLong(10));
return map;
}
});
public static void main(String[] args) throws Exception {
System.out.println(NWZs.get("foo").get(0));
Map<Integer, AtomicLong> wincm = NWZs.get("foo");
wincm.get(0).addAndGet(5);
System.out.println(NWZs.get("foo").get(0));
}
The output should be
10
15
Upvotes: 1