Search code examples
javaehcacheehcache-3

In EhCache3 does a persistent cache mean that data always has to be written to the disk cache


With Ehcache 3 if I have a persistent cache does that mean that everything will be written to the disk cache even if the heap/offheap caches are full or not ?

i.e I have this

PersistentCacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .with(CacheManagerBuilder.persistence(new File(Platform.getPlatformDatabaseFolder(), RELEASE_CACHE)))
                .withCache(RELEASE_CACHE,
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(
                                String.class,
                                String.class,
                                ResourcePoolsBuilder.newResourcePoolsBuilder()
                                        .heap(100, EntryUnit.ENTRIES)
                                        .offheap(10, MemoryUnit.MB)
                                        .disk(20, MemoryUnit.MB, true)))
                .build();

So I am expirmenting with this but I have specified a disk cache because usually memory cache will not be sufficient, and I have specified it to be persistent because if data is written to the disk it may well be useful for subsequent runs of the application.

However, sometimes the application may be used in such a way that the heap/offheap is not fully used, therefore I do not want the application to be wasting time writing data to disk just because I have marked it as persistent. After all the reason I am using a cache is to improve performance.


Solution

  • As documented, whenever you have multiple tiers in Ehcache, the lowest tier (disk in your case) always see the put to the cache, while higher tiers are simply invalidated (offheap and heap in your case). On a get the value is pulled into the highest tier (heap in your case) for fast subsequent access. If that results in eviction from heap, then the evicted value is pushed down to offheap and, in cascade, that could cause an eviction from offheap to disk.

    Note that the above system is done so that performance remains predictable instead of dropping suddenly when a tier gets full.

    So there is a cost to have multiple tiers in Ehcache. Depending on your use case, it might be better to have less tiering options activated. As always with caching: measure and adapt.