在使用Ehcache刷新之前,是否需要锁定只读缓存?

时间:2013-03-25 23:57:35

标签: java multithreading java-ee caching ehcache

我正在多线程环境中实现Ehcache。 我有1个专用于管理和刷新缓存的线程,其他线程可以在任何给定时间调用它。

缓存是只读的,但每30分钟刷新一次。 Ehchache在更新缓存时是否会自动管理并锁定对缓存的读取权限?或者我需要使用acquireReadLockOnKey()语句进行换行吗?

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

UDPATE: 以下是有关实施的更多详细信息。上面的代码用于“updateCache()”方法,但下面是最初创建的方法。

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;
    }`

其配置: `         

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

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

</ehcache>`

1 个答案:

答案 0 :(得分:3)

如果您的方案是read -> flush -> recalculate -> put -> read,那么答案是否定的,Ehcache在计算新值之前不会自动阻止所有读者。您需要做的是使用其read-through mechanism或类似的东西。

但如果您的方案是read -> recalculate -> replace -> read,那么我认为不需要任何额外的锁定。

相关问题