Friday, June 3, 2016

Design a Cache mechanism which uses LRU(Least Recently Used) in java

Solution Description:

The Processing costs for selecting a value from a database-table is high compared to the cost having the value already in memory.So there should be some mechanism that keeps often used values in your application instead getting these values from resource somewhere outside.

But there is a point when using cache in java is the size of the cache;when chache grows too big the java garbage collector has to cleanup more often or our application crashes with a out of memory error.

So we can implement LRU using "LinkedHashMap" class allows us to implement both an LRU and FIFO queues almost without coding.

Why LinkedHashMap? we are using?.
Because the map to become an LRU map. That's because  the map is ordered by access-order.

public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder)

Implementation:

import java.util.LinkedHashMap;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class LRUCache extends LinkedHashMap
{

private static final long serialVersionUID =1L;
private final int capacity;
private long accessCount = 0;
private long hitCount =0;

public LRUCache(int capacity)
{
this.capacity =capacity;
}

public Object get(Object key)
{
accessCount++;
if(super.containsKey(key))
{
hitCount++ ;
}
Object value=super.get(key);
return value;
}

public boolean containsKey(Object key)
{
accessCount ++ ;
if(super.containsKey(key))
{
hitCount++ ;
return true;
}
else
{
return false;
}
}

protected boolean removeEldesEntry(Entry eldest)
{
return size() > capacity ;
}

public long getHitCount() {
return hitCount;
}

public long getAccessCount() {
return accessCount;
}

}

Note: There is a Catch here.What if the interviewer does not allow us to use"LinkedHashMap"?
I am leaving on you guys to solve without "LinkedHashMap".

No comments: