LRU Cache implementation with LinkedHashMap

If you are reading this article then you might have reached here hunting for implementation of LRU Cache. Below is simple code which can help you in understanding the LRU Cache and its implementation.

import java.util.LinkedHashMap;
import java.util.Map.Entry;

/**
 * @author ThoughtClicks Inc
 *
 */
public class LRUCache extends LinkedHashMap {

 private static final long serialVersionUID = 1L;
 private final int capacity;
 private long accessCount = 0;
 private long hitCount = 0;

 public LRUCache(int capacity) {
  super(capacity + 1, 1.1f, true);
  this.capacity = capacity;
 }

 @Override
 public Object get(Object key) {
  accessCount++;
  if (super.containsKey(key)) {
   hitCount++;
  }
  Object value = super.get(key);
  return value;
 }

 @Override
 public boolean containsKey(Object key) {
  accessCount++;
  if (super.containsKey(key)) {
   hitCount++;
   return true;
  }else{
   return false;
  }
 }

 protected boolean removeEldestEntry(Entry eldest) {
  return size() > capacity;
 }

 public long getAccessCount() {
  return accessCount;
 }

 public long getHitCount() {
  return hitCount;
 }
}



To use the above cache you just need to call the constructor of the above LRUCache with the maximum size of your cache and then just set the value as you do in a hashmap.

Have fun !