LRU Cache Java

In this article, we will discuss about LRU Cache implementation in Java.
 

LRU Cache

 
LRU Cache (Least Recently Used) cache is a cache-eviction algorithm that removes the least recently used element first from cache.

To implement LRU cache, we need to track the recently used item along with the age of the elements.
 
LRU Cache
 

LRU Cache in Java

 
In Java, we can use a LinkedHashMap to implement a LRU Cache.

LinkedHashMap provides a special constructor that creates a map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.
 
Here is the corresponding constructor :


LinkedHashMap(int initialCapacity, float loadFactor, boolean order) 

If order is true, it represents “Access order”, otherwise it represents “Insertion order”.
 
It also provides a removeEldestEntry() method, to remove the least recently used item from the map when new entries are added.
 
Here is the code for implementing LRU cache using LinkedHashMap :

package com.topjavatutorial;

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

public class LRUCache<K, V> extends LinkedHashMap<K, V> {

  private static float loadFactor = 0.75f;
  private static LRUCache<String,String> cache ;
  int size;

  private LRUCache(int size) {
    super(size, loadFactor, true);
    this.size = size;
  }

  public static LRUCache<String,String> getInstance(int size) {
    return new LRUCache<String,String>(size);
  }

  @Override
  protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
    return size() > size;
  }

  public static void main(String[] args) {
    cache = LRUCache.getInstance(3);
    cache.put("1", "A");
    cache.put("2", "B");
    cache.put("3", "C");
    cache.get("1");
    cache.put("4", "D");
    System.out.println(cache);
    cache.get("3");
    cache.put("5","E");
    System.out.println(cache);
  }

}

 

Output

 
{3=C, 1=A, 4=D}
{4=D, 3=C, 5=E}

 

Concurrent LRU Cache

 
The above LRU Cache implementation is not synchronized. To implement it in multi-threaded environment, we can wrap the map using Collection.synchronizedMap() method.

 

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags