Implementing a Least-Recently-Used(LRU) Cache

In this section, you will learn about the least-recently- used(LRU) cache in Java.



How to read properties file in Java? Generate random numbers in Java Cloneable Interface in Java What is the flaw with the Stack class? List In Java Java Stack Example HashSet In Java Enumeration in java How to generate random number in java Iterator in java Queue in java Transient Java Keyword clone method in Java Java Queue example Logger in Java Java current date - How to get current date in Java Collection : LinkedList Example Collection : ArrayList Example Random alpha numeric string of fixed size Java List Iterator Example The Hashtable Class The BitSet class Java Vector Java Enumeration Data Structures in Java Java Transient Variable Java Date Format Example Java Properties File Example Map.Entry Java Interface Java Property File java preferences,Change the value of Preferences by user Retrieving a Preference Node Java hasNext Write Keys and Values to the Properties file in Java Get All Keys and Values of the Properties files in Java Properties file in Java Properties file in Java Determining If a Preference Node Contains a Specific Value Change the value of Preferences by user Clone method example in Java Implementing a Simple Event Notifier Determining When a Preference Node Is Added or Removed Listening for Changes to Preference Values in a Preference Node Importing Preferences Finding a Preference in a Preference Tree Retrieving the Parent and Child Nodes of a Preference Node Determining If a Preference Node Exists Removing a Preference Node Creating a Preference Node Getting the Maximum Size of a Preference Key and Value

Implementing a Least-Recently-Used(LRU) Cache


In this section, you will learn about the least-recently- used(LRU) cache in Java. LRU Cache helps you how to use the buffer and how to limit or fixed the size of buffer and how to manage storing and retrieving process of the buffer which size is limited.

In this section, you can create a LRU(least-recently-used) Cache and manage it efficiently. Here the given program takes a in numeric input to fix the size of the LRU Cache. If your entry exceeds the size of the LRU Cache the the eldest element with key is removed. LRU Cache is implemented through the LinkedHashMap class. LinkedHashMap holds values with unique key. You you store values with a duplicate key then the LinkedHashMap replace the old value of that key with the new value of the key.

Code Description:

This program shows the object keys and values by using the LRU cache. Many methods and APIs which have been used in the following program are explained as follows:

This is the class of the java.util.*; package. This class is also used for the implementing the doubly linked list which tracks either insertion or access order. The put() method is used for the insertion process to the LinkedHashMap with the value and the unique key regarding the value.

put(Object key, Object value):
This method has been used to add a value with it's unique key in the LRU Cache. This method of the LinkedHashMap class takes two argument in which first is the key and another is the value for the specified key.

This interface returns the view of map of collection . The Map.Entry objects are valid only to the duration of the iteration. This is the nested class of the Map class from the java.util.*; package.

Above method of the Map.Entry class which returns the key corresponding to the value. Here 'e' is the instance of the Map.Entry class.

Above written is also a method of the Map.Entry class which returns the value corresponding to the key of the index of the LRU Cache. 

Here is the code of program:

import java.util.*;

public class LRUCacheExample {
  int num = 0;
  LinkedHashMap<String,String> map;
  public static void main (String[] argsthrows IOException{
  LRUCacheExample lruCache = new LRUCacheExample();

  public LRUCacheExample() throws IOException{
  System.out.print("Please enter the size of the LRU Cache: ");
  BufferedReader in = new BufferedReader(new InputStreamReader(;
  num = Integer.parseInt(in.readLine());
  catch(NumberFormatException ne){
  System.out.println(ne.getMessage() " is not a legal entry!");
  System.out.println("Please enter a numeric value.");
  map = new LinkedHashMap<String,String>() {
  public boolean removeEldestEntry (Map.Entry<String,String> eldest){
  return size() > num;
  String ch = "N";
  System.out.print("Enter key: ");
  String str = in.readLine();
  System.out.print("Enter value: ");
  String str1 = in.readLine();
  map.put (str, str1);
  System.out.print("Do you want to stop the entry(Y/N)?");
  ch = in.readLine();
  for (Map.Entry<String,String> e : getAll())
  System.out.println (e.getKey() " : " + e.getValue());

  public synchronized Collection<Map.Entry<String,String>> getAll() {
  return new ArrayList<Map.Entry<String,String>>(map.entrySet());

Download this example


Share on Google+Share on Google+

Implementing a Least-Recently-Used(LRU) Cache

Posted on: April 16, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Implementing a Least-Recently-Used(LRU) Cache   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
August 4, 2014
Too many typos.

Please proofread your text before posting. The number of typos on this website is too damn high.