Monday, March 14, 2011

Simple cache implementation

I was looking for a cache solution for a small prototype application I currently work on. There are a lot of caching libraries out there but since I needed something extremely simple I decided to implement one myself.

The Java Collections Framework never stops to surprise me. When I started to look for suitable collections to store my cached objects I noticed an interesting protected method in the LinkedHashMap class:
protected boolean removeEldestEntry(Map.Entry eldest);
Using this, implementing a fixed size "last recently used" collection is possible in just a few lines of code:
public class LruMap<K, V> extends LinkedHashMap<K, V> {

    private final int limit;

    public LruMap(int limit) {
        super(16, 0.75f, true);
        this.limit = limit;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > limit;
    }
}

No comments:

Post a Comment