如何通过Java清除缓存对象(内存)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9662831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear cache object (memory) through Java
提问by JavaBits
Code snippet used to allocate cache memory:
用于分配缓存内存的代码片段:
private static Cache cache = CacheManager.getInstance().getCache(CACHE_NAME);
public static HashMap<String, XXX> getxxCodes(int version) {
HashMap<String, XXX> xxCodes = new HashMap<String, XXX>();
try{
Object[] cacheResult = cache.get(Constants.I_XX_CODES_FOR_XXX);
if (Boolean.FALSE.equals(cacheResult[1])) {
cache.put(Constants.I_XX_CODES_FOR_XXX, id.loadXXHashMap(version));
cacheResult = cache.get(Constants.I_XX_CODES_FOR_XXX);
}
if(cacheResult[0]!=null){
xxCodes = (HashMap<String, XXX>)cacheResult[0];
}
}catch(Exception e){
logger.error("Exception occured while loading Data from I10_DRG_XX",e);
}
return xxCodes;
}
Now at some point of time I need to load some other "version" into the cache memory. Here version can be 1, 2, 3 etc. So the cache first holds version 1 data (Hash map). Now when I am passing 2 which is unavailable in cache it needs to load specific data again into cache, but before that it is better to clear version 1 data. Do we have commands like flush to clear specific data?
现在在某个时间点我需要将一些其他“版本”加载到缓存中。这里版本可以是 1、2、3 等。所以缓存首先保存版本 1 数据(哈希映射)。现在,当我传递缓存中不可用的 2 时,它需要再次将特定数据加载到缓存中,但在此之前最好清除版本 1 数据。我们有像flush这样的命令来清除特定数据吗?
I hope I am clear with my question. Thanks for helping.
我希望我的问题很清楚。谢谢你的帮助。
采纳答案by JavaBits
I have used the following code and its working correctly,
我使用了以下代码并且它工作正常,
public void flushCache()
{
cache.flush(cacheKeyName)
}
This will delete the Instance of cache from memory. Thanks for all your help.
这将从内存中删除缓存实例。感谢你的帮助。
回答by Shashank Kadne
This will remove the object from the Cache(Assumption:Weblogic cache)..It sets the Time to Liveto "0"
这将从缓存中删除对象(假设:Weblogic 缓存)。它将生存时间设置为“0”
Cache cache = getCache();
cache.remove(cacheKey);
getCache()
can be implemented as follows...
getCache()
可以实现如下...
public Cache getCache(){
Cache cache = CacheFactory.getCache(cacheKey);
long ttl=0;
cache.setTtl(ttl);
return cache;
}