Search code examples
ehcacheehcache-3

Make Ehcache return expired data if LoaderWriter fails


Is it possible to set up Ehcache in such a way that cache will return "expired" data if the underlying CacheLoaderWriter fails (throws an Exception)?

Accordingly to my tests, if a given cache entry is expired, and CacheLoaderWriter fails to load data, cache returns null.

However, on my case, it would be better to return the expired cached data than nothing. What I am doing as a work around is to store the latest successfully loaded data in the CacheLoaderWriter, so if a new execution of the load fails, I return this copy. Anyway, think that would be more "memory efficient" to, somehow, return the data that it's already in the cache, instead of keeping another copy in the CacheLoaderWriter.

I am using ehcache 3.4.0

        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("myCacheName",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, ResourcePoolsBuilder.heap(100))
                            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(4, TimeUnit.HOURS)))
                            .withLoaderWriter(new TestCacheLoaderWriter()))
            .build();

Solution

  • It is not possible. However, unless you are using a copier, it isn't a copy you are keeping in your loader-writer. It's only another reference to the object in cache.

    Your request could be filed as an enhancement in the Ehcache issue tracker.

    The alternative would be to never expire the data but replacing it from outside when needed.