猿问
下载APP

在Java中易于使用的LRU缓存

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


我要解决的问题是我为不同的页面,角色加载了配置(从XML,所以我想缓存它们),因此输入的组合可以增长很多(但99%的增长)。为了处理这个1%,我想在缓存中设置一些最大项目...


直到我在apache commons中找到了org.apache.commons.collections.map.LRUMap,它看起来还不错,但还想检查其他内容。有什么建议吗?


一只萌萌小番薯
浏览 56回答 3
3回答

繁华开满天机

您可以使用LinkedHashMap(Java 1.4+):// Create cachefinal 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 cacheObject key = "key";cache.put(key, object);// Get objectObject 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 methodscache = (Map)Collections.synchronizedMap(cache);

天涯尽头无女友

这是一个老问题,但是为了后代,我想列出ConcurrentLinkedHashMap,它是线程安全的,与LRUMap不同。用法很简单:ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()&nbsp; &nbsp; .maximumWeightedCapacity(1000)&nbsp; &nbsp; .build();该文档还有一些很好的示例,例如如何使LRU缓存基于大小而不是基于项目数。

守候你守候我

这是我的实现,可让我在内存中保留最佳数量的元素。关键是我不需要跟踪当前正在使用的对象,因为我将MRU对象的LinkedHashMap和LRU对象的WeakHashMap结合使用。因此,缓存容量不小于MRU大小加上GC允许我保留的容量。只要有物体从MRU上掉落,它们就会进入LRU,直到GC拥有它们。public class Cache<K,V> {final Map<K,V> MRUdata;final Map<K,V> LRUdata;public Cache(final int capacity){&nbsp; &nbsp; LRUdata = new WeakHashMap<K, V>();&nbsp; &nbsp; MRUdata = new LinkedHashMap<K, V>(capacity+1, 1.0f, true) {&nbsp; &nbsp; &nbsp; &nbsp; protected boolean removeEldestEntry(Map.Entry<K,V> entry)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.size() > capacity) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LRUdata.put(entry.getKey(), entry.getValue());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; };}public synchronized V tryGet(K key){&nbsp; &nbsp; V value = MRUdata.get(key);&nbsp; &nbsp; if (value!=null)&nbsp; &nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp; value = LRUdata.get(key);&nbsp; &nbsp; if (value!=null) {&nbsp; &nbsp; &nbsp; &nbsp; LRUdata.remove(key);&nbsp; &nbsp; &nbsp; &nbsp; MRUdata.put(key, value);&nbsp; &nbsp; }&nbsp; &nbsp; return value;}public synchronized void set(K key, V value){&nbsp; &nbsp; LRUdata.remove(key);&nbsp; &nbsp; MRUdata.put(key, value);}}
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答