Java Secret: LRU cache in Java.
Overview
Since Java 1.4, Java has had a support for a LRU (least recently used) cache. Very few seem to know about it even though it can be very useful.LinkedHashMap as an LRU Cache
This class has a couple of features which allows it to support an LRU cache. The default order for LHM is the order entries are added, but you can change the order so it can be ordered by last accessed. Another feature is the removeEldest method which allows you to specify whether the eldest entry should be implicitly removed. Used in combination we have an LRU cache.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; } }; }
This cache is not thread safe and you would need to wrap it in Collections.synchronizedMap() if you needed thread safety.
Comments
Post a Comment