javaguavagoogle-guava-cache

Guava CacheBuilder evicts items ahead of schedule


I am trying to create a simple cache where I can store some data elements in a map. I need to keep this data around for ~ 16 hours or so, after that I can let the older items expire. I am instantiating my LoadingCache thusly:

 cache = CacheBuilder.newBuilder()
                .concurrencyLevel(4)
                .weakKeys()
                .expireAfterWrite(16, TimeUnit.HOURS)
                .build(
                        new CacheLoader<K, V>() {
                            public V load(K key) throws Exception {
                                return getByKey(key);
                            }
                        });

There is a process that adds ~ 16 items to the list every minute. Every 12 minutes or so, the cache gets completely wiped out. I'm baffled by what is causing the cache to be wiped out, well in advance of the time set in the expireAfterWrite().


Solution

  • my guess is that weakKeys() is responsible. if the cache is the only one referencing the items, a garbage collection may decide to delete the entries. From the Guava doc:

    If weakKeys, weakValues, or softValues are requested, it is possible for a key or value present in the cache to be reclaimed by the garbage collector.