Java Secret: LRU cache in Java.

Overview

Since Java 1.4, Java has had a support for a LRU (least recently used) cache. Very few seem to know about it even though it can be very useful.

LinkedHashMap as an LRU Cache

This class has a couple of features which allows it to support an LRU cache. The default order for LHM is the order entries are added, but you can change the order so it can be ordered by last accessed. Another feature is the removeEldest method which allows you to specify whether the eldest entry should be implicitly removed. Used in combination we have an LRU cache.

public static <K,V> Map<K,V> lruCache(final int maxSize) {
        return new LinkedHashMap<K,V>(maxSize*4/3, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
                return size() > maxSize;
            }
        };
    }

This cache is not thread safe and you would need to wrap it in Collections.synchronizedMap() if you needed thread safety.

Conclusion

If ever you include a complex library to do one or two simple things, you might find you don't need the library and the JDK will do what you want.

Comments

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

What does Chronicle Software do?