This tutorial provides an example of how to implement an LRU cache in Java using the java.util.LinkHashMap class. The source from this tutorial was taken from Stack Overflow (http://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6) and is used for educational purposes. The LRU cache below is unsynchronized, so when used in conjunction with multiple threads, access to the cache needs to be synchronized explicitly.
package edu.rutgers.sakai.java.generics; import java.util.LinkedHashMap; import java.util.Map; /** * Simple implementation of an LRU cache based on LinkedHashMap. Idea provided by Hank Gay on StackOverflow.com * * Sourced fromhttp://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6 * * @author <a href="http://stackoverflow.com/users/4203/hank-gay">Hank Gay</a> * @author Robert Moore II * * @param <K> key for the cache, must be a class that is hashable (overrides {@link Object#hashCode()}) and {@link Object#equals(Object)}). * @param <V> the value for the cache, which may be any object. */ public class LRUCache<K, V> extends LinkedHashMap<K, V> { /** * To be updated when the class members change. */ private static final long serialVersionUID = 8497845908840524213L; /** * Maximum capacity of the cache. */ private final int capacity; /** * Creates a new LRU cache with the specified capacity. * @param capacity the maximum capacity for this cache. */ public LRUCache(int capacity) { super(capacity+1, 1.0f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(final Map.Entry<K, V> entry) { return super.size() > this.capacity; } }