BaDr Amer
BaDr Amer

Reputation: 920

implement a Guava cache to last for ever

I have a cache that holds multiple values (~ 50 records) from a lookup table and I want to put these values in a cache and I don't want it to expire.

my implementation look like this :

static {
        cache = CacheBuilder.newBuilder().removalListener(new RemovalListener<String, Record>() {
        }).maximumSize(100)
                .expireAfterAccess(1, TimeUnit.DAYS) // ??
                .build(new CacheLoader<String, Record>() {
                    @Override
                    public Record load(String id) throws Exception {
                        throw new Exception("not cached");
                    }
                });
    }

and inside the constructor I check if the cache is empty then load the data from the database :

cache = CacheUtil.getLoadingDeviceCache();
if(cache == null || cache.size() == 0) {
    synchronized(this) {
        List<Record> allAuthorizedDevices = DB.getAuthorizedDevices();
        for (Record record : allAuthorizedDevices) {
            try {
                cache.put(record.getValue("id").toString(), record);
            } catch (DataSetException e) {
            }   
        }
    }
}

what can I do to make it eternal ?

Upvotes: 0

Views: 1803

Answers (2)

kapex
kapex

Reputation: 29999

If you build your cache with CacheBuilder.maximumSize, then elements will be removed from the cache when the maximum size is approached. If you build your cache with CacheBuilder.expireAfterAccess, then elements will be removed after some time.

If you don't want any of that, you should build your cache without time or size restrictions. If you use e.g. CacheBuilder.weakKeys() instead, then elements will only be removed from the cache if they aren't referenced anywhere except by the cache.

See Guava Cache Eviction for more information.

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140554

Cache entries only expire after a given time if you call expireAfterAccess.

The solution: don't call expireAfterAccess!

Upvotes: 1

Related Questions