javagoogle-guava-cache

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 ?


Solution

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

    The solution: don't call expireAfterAccess!