LFUCache

Introduction

LFU (least frequently used) strategy. Determines whether objects should be continuously cached based on the number of accesses (usage rate is calculated through access counts). When the cache is full, expired objects are cleaned up. If the cache is still full after cleanup, the object with the fewest accesses (the smallest access count) is removed, and the access counts of other objects are decreased by this minimum access count to allow new objects to enter and count fairly.

Usage

Cache<String, String> lfuCache = CacheUtil.newLFUCache(3);
// Create an instance of the object
// LFUCache<String, String> lfuCache = new LFUCache<String, String>(3);

lfuCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
lfuCache.get("key1"); // Access count +1
lfuCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 3);
lfuCache.put("key3", "value3", DateUnit.SECOND.getMillis() * 3);
lfuCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3);

// Since the cache capacity is only 3, when adding the fourth element, according to the LRU rule, the least frequently used one will be removed (2,3 are removed)
String value2 = lfuCache.get("key2"); // null
String value3 = lfuCache.get("key3"); // null