简体   繁体   中英

LRU best way to do a quick implementation in java

I want to construct a quick LRU cache. Is this kind of solution is a good way to do this ? And what about the synchronization ?

There's a protected method called removeEldestEntry. This method is called when items are being added to the map. The default implementation just returns false. But i can subclass LinkedHashMap and override this method to check whether a maximum size has been reached, then just return true. The LinkedHashMap will find the oldest entry via the linked list and boot it before adding a new entry.

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泛型和集合” 在这里

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM