在java中使用简单易用的LRU缓存 [英] Easy, simple to use LRU cache in java

查看:130
本文介绍了在java中使用简单易用的LRU缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它实现起来很简单,但我想重用已经存在的东西。

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

我想解决的问题是我加载配置(从XML开始,所以我想要缓存它们)用于不同的页面,角色......所以输入的组合可以增长很多(但99%不会)。要处理这个1%,我希望在缓存中有一些最大数量的项目...

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...

直到知道我找到了org.apache.commons.collections.map。 LRUMap在apache commons中它看起来很好但是想要检查别的东西。有什么建议?

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?

推荐答案

你可以使用 LinkedHashMap (Java 1.4+):

You can use a LinkedHashMap (Java 1.4+) :

// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
    // 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);

这篇关于在java中使用简单易用的LRU缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆