Java - Least-Recently-Used (LRU) cache
A cache is here defined, which can take in 50 elements. Is a 51th added, then the element is deleted on which weren't accessed at longest in the last time.
public class LRUCache { public static final int MAX_ENTRIES = 50; private Map cache; public LRUCache(){ cache = new LinkedHashMap(MAX_ENTRIES+1, 0.70f, true){ @Override public boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } }; }
The LRUCache can from now on be used as a normal Map:
cache.put("key", myObject); Object o = cache.get("key");
If the Cache shall be used by several Threads, so this one must be synchronized:
cache = (Map) Collections.synchronizedMap(cache);