Is there a way to configure ehcache to only cache some numbers of elements in time order?

2.2k views Asked by At

My current config is as below, I intended to only cache up to 30 elements and evict the oldest one when the number is more than 30:

<ehcache>
    <diskStore path="/path/to/store/"></diskStore>
    <cache name="myCache"
       eternal="false"
       maxEntriesLocalHeap="30"
       maxEntriesLocalDisk="30"
       memoryStoreEvictionPolicy="FIFO">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

I have another scheduled job which runs every minute to put a new element into the cache. So I expect to get only 30 elements within recent 30 minutes. But the expiring/eviction was not as expected. Some very old elements were still kept while some elements within recent 30 minutes were unexpectedly evicted. Is there anything I missed here?

I've read through the expiring/eviction related documentation in ehcache, but did not find any clue. Hope someone can help :)

BTW, the ehcache version is 2.6.6

2

There are 2 answers

3
Roy Ling On BEST ANSWER

Thanks @Louis for the answer and suggestion.

In ehcache doc, I learned that memoryStoreEvictionPolicy is only for memory store, while in my case disk store is used. And also eviction policy for disk store is by default LFU and not configurable.

In Ehcache, the MemoryStore may be limited in size (see How to Size Caches for more information). When the store gets full, elements are evicted. The eviction algorithms in Ehcache determine which elements are evicted. The default is LRU.

... The DiskStore eviction algorithm is not configurable. It uses LFU.

So to achieve what I am expecting, I changed to use memory store only, given that the current persistent strategy for disk store is not restartable (localTempswap), which is equivalent in using memory store. The final config is as:

<cache name="myCache"
       eternal="false"
       maxEntriesLocalHeap="30"
       memoryStoreEvictionPolicy="FIFO">
</cache>
0
Louis Jacomet On

Ehcache eviction strategies have always had some level of heuristics in them. For example the eviction policy is not applied on the entire population of the cache, that would be too costly for large caches, but rather on a sample.

That's why you are experiencing an inexact outcome compared to your requirements.

Now given the limited number of elements you want to keep, a LinkedHashMap sounds like a great choice, although it is not safe for multi threaded access.