Class LruCache<K,​V>

  • Type Parameters:
    K - the type of keys maintained by this cache
    V - the type of values maintained by this cache
    All Implemented Interfaces:
    java.io.Serializable, java.lang.Cloneable, java.util.Map<K,​V>

    @API(status=INTERNAL,
         since="1.6")
    public class LruCache<K,​V>
    extends java.util.LinkedHashMap<K,​V>
    A simple LRU cache with a maximum size.

    This class is not thread-safe.

    Since:
    1.6
    See Also:
    Serialized Form
    • Nested Class Summary

      • Nested classes/interfaces inherited from class java.util.AbstractMap

        java.util.AbstractMap.SimpleEntry<K extends java.lang.Object,​V extends java.lang.Object>, java.util.AbstractMap.SimpleImmutableEntry<K extends java.lang.Object,​V extends java.lang.Object>
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private int maxSize  
      private static long serialVersionUID  
    • Constructor Summary

      Constructors 
      Constructor Description
      LruCache​(int maxSize)
      Create a new LRU cache that maintains at most the supplied number of entries.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected boolean removeEldestEntry​(java.util.Map.Entry<K,​V> eldest)  
      • Methods inherited from class java.util.LinkedHashMap

        clear, containsValue, entrySet, forEach, get, getOrDefault, keySet, replaceAll, values
      • Methods inherited from class java.util.HashMap

        clone, compute, computeIfAbsent, computeIfPresent, containsKey, isEmpty, merge, put, putAll, putIfAbsent, remove, remove, replace, replace, size
      • Methods inherited from class java.util.AbstractMap

        equals, hashCode, toString
      • Methods inherited from class java.lang.Object

        finalize, getClass, notify, notifyAll, wait, wait, wait
      • Methods inherited from interface java.util.Map

        compute, computeIfAbsent, computeIfPresent, containsKey, equals, hashCode, isEmpty, merge, put, putAll, putIfAbsent, remove, remove, replace, replace, size
    • Field Detail

      • maxSize

        private final int maxSize
    • Constructor Detail

      • LruCache

        public LruCache​(int maxSize)
        Create a new LRU cache that maintains at most the supplied number of entries.

        For optimal use of the internal data structures, you should pick a number that's one below a power of two since this is based on a HashMap and the eldest entry will be evicted after adding the entry that increases the size to be above maxSize.

    • Method Detail

      • removeEldestEntry

        protected boolean removeEldestEntry​(java.util.Map.Entry<K,​V> eldest)
        Overrides:
        removeEldestEntry in class java.util.LinkedHashMap<K,​V>