【发布时间】: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