Reputation: 735
As I undestand this is LRU cache realization:
// LRU cache -----------------------------------------------------------------
private static final Map cacheLRU = Collections.synchronizedMap(new LinkedHashMap(MAX, 0.75f,
true/*true for access-order, false for insertion-order.*/) {
protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
return size() > MAX;
};
});
static void cacheLRUTest(){
cacheLRU.put ("1", "one"); // 1
cacheLRU.put ("2", "two"); // 2 1
cacheLRU.put ("3", "three"); // 3 2 1
cacheLRU.put ("4", "four"); // 4 3 2
if (cacheLRU.get("2") == null) throw new Error(); // 2 4 3
cacheLRU.put ("5", "five"); // 5 2 4
cacheLRU.put ("4", "second four"); // 4 5 2
// Verify cache content.
if (cacheLRU.size() != 3) throw new Error();
if (!cacheLRU.get("4").equals("second four")) throw new Error();
if (!cacheLRU.get("5").equals("five")) throw new Error();
if (!cacheLRU.get("2").equals("two")) throw new Error();
}
How can I realize MRU cache algorithm using LinkedHashMap?
UPDATE:
http://javalandscape.blogspot.com/2009/01/cachingcaching-algorithms-and-caching.html
As I undestand: LRU - If cache is full I need to delete lru item, MRU - ... mru item
Upvotes: 2
Views: 2194
Reputation: 46872
ok, my apologies - i didn't even know MRU was a valid hashing scheme, so sorry for my original comment on the question.
anyway, all you need to do to implement one with LinkedHashMap is to store items in the map and, when that number will cross some limit, discard the most recent. you can do that easily because LinkedHashMap includes a record of the access order. so you need to do two things:
create the LinkedHashMap with the constructor that allows you to specify the ordering mode, and request access order (since you want ordering to reflect access as well as addition).
on insertion, when the size is at the limit, find the first key in the list via the iterator over keys, and remove it.
Upvotes: 3