VOOZH about

URL: https://www.geeksforgeeks.org/java/implement-a-cache-eviction-policy-using-treemap-in-java/

⇱ How to Implement a Cache Eviction Policy using TreeMap in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Implement a Cache Eviction Policy using TreeMap in Java?

Last Updated : 28 Feb, 2024

To enhance application speed, caching is a method that stores frequently visited data in memory. When the cache fills up, a cache eviction policy decides which things must be removed. A sorted map implementation is provided by Java's TreeMap, which may be used to create a cache with a unique eviction strategy.

A TreeMap makes efficient retrieval and iteration possible by keeping the keys ordered. Here, we will be using a TreeMap with timestamps as keys to design a cache eviction strategy in which the oldest items are removed first.

LFU (Least Frequently Used) Cache Eviction Policy

Below is the implementation of the LFU (Least Frequently Used) Cache Eviction Policy using TreeMap in Java:


Output
Get 1: One
Get 2: null
Get 3: Three
Get 4: Four

Explanation of the Program:

  • We have implemented the usage of LFU Cache Eviction policy by adding key-value pairs and retrieving those values for different keys.
  • We have implemented a Map to store the actual key-value pair and the frequency of each key by using frequencyMap.
  • Then we have implemented a TreeMap to track efficient frequency by the use of frequencyCounter.
  • After that, by using put() and get() methods, we have added and retrieved key-value pairs to the cache.
  • Then the LFUCache class creates an object with capacity of 3, then adds and retrieves the values using get() method.
Comment