Pergunta

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?

Foi útil?

Solução

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

Outras dicas

It will, assuming that

  • you don't get an NPE because of wincm not present in the cache
  • the Map you modified won't get evicted and reloaded again

I 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

  • you try to update the data in cache and it's not there (so you think it's fine)
  • the data gets loaded into the cache just before
  • you update them in the backend

or the other way round

  • you update the data in the backend
  • and they get loaded into the cache
  • and then updated manually again
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top