LRU Implementation - Java

import java.util.LinkedHashMap;import java.util.Map;
/** * Created by skupunarapu on 10/19/2015. */public class LRUImpl extends LinkedHashMap<Integer, String> {

    private static final long serialVersionUID = 1L;   
    private int capacity;

    public LRUImpl(int capacity, float loadFactor){
        super(capacity, loadFactor, true);        
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
        return size() > this.capacity;
    }

    public static void main(String arg[]){
        LRUImpl lruCache = new LRUImpl(4, 0.75f);
        lruCache.put(1, "Object1");
        lruCache.put(2, "Object2");
        lruCache.put(3, "Object3");
        lruCache.get(1);
        lruCache.put(4, "Object4");
        System.out.println(lruCache);
        lruCache.put(5, "Object5");
        lruCache.get(3);
        lruCache.put(6, "Object6");
        System.out.println(lruCache);
        lruCache.get(4);
        lruCache.put(7, "Object7");
        lruCache.put(8, "Object8");
        System.out.println(lruCache);
    }
}


{2=Object2, 3=Object3, 1=Object1, 4=Object4}
{4=Object4, 5=Object5, 3=Object3, 6=Object6}
{6=Object6, 4=Object4, 7=Object7, 8=Object8}

println() method prints object in order of their staleness. As you can see in the above code, Object1, Object2 and Object3 are inserted and object1 is accessed just before inserting the Object4 and hence Object1 is printed before the object4 in the first line of the output. When Object5 is inserted the Object2 is get evicted from the list because this object is the oldest in the list. When object3 is accessed, it gets promoted higher than object5 and when object6 is inserted Object1 is evicted. The rest output is self-explanatory, hope you will not find difficult in understanding the output.

Comments

Popular posts from this blog

public vs protected vs default access modifiers - Java

Class, Reference and Object