Advertisement
Guest User

LRUCache

a guest
Jul 15th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package tests.sound;
  2.  
  3. import java.util.Collection;
  4. import java.util.LinkedHashMap;
  5. import java.util.Map;
  6.  
  7. /**
  8.  * A simple implementation of an LRU cache.
  9.  * <p>
  10.  * Retrieved from <a href=
  11.  * "http://stackoverflow.com/questions/224868/easy-simple-to-use-lru-cache-in-java"
  12.  * >Stackoverflow</a>.
  13.  *
  14.  * @author Gustavo Steigert
  15.  */
  16. public class LRUCache<K, V>
  17. {
  18.     /**
  19.      * Called when a cached element is about to be removed.
  20.      */
  21.     public interface CacheEntryRemovedListener<K, V>
  22.     {
  23.         void notifyEntryRemoved(
  24.             K key,
  25.             V value );
  26.     }
  27.  
  28.     private Map<K,V> cache;
  29.     private CacheEntryRemovedListener<K,V> entryRemovedListener;
  30.  
  31.     /**
  32.      * Creates the cache with the specified max entries.
  33.      */
  34.     public LRUCache(
  35.         final int maxEntries )
  36.     {
  37.         cache = new LinkedHashMap<K,V>( maxEntries + 1, .75F, true ) {
  38.             private static final long serialVersionUID = 1L;
  39.  
  40.             public boolean removeEldestEntry(
  41.                 Map.Entry<K,V> eldest )
  42.             {
  43.                 if( size() > maxEntries ) {
  44.                     if( entryRemovedListener != null ) {
  45.                         entryRemovedListener.notifyEntryRemoved( eldest.getKey(), eldest.getValue() );
  46.                     }
  47.                     return true;
  48.                 }
  49.                 return false;
  50.             }
  51.         };
  52.     }
  53.  
  54.     public void add(
  55.         K key,
  56.         V value )
  57.     {
  58.         cache.put( key, value );
  59.     }
  60.  
  61.     public V get(
  62.         K key )
  63.     {
  64.         return cache.get( key );
  65.     }
  66.  
  67.     public Collection<V> retrieveAll()
  68.     {
  69.         return cache.values();
  70.     }
  71.  
  72.     public void setEntryRemovedListener(
  73.         CacheEntryRemovedListener<K,V> entryRemovedListener )
  74.     {
  75.         this.entryRemovedListener = entryRemovedListener;
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement