Are there any implementations of a static size hashtable that limits the entries to either the most recently or most frequently used metadata? I would prefer not to keep track of this information myself.
I know most caching components keep track of this, but I w开发者_如何转开发ould rather not introduce quite a lot of new dependencies.
You can build an LRU cache using the standard JDK library using LinkedHashMap
:
public class MyLRUCache<K, V> extends LinkedHashMap<K, V> {
private final int maxEntries;
public MyLRUCache(int maxEntries) {
// you can be a bit fancy with capacity and load factor
super(16, 0.75, true);
this.maxEntries = maxEntries;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries;
}
}
You may want to play with WeakReference
s as well.
Use LinkedHashMap and override removeEldestEntry and make sure to use the
constructor that allows to accessOrder as true
Accessordered makes the map remove the least recently accessed item instead of the eldest.
All queries will alter the structure of the map, hence be a tiny bit slower.
Example:
public AccesOrderedLRUCache<V,K> extends LinkedHashMap<V,K>{
private final m_capacity;
public AccesOrderedLRUCache(int capacity) {
super(0.75*capacity, 0.75, true);
m_capacity = capacity;
}
@Override
protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
return size() > getCapacity();
}
public int getCapacity() {
return m_capacity;
}
}
精彩评论