Friday, 3 July 2015

LRU Cache In Java

Discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least Recently Used" cache-line based on age-bits. In such an implementation, every time a cache-line is used, the age of all other cache-lines changes. LRU is actually a family of caching algorithms with members including 2Q by Theodore Johnson and Dennis Shasha,[3] and LRU/K by Pat O'Neil, Betty O'Neil and Gerhard Weikum.


//****************************************************************
//* Copyright (c) 2015 . All Rights Reserved.
//****************************************************************


import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCacheImpl extends LinkedHashMap<Integer, String> {
    private static final long serialVersionUID = 1L;
    private int capacity;

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

    /**
     * removeEldestEntry() should be overridden by the user, otherwise it will
     * not remove the oldest object from the Map.
     */
    @Override
    protected boolean removeEldestEntry(final Map.Entry<Integer, String> eldest) {
        return size() > this.capacity;
    }

    public static void main(final String arg[]) {
        final LRUCacheImpl lruCache = new LRUCacheImpl(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);
    }
}


Kindly provide your valuable feedback in comment box.

No comments:

Post a Comment