【问题标题】:Do I need to lock my read-only cache before refreshing it with Ehcache?在使用 Ehcache 刷新之前,我是否需要锁定我的只读缓存?
【发布时间】:2013-03-15 15:42:34
【问题描述】:

我正在多线程环境中实现 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>`

【问题讨论】:

  • 在您刷新时,如果另一个线程看到旧值,这有关系吗?如果没有,那么你不需要锁定。
  • 虽然,这可能取决于您的缓存是否是自填充的。您应该包含有关如何配置 ehcache 实例的更多详细信息。
  • 不,缓存是否有旧值无关紧要,只要它不返回不一致的对象即可。你有没有提到它不需要明确锁定?

标签: java multithreading jakarta-ee caching ehcache


【解决方案1】:

如果您的场景是read -&gt; flush -&gt; recalculate -&gt; put -&gt; read,那么答案是否定的,Ehcache 不会自动阻塞所有读取器,直到计算出新值。您需要做的是使用它的read-through mechanism 或类似的东西。

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

【讨论】:

  • 嗯,它是多线程的,所以控制缓存的线程会这样做:重新计算 -> 替换。其他线程刚刚阅读。
  • Ehcache.putEhcache.replace 是原子的,因此一旦此方法完成,所有其他 Ehcache.read 方法将获得新值。这里不需要任何额外的锁定。
  • 另外,多个线程的默认 putIfAbsent 行为是否只有一个成功,而 EhCache 中没有任何额外的写入/读取锁?
  • @user469718 你可能想为此打开一个单独的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2015-05-06
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
相关资源
最近更新 更多