문제

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

도움이 되었습니까?

해결책

That is the recommended way to do it although it might be best to do size() > this.maxCapacity instead of >=

다른 팁

i would like to recommend guava/cachebuilder for this

This implementation is mentioned in the book “Java Generics and Collections” here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top