LRUMap的一种: LinkedHashMap原来这么有魅力

本文介绍了一种使用 Java 中的 LinkedHashMap 实现 LRU (Least Recently Used) 缓存的方法。该方法允许设置缓存的最大容量,并在超出容量时自动移除最久未使用的条目。此外,还探讨了在多线程环境中如何同步此类缓存。
摘要由CSDN通过智能技术生成

http://stackoverflow.com/questions/224868/easy-simple-to-use-lru-cache-in-java


Easy, simple to use LRU cache in java


I know it's simple to implement, but I want to reuse something that already exist.


Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...


Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?

 


You can use a LinkedHashMap (Java 1.4+) :
The code from exampledepot.com:
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) { //true 以访问顺序排列;false 以插入顺序排列
    // This method is called just after a new entry has been added
    public boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;//删除最老的键值对的条件
    }
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
    // Object not in cache. If null is not a possible value in the cache,
    // the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值