LRU Cache for Page replacement policy


What is the purpose?

When accessing large amounts of data is deemed too slow, a common speed up technique is to keep a small amount of the data in a more accessible location known as a cache.
In general, a cache is much too small to hold all the data you might possibly need, so at some point you are going to have to remove something from the cache in order to make room for new data. The goal is to retain those items that are more likely to be retrieved again soon. This requires a sensible algorithm for selecting what to remove from the cache. One simple but effective algorithm is the Least Recently Used, or LRU, algorithm.

How to do?
package com.kartik;
import java.util.LinkedHashMap;
import java.util.Map;
public class LruCache<K,V> extends LinkedHashMap<K, V> {
 private static final long serialVersionUID = 1L;
 private int size;
 private LruCache(int size){
  super(size,0.75f,true);
  this.size=size;
 }
   public static<K, V> LruCache<K, V> newInstance(int size){
    return new LruCache<K, V>(size);
   }
   public void setMaxSize(int size){
   this.size=size;
   }
   @Override
   protected boolean removeEldestEntry(Map.Entry<K, V> eledest){
 return size()>size;
  
   }
 public static void main(String[] args) {
LruCache<String,String> lruCache=LruCache.newInstance(5);//number of cache memory block size
lruCache.put("1", "1");//first 1 is block number and second 1 is page number
lruCache.put("3", "3");//first 3 is block number and second 3 is page number
lruCache.put("2", "2");
lruCache.put("4", "4");
lruCache.put("5", "6");
lruCache.put("4", "1");
lruCache.put("2", "23");
lruCache.put("4", "4");
System.out.println(lruCache);
 }
}

Output:

{1=1, 3=3, 5=6, 2=23, 4=4}



Example:




Previous
Next Post »

2 comments

Click here for comments
Unknown
admin
6 May 2016 at 07:02 ×

Nice Implementation. I Remember this studied in college days.

Reply
avatar