Cache Replacement Algorithm - LRU

Cache Replacement LRU Algorithm - (Least Recently Used)
Least Recently Used algorithm, the name itself represents its behavior. When we use this algorithm with the cache replacement policy, it will always remove the least used page from the cache and make space for the currently used page.
Based on the above statement, we have to think about the implementation of the same. We need a data structure where we have to add all the recently used data from the tail and remove it from the head.

For Example:-
We can store a maximum of 3 pages in our cache. Suppose, we have the request of pages as given below.
3, 2, 1, 0, 2, 3, 7, 4, 7

Cache Frame
2

1023747
1
22102374
0333210233
Page StatusCache MissCache MissCache MissCache MissCache HitCache MissCache MissCache MissCache Hit

We will follow the steps to push the missing pages into the cache for the performance. If the page is found then remove it and again push it on the top. If the size of the cache reaches maximum then remove the page from the beginning.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Chandra Shekhar Paatni on 26/04/20
 */
public class LRUCache {
    List<Integer> cacheList;
    int maxCapacity;
    public LRUCache(int capacity) {
        this.cacheList = new ArrayList<>(capacity);
        maxCapacity = capacity;
    }

    public  void get(int value) {
        if (!cacheList.contains(value)) {
            if (maxCapacity > 0 && cacheList.size() == maxCapacity) {
                cacheList.remove(cacheList.iterator().next());
            }
            cacheList.add(value);
        } else {
            cacheList.remove(cacheList.indexOf(value));
            cacheList.add(value);
        }
    }

    public static void main(String[] args) {
        List<Integer> integers = Arrays.asList(
                3, 2, 1, 0, 2, 3, 7, 4, 7        );
        LRUCache lruCache = new LRUCache(3);
        integers.forEach(e -> lruCache.get(e));
        lruCache.cacheList.forEach(System.out::print);
    }
}
In the coming days, we will optimize this approach with the reoccurrence of the least recently used in the near future.

Comments

Popular posts from this blog

Recursion

Stack

Data Structure & Algorithm