LRU cache implementation in java

If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.

In this post, we will see LRU cache implementation in java.


Problem

Design a Least recently used cache implementation in java. It should have below properties.

bounded size: It should have bounded size to take care of memory limits.

Fast access: As we are designing cache, we should be able to fetch or update entries faster.

Evict least recently used entry: Cache should evict least recently used entry if capacity is reached.


Solution

Using HashMap and Doubly linked list

As we need to do lookup in O(1) time then HashMap is obvious choice but we need to take care of least recently used entry as well.

We need to find a data structure which can remove/add in O(1) time if we already know the node. We can use a double linked list for this purpose because it provides removal/addition in O(1) time if already know about the node.

HashMap will make get operation in O(1) time and Doube linked list will make removal/addition in O(1) time.

LRU cache

 

Here is simple program for LRU cache implementation in java.

When you run above program, you will get below output:

94
97
-1

As you can see, in last 4 entries, we do not have 15 as key. That’s the reason we are getting -1 for it.

Using LinkedHashMap

We can use LinkedHashMap to create LRU cache as well. LinkedHashMap has a constructor in which you can specify access order. If you pass accessOrder as true, LinkedHashMap will work on the basis of access order rather than insertion order.

We will also override a method named removeEldestEntry() and it will return true in case size() is greater than capacity.

Let’s create a class Named LRUCache

When you run above program, you will get output:

94
97
-1

As you can see, in last 4 entries, we do not have 15 as key. That’s the reason we are getting -1 for it.

That’s all about LRU cache implementation in java.

Was this post helpful?

Comments

  1. I am big fan of your blog. It has best interview preparation and concepts learning materials. Please keep adding more design implementations that’s been frequently asked in interviews these days. Thanks for your effort:)

Leave a Reply

Your email address will not be published. Required fields are marked *