[英]LRU best way to do a quick implementation in java
I want to construct a quick LRU cache. 我想构建一个快速LRU缓存。 Is this kind of solution is a good way to do this ?
这种解决方案是一种很好的方法吗? And what about the synchronization ?
同步怎么样?
There's a protected method called removeEldestEntry. 有一个名为removeEldestEntry的受保护方法。 This method is called when items are being added to the map.
将项目添加到地图时会调用此方法。 The default implementation just returns false.
默认实现只返回false。 But i can subclass LinkedHashMap and override this method to check whether a maximum size has been reached, then just return true.
但我可以继承LinkedHashMap并重写此方法以检查是否已达到最大大小,然后返回true。 The LinkedHashMap will find the oldest entry via the linked list and boot it before adding a new entry.
LinkedHashMap将通过链表找到最旧的条目,并在添加新条目之前将其引导。
public class MyLRUMap<K,V> extends LinkedHashMap<K,V> {
private int maxCapacity;
public MyLRUMap(int initialCapacity, float loadFactor, int maxCapacity) {
super(initialCapacity, loadFactor, true);
this.maxCapacity = maxCapacity;
}
@Override
protected boolean removeEldestEntry(Entry<K,V> eldest) {
return size() >= this.maxCapacity;
}
}
Thanks 谢谢
这是推荐的方法,尽管最好使用size() > this.maxCapacity
而不是>=
我想为此推荐guava / cachebuilder
这实现在书中提到的“Java泛型和集合” 在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.