Most recently used (LRU) cache

Least recently used cache collection

In order to implement cache recycling, we need to be easy to do:

  • Query the most recently used item
  • mark a recently used item

A linked list can implement these two operations. Detecting the least recently used item only needs to return the tail of the list. Marking an item as recently used simply removes it from its current location and places the item in the header. The more difficult thing is how to quickly find the item in the linked list.

Hash table help

Looking at the data structures in our toolbox, a hash table can index into an object in (consumed) constant time. If we create a hash table of the form key->linked list nodes, we can find the most recently used nodes in constant time. What's more, we can also judge whether the node exists (or does not exist) in constant time;

Once we find this node, we can move the node to the front of the list and mark it as the most recently used item.

Shortcuts for Java

As far as I know, there are very few common data structures in the standard library of a programming language that provide the above functionality. This is a mixed data structure, and we need to build a linked list based on a hash table. But Java already provides us with this form of data structure - LinkedHashMap! It even provides methods to override the recycling strategy (see removeEldestEntry documentation ). The only thing we need to pay attention to is that the order of changing the linked list is the order of insertion, not the order of access. However, there is a constructor that provides an option to use the order of access (see documentation ).

removeEldestEntry文档http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#removeEldestEntry(java.util.Map.Entry)

文档http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#LinkedHashMap(int,%20float,%20boolean)

Without further ado:

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;
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324637607&siteId=291194637