Olivier
Olivier

Reputation: 474

Do I need to lock my read-only cache before refreshing it with Ehcache?

I am making an implementation of Ehcache in a multi-thread environment. I have 1 thread dedicated for managing and refreshing the cache, and the other threads could invoke it any given time.

The cache is read-only, but refresh every 30 minutes. Does Ehchache automatically manage and lock the read access to the cache while it is updating it? Or do I need to wrap with acquireReadLockOnKey() statements?

Ehcache cache = getCache();
cache.acquireReadLockOnKey(element);
try {
    cache.put(element); 
}
finally {
    cache.releaseReadLockOnKey(element);
}

UDPATE: Here are more details on the implementation. The above code is for the "updateCache()" method, but below is how it is initially created.

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;

public class TTLCacheProviderHelper {   
    private CacheManager cacheManager = null;
    Ehcache myTtlCache = null;  
    private static final String CACHE_NAME = "myTTLCache";
    private static int TTL_VALUE = 1800;    
    private static EvictTimeClock evictTimeClock = null;


    /**
     * Constructor
     */
    public TTLCacheProviderHelper() {
        cacheManager = CacheManager.create();      
        Cache testCache = new Cache(CACHE_NAME, 100, false, false, 10, 10);
        Ehcache  originalCache = testCache;        
        cacheManager.addCache(originalCache);       
        myTtlCache = cacheManager.getCache(CACHE_NAME); 
        String ttlValue = AppConfigService.getInstance().getTTL();
        if(ttlValue!= null)
            TTL_VALUE = Integer.parseInt(ttlValue);
        evictTimeClock = new EvictTimeClock();
        setEvictTimeClock(TTL_VALUE);
    }

    Ehcache getCache(){
        return myTtlCache;
    }`

And its config: `

    <cache name="configCache" maxElementsInMemory="100000" eternal="true" overflowToDisk="false" />

    <cache name="validationTemporaryCache" maxElementsInMemory="10000"
        eternal="false" overflowToDisk="false" timeToIdleSeconds="500"
        timeToLiveSeconds="500" />

</ehcache>`

Upvotes: 4

Views: 2759

Answers (1)

mindas
mindas

Reputation: 26713

If your scenario is read -> flush -> recalculate -> put -> read, then the answer is no, Ehcache does not automagically block all readers until the new value is calculated. What you need to do is to use its read-through mechanism or something similar.

But if your scenario is read -> recalculate -> replace -> read, then I don't see a need for any extra locking.

Upvotes: 3

Related Questions