Java Data Structure How to - Create a Least-Recently-Used (LRU) Cache by using LinkedHashMap








Question

We would like to know how to create a Least-Recently-Used (LRU) Cache by using LinkedHashMap.

Answer

//from w  ww.j a  v  a  2s . c  om
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
  public static void main(String[] argv) throws Exception {
    final int MAX_ENTRIES = 100;
    Map cache = new LinkedHashMap(MAX_ENTRIES + 1, .75F, true) {
      public boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;
      }
    };

    Object key = "key";
    Object value = "value";
    cache.put(key, value);
    Object o = cache.get(key);
    if (o == null && !cache.containsKey(key)) {
    }
    cache = (Map) Collections.synchronizedMap(cache);
  }
}

The code above generates the following result.