Thursday, 24 November 2016

Design LRU cache and explain with real time example in java

Least Recently Used Cache - The limited or LRU caching technique is used to stored only the recently used data and expires the one which is least recently used whenever the new entry into the cache.

Cache removes least recently used item while making entry for a new one.

Let's see the below scenario. In a trading system, they want to maintain the 5 recently used product to do future analysis. LRU is used in this case.

For example :  From above scenario, trading system want to store 5 recently executed product from the list of 10 products(A,B,C,D,E,F,G,H,I,J). Trading system execute first five product in the order A,B,C,D and E. The below picture depict the LRU cache
                   E -- D -- C -- B -- A  

Where 'E' is the recently used and 'A' is the least recently used. Now, trading system execute another product 'F', now LRU cache has to remove 'A' and add 'F' to the cache. Now the above cache looks like below
                   F -- E -- D -- C -- B 

What happen if trading system execute the product 'C' which is already in the LRU cache. The cache has to remove the 'C' product and add it to the beginning of the cache
                  D -- F -- E -- C -- B 

if system execute new product 'G', then B is removed.
                  G -- D -- F -- E -- C 

if system execute again product 'D' , then 'D' is removed and added to the beginning of the cache.
                   D -- G-- F -- E -- C 

if system execute new product 'H',  then 'C' is removed. Now the cache looks like below.
                    H -- D -- G-- F -- E    

By repeating the above logic, LRU store recently used 5 product in the cache.





If you like the above solution . Please share this blog

No comments:

Post a Comment

s