Pergunta

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

Foi útil?

Solução

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

Outras dicas

i would like to recommend guava/cachebuilder for this

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top