10 lines of Java code implementation recently used (LRU) Cache
In my recent interview, I was asked several times how to implement a cache with least LRU recently. The cache can be implemented through a hash table. However, increasing the size limit for this cache will become another interesting problem. Now let's take a look at how to implement it.
Minimum cache recycling recently
To implement cache collection, We need to easily:
-
Query the latest items
-
Mark recently used items
The linked list can implement these two operations. To detect the least recently used items, you only need to return the end of the linked list. To mark a recently used item, you only need to remove it from the current position and place it in the header. The difficult thing is how to quickly find the item in the linked list.
Hash Table Help
Take a look at the data structure in our toolbox. The hash table can be used to index an object within the time consumed by the constant. If we create a hash table like a key-> linked list node, we can find the most recently used node within the constant time. What's more, we can also determine whether a node exists or does not exist within the constant time );
After finding this node, we can move it to the front-end of the linked list and mark it as the recently used item.
Java shortcuts
As far as I know, few standard libraries in a programming language have a common data structure that provides the above features. This is a hybrid data structure. We need to create a linked list based on the hash table. However, Java already provides us with a data structure in this form-LinkedHashMap! It even provides methods to override the recycle policy, see the removeEldestEntry document ). The only thing we need to pay attention to is that the sequence of modifying the linked list is the order of insertion, not the order of access. However, a constructor provides an option. For the access sequence, see the document ).
Needless to say:
- import java.util.LinkedHashMap;
- import java.util.Map;
-
- public LRUCache<K, V> extends LinkedHashMap<K, V> {
- private int cacheSize;
-
- public LRUCache(int cacheSize) {
- super(16, 0.75, true);
- this.cacheSize = cacheSize;
- }
-
- protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
- return size() >= cacheSize;
- }
- }