Skip to main content

LinkedHashMap as LRU cache

I have a simple implementation for a LRU cache using LinkedHashMap.

  • I want it to be as generic as possible.
  • This is not for production use, just practice, so I don't care if its thoroughly robust as far as it is correct. However, I will welcome any comments, especially the ones which might make this better with simple changes :)
  • Are there any other ways of doing this?
class LRUCache<E> {

    @SuppressWarnings("unchecked")
    LRUCache(int size)
    {
        fCacheSize = size;
        
        // If the cache is to be used by multiple threads,
        // the hashMap must be wrapped with code to synchronize 
        fCacheMap = Collections.synchronizedMap
        (
            //true = use access order instead of insertion order
            new LinkedHashMap<Object,E>(fCacheSize, .75F, true)
            {                                
                @Override
                public boolean removeEldestEntry(Map.Entry eldest)  
                {
                    //when to remove the eldest entry
                    return size() > 99 ;   //size exceeded the max allowed
                }
            }
        );
    }

    public void put(Object key, E elem)
    {
        fCacheMap.put(key, elem);
    }

    public E get(Object key)
    {
        return fCacheMap.get(key);
    }

    private Map<Object,E> fCacheMap;
    private int fCacheSize;
}
p101
  • 343
  • 1
  • 4
  • 9