Limited Size Hash Card

I would like to make a hash map for use as a cache. The cache has an initial size if you try to insert an item when the cache is full. The last last used item should be replaced ... any ideas?

+5
source share
6 answers

On Android, you can use http://developer.android.com/reference/android/util/LruCache.html . I am quite sure that you can take this implementation from AOSP and use it under the Apache license.

+2
source

You can use LinkedHashMap by implementing removeEldest

public static <K,V> Map<K,V> lruCache(final int maxSize) {
    return new LinkedHashMap<K,V>(maxSize*4/3, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
            return size() > maxSize;
        }
    };
}

More details

http://vanillajava.blogspot.co.uk/2011/06/java-secret-lru-cache-in-java.html

http://blog.meschberger.ch/2008/10/linkedhashmaps-hidden-features.html

+13

Guava? factory caches ..

. ( )

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
   .maximumSize(1000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });
+8

LRUMap Apache Commons.

, , .

get put. , , . , containsKey containsValue , .

OrderedMap, OrderedMapIterator. . OrderedIterator, .

reset , ResettableIterator reset().

, LRUMap . , . - , Collections.synchronizedMap(). NullPointerException .

+1

-. , , .

+1

The easiest approach is to expand LinkedHashMap, override the method removeEldestEntry(Map.Entry<K,V> eldest)and decide in its implementation if your cache is "full" or not.

0
source

All Articles