Can't write to Lru cache? Look at Mybatis

Lru (least recently used) is the least recently used. It is often used in the cache elimination mechanism. When the cache capacity is insufficient, the least active caches are eliminated first. What is the least active? This of course refers to the least recently used cache.

The most basic operation of the cache is put/get, and the Cache interface defines the cache standard.

public interface Cache {
    
    
  String getId();
  void putObject(Object key, Object value);
  Object getObject(Object key);
  Object removeObject(Object key);
  void clear();
  int getSize();
}

The implementation of Lru in Mybatis is with the help of LinkedHashMap, which can easily realize that the cached Entry follows the access-order access sequence, and can easily delete the most outdated Entry of eldestEntry. When the cache capacity exceeds the initial capacity, find the oldest Entry and delete it from the cache.

public LruCache(Cache delegate) {
    
    
  this.delegate = delegate;
  setSize(1024);
}
public void setSize(final int size) {
    
    
  keyMap = new LinkedHashMap<Object, Object>(size, .75F, true) {
    
    
      private static final long serialVersionUID = 4267176411845948333L;
    @Override
    protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
    
    
      boolean tooBig = size() > size;
      if (tooBig) {
    
    
        eldestKey = eldest.getKey();
      }
      return tooBig;
    }
  };
}

Seeing that this is a bit fascinating, this is just the realization of the Lru cache elimination mechanism. Where is the real cache access? Mybatis provides us with a default cache implementation method, which also uses map to access the cache key/value.

public class PerpetualCache implements Cache {
    
    
  private final String id;
  private Map<Object, Object> cache = new HashMap<>();
}

The basic idea is to use HashMap to store the cache key/value, use LinkedHashMap to record the oldest Entry, and delete the oldest Entry when the cache capacity reaches the initial capacity.

I find it useful, just pay attention. Welcome to pay attention to the public account of the same name [Ma Nong Wheat], thank you Lao Tie.

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43275277/article/details/115352559